What is the problem with this for loop in python? - python-3.x

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.

Related

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.(I am not getting what is wrong in this code)

sum = 2
x=3
y=5000
for i in range (x,y):
for j in range (2,i):
if i%j==0:
break
elif i%j!=0 and j==i-1:
sum += i
if i==y-1 and y<2000000:
x=y
y+=5000
else:
continue
print(sum)
**I am not getting what is wrong in this code. By running this I came to know that the Last If and Else statement are not running **
Given your code, there are a couple of things wrong. First, sum is a python function name and should never be used as a variable name. It will get you into trouble in more ways than I care to think about. Second, the last else statement is not needed, because whether the if clause above it is or is not executed executed, the for loop will be executed again. Third, I don't understand the purpose of y and the magical value 5000, unless you are trying to provide an end value for your loop. The problem with this approach is you seem to try and extend it's range in increments of 5000. The problem is that once the initial for loop is executed, it creates a local iterable from x to 5000, and subsequent changes to y do not affect the for loops range.
I would approach the problem differently, by creating a list of primes and then use the python sum method to add all the values. Here is the code:
def sum_primes(max_prime):
""" Return Sum of primes Less than max_prime"""
primes = [2]
indx_num = 3
while primes[-1] <= max_prime:
update = True
for prime in primes:
if indx_num == prime or indx_num % prime == 0:
update = False
break
if update:
primes.append(indx_num)
indx_num += 2
#return summ of all values except the last
return sum(primes[:-1])
Executing sum_primes(2000000)
yields 1709600813

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)

the prisoner box problem, simulating the solution

I am trying to write code to simulate the prisoners going to the box labeled with their number, then to the box that the ticket inside send them too and so on.
I'm getting a list index out of range error but not sure if the code is even right anyway
total = 0
for s in range(100):
prisoners = []
boxes = []
counter = 0
winners = 0
number = 0
for i in range(1, 101):
prisoners.append(i)
#print(prisoners)
for x in range(1, 101):
boxes.append(x)
shuffle(boxes)
#print(boxes)
while counter!=99:
for h in range(1, 51):
if prisoners[counter] == boxes[number]:
print("winner")
winners +=1
counter +=1
break
else:
number = boxes[number]
print("loser")
The issue is you store boxes numbers as range [1,100], but use them as indices of 100-long array (0-99), so when it runs number = boxes[number] it sometimes assigns number to be 100 and causes error.
One way to solve it is make it number = boxes[number] - 1.
Another is use 0-99 ranges in logic, but add 1 if you want to print them.

Number of Combinations to make change with coins

We have unlimited coins of different values - Calculate the unique combinations of how these coins can make up a specific amount. For example:
n = 4 (say, 4 cents)
coins_list = [1,2] - we have 1-cent coins, and 2-cent coins
The different combinations would be 112, 1111, and 22. (121 and 211 should be excluded since it's not unique - using one 2-cent coin and two 1-cent coin)
I have watched this video: https://www.youtube.com/watch?v=k4y5Pr0YVhg
countless number of times, and edited my codes countless number of times, but I cannot manage to get rid of the same combination of different orders.
def make_change(n, coinlist_index=None):
coin_list = [1, 2]
if coinlist_index == None:
coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins
if n == 0:
return 1
if n < 0:
return 0
ways = 0
# if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
for coinlist_index in range(len(coin_list)):
ways += make_change((n - coin_list[coinlist_index]), coinlist_index)
coinlist_index += 1
return ways
make_change(4)
Output: 5
My output was 5 (different ways to make change for 4 cents with 1 and 2-cent coins), instead of 3 (which is what I want).
I'm sure it has to do with the for loop toward the end, but when i change "for coinlist_index in range..." to a different iterator, i, I get an error that says index is out of range.
What is going on, and more importantly, how can I fix it?
EDIT: P.S. This is just a simple example that I'm working through to solve the actual assignment - Which is with 6 types of coins, in cents, (1, 5, 10, 25, 50, 100), and calculate how many ways to make change for 200 dollars. I have seen and tried the dynamic programming method out there, which worked, but we have to use recursion for assignment purposes.
Looks like I got it working. In each recursive pass you want to make sure that you aren't double counting possible ways to make the change. My thought to do this was to make sure that you never go backwards in the coin_list. So for the coin_list [1,2] if we ever use the 2 cent coin we never want the option to use the 1 cent coin afterwards. I made sure it follows this order by changing your for loop a bit:
for i in range(len(coin_list)-coinlist_index):
ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)
In the for loop I subtracted coinlist_index from the upper bound so we don't cycle over all coins once the index reaches 1, then added the index to where you pull from the coin_list, making sure once coinlist_index is 1 or more, we NEVER usecoin_list[0]. This got me to 3 in your sample case, hopefully it works for all cases. Full code:
def make_change(n, coinlist_index=None):
coin_list = [1, 2]
if coinlist_index == None:
coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins
if n == 0:
return 1
if n < 0:
return 0
ways = 0
# if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
for i in range(len(coin_list)-coinlist_index):
ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)
coinlist_index += 1
return ways
print(make_change(4))
I feel 5 is actually the correct answer.
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2
Or if you want distinct result, you may store results in the list and remove the duplicate result.
def make_change(n, coinlist_index=0):
coin_list = [1, 2]
if n == 0:
return [[]]
if n < 0:
return []
ways = []
for coinlist_index in range(len(coin_list)):
res = make_change((n - coin_list[coinlist_index]), coinlist_index)
ways += list(map(lambda x : x + [coin_list[coinlist_index]], res))
return ways
def remove_dup(lolist):
res = []
for lst in lolist:
lst.sort()
if lst not in res:
res.append(lst)
return res
print remove_dup(make_change(4))

python 3.x for loop not stopping at desired value

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))

Resources