python 3.x for loop not stopping at desired value - python-3.x

i'm reading a beginners book written in Python 2.x but I decided to follow it using 3.5
the book is about data wrangling and while reading an Excel file using the library xlrd it gives a quick example of how Counters work:
count = 0
for i in range(1000):
if count < 10;
print i
count += 1
print 'Count: ', count
first of all, i know in Python 3.x print is actually print() and i also learned that in 2.x range(1000) IS NOT the same in 3.x
so i managed to run the code without errors but not with the desired result:
count = 0
my_list = list(range(1000))
for i in my_list:
if count < 50:
print(i)
count += 1
print(count)
the result were the numbers from 1001 to 2000. clearly not what i meant it to do, so it made my think if the += was the same for 3.x but couldnt find much information, so i tried the (at least to me) logical way:
count = 0
my_list = list(range(1000))
for i in my_list:
if count < 50:
print(i)
count = count + 1
print(count)
but now the result are all numbers from 0 to 1000 BUT all numbers from 1 to 49 are repeated once. so i changed count for just i but made no difference.
clearly none of my attempts stopped at 50...
i appreciate all input in advance

I think your confusion is originating from increment-ing count at the end of your for loop.
the way you have it written if you do for k in range(5) ... counter will increment from 0 all the way up to 5, because it increments once past it's value on each iteration.
Running this code will sow that count counts higher than your itterating variable k in the loop.
print ("Hello World!");
count = 0
for k in range(5):
print("k: "+str(k))
print("count: "+str(count))
count+=1
print("countNow: "+str(count))

Related

How to extract numbers with repeating digits within a range

I need to identify the count of numbers with non-repeating digits in the range of two numbers.
Suppose n1=11 and n2=15.
There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.
Wrote this code:
n1=int(input())
n2=int(input())
count=0
for i in range(n1,n2+1):
lst=[]
x=i
while (n1>0):
a=x%10
lst.append(a)
x=x//10
for j in range(0,len(lst)-1):
for k in range(j+1,len(lst)):
if (lst[j]==lst[k]):
break
else:
count=count+1
print (count)
While running the code and after inputting the two numbers, it does not run the code but still accepts input. What did I miss?
The reason your code doesn't run is because it gets stuck in your while loop, it can never exit that condition, since n1 > 0 will never have a chance to be evaluated as False, unless the input itself is <= 0.
Anyway, your approach is over complicated, not quite readable and not exactly pythonic. Here's a simpler, and more readable approach:
from collections import Counter
n1 = int(input())
n2 = int(input())
count = 0
for num in range(n1, n2+1):
num = str(num)
digit_count = Counter(num)
has_repeating_digits = any((True for count in digit_count.values() if count > 1))
if not has_repeating_digits:
count += 1
print(count)
When writing code, in general you should try to avoid nesting too much stuff (in your original example you have 4 nested loops, that's readability and debugging nightmare), and try using self-describing variable names (so a, x, j, k, b... are kind of a no-go).
If in a IPython session you run import this you can also read the "Zen of Python", which kind of sums up the concept of writing proper pythonic code.

What is the problem with this for loop in python?

I want to create a function to calculate the sum of number which are multiples of 3.
What is the problem here, because I get numbers repeated 3 times until I get to 18, which is out of range. I don't understand.
summ = 0
for n in range(10):
if n % 3 == 0:
summ = summ+n
print(summ)
Try:
summ = 0
for n in range(10):
if n % 3 == 0:
summ = summ+n
print(summ)
Your code print(summ) is inside the loop, meaning it will print multiple times (as many times as the loop runs). Moving it outside of the loop will only make it print once after the loop is done running.

python return / print highest number of value in a row in a list

I am a beginner.
Trying to make a function that can return the highest number in a row a value in a list was picked.
Basicly I want to simulate a head or tails game, and find out how many times in a row it was for example tails.
import random
def simulations(runs):
sequence = []
in_a_row = []
tæller = 0
for run in range(0, int(runs)):
my_random = random.randint(0,1)
sequence.append(my_random)
if my_random == 0:
in_a_row.append(my_random)
tæller = tæller + 1
print()
elif my_random == 1:
tæller = 0
in_a_row = []
print()
print(f'{tæller}')
print(sequence)
# runs = input('How many simulations do you want to run ? ')
runs = 10
simulations(runs)
I think I am almost there. But I cant figure it out, when I run this code I first print the actual value that was picked, and then see the list that was created so far.
if for example my_random == 0 3 times in a row it will print each time it was 0 until it picks 1.
Want i want is for the code to print only the longest sequence where 0 was picked in the entire list
I know my code is spagetti, and the function is not finished, but i belive I can do that by myself. I just need some help with isolating the number of times a given value was picked in a row from the list.
Hmm I think I was finally able to create a solution by myself.
So happy i think i spend like 5 hours trying to figure it out.
Here is my solution. I would still appriciate it a lot if someone can comment on my solution, and maybe show another more simple way of doing it :-)
import random
def simulations(runs):
sequence = []
in_a_row = []
found_zero = 0
all_time_high = [0]
for run in range(int(runs)):
my_random = random.randint(0,1)
sequence.append(my_random)
if my_random == 0:
in_a_row.append(my_random)
found_zero = found_zero + 1
print(f'fundet 0 ja: {found_zero} Gange')
all_time_high.append(found_zero)
elif my_random == 1:
found_zero = 0
in_a_row = []
print()
print(sequence)
print(f'Higest number of times in a row zero was found: {max(all_time_high)}')
# runs = input('How many simulations do you want to run ? ')
runs = 10
simulations(runs)

Equivalent while loop block for a for loop block

I am a novice trying to learn python from Automate The Boring Stuff with Python by Al Sweigart and I came across his block of code to answer a math problem: "What is the sum of all the numbers from 0 to 100?" Apparently, this was a question Gauss got when his teacher wanted to keep him busy.
Sweigart used a for loop and range() function to get the answer:
total = 0
for num in range(101):
total=total+num
print(total)
A page later he states that "you can actually use a while loop to do the same thing as a for loop; for loops are more concise."
How would this statement be rendered in a while loop?
I tried replacing the for with while but got an error: "name 'num' is not defined." I also tried to set up a summation math equation using another block of code from another forum, but completely got lost.
print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
a=[1,2,3,4,5,...,100]
i=0
while i< len(a)-1:
result=(a[i]+a[i+1])/2
print(result)
i +=1
Then, I tried to setup i in an equation that would loop until each number was added, but got stuck.
print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
i=0
while i<101:
i=i+1
a=i
Would the while statement be too complex to warrant the effort?
Your last example comes close.
A for loop of this form:
for x in range(N):
# ...
can be replaced by a while loop like this:
x = 0
while x < N:
# ...
x += 1 # equivalent to x = x + 1
Just make sure you leave the rest of the code unchanged!
The for loop is more concise. Notice how we need a "counter" variable , in this case i with the while loop. That's not to say we don't need them in a for loop, however they're integrated nicely into the syntax to make for cleaner code.
i = 0
total = 0
while i < 101:
total += i
i += 1
print(total)
Python's for loop syntax is also a foreach equivalent:
for eachItem in list:
# Do something

Regex Output Count

I am trying to count the output of a regex search I am conducting on a dataset but for some reason my count is off by a lot. I was wondering what I am doing wrong and how I can get an official count. I should have around 1500 matches but I keep getting an error that says "'int' object is not iterable".
import re
with open ('Question 1 Logfile.txt' , 'r') as h:
results = []
count = []
for line in h.readlines():
m = re.search(r'(((May|Apr)(\s*)\w+\s\w{2}:\w{2}:\w{2}))', line)
t = re.search(r'(((invalid)(\s(user)\s\w+)))',line)
i = re.search(r'(((from)(\s\w+.\w+.\w+.\w+)))', line)
if m and t and i:
count += 1
print(m.group(1),' - ',i.group(4),' , ',t.group(4))
print(count)
You want to increment the number of times you satisfy a condition over a series of loop iterations. The confusion here seems to be how exactly to do that, and what variable to increment.
Here's a small example that captures the difficulty you've encountered, as described in OP and in OP comments. It's meant as a learning example, but it does also provide a couple of options for a solution.
count = []
count_int = 0
for _ in range(2):
try:
count += 1
except TypeError as e:
print("Here's the problem with trying to increment a list with an integer")
print(str(e))
print("We can, however, increment a list with additional lists:")
count += [1]
print("Count list: {}\n".format(count))
print("Most common solution: increment int count by 1 per loop iteration:")
count_int +=1
print("count_int: {}\n\n".format(count_int))
print("It's also possible to check the length of a list you incremented by one element per loop iteration:")
print(len(count))
Output:
"""
Here's the problem with trying to increment a list with an integer:
'int' object is not iterable
We can, however, increment a list with additional lists:
Count list: [1]
Most common is to increment an integer count by 1, for each loop iteration:
count_int: 1
Here's the problem with trying to increment a list with an integer:
'int' object is not iterable
We can, however, increment a list with additional lists:
Count list: [1, 1]
Most common is to increment an integer count by 1, for each loop iteration:
count_int: 2
It's also possible to check the length of a list you incremented
by one element per loop iteration:
2
"""
Hope that helps. Good luck learning Python!

Resources