Update list in for loop using list.append - python-3.x

The variable mult is not updated as the program runs. What is the issue with this code? The run results show me that the loop is actually working as I wanted but for the list update and final print
number = 18
for i in range(int(number/2)):
i += 1
mults = []
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
elif i == int(number/2):
print(mults)
with this other code I get the error: AttributeError: 'NoneType' object has no attribute 'append'
number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)

number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)
Few notes, move mults outside of the for loop so you aren't over writing it every time the loop runs.
You don't need that last elif statement, just print(mults) when the for loop is done, is basically the last elif statement.
mults.append(i) is in line meaning it changes the list mults automatically and you don't need to reassign it.

Related

CODEFORCES 1744B, how could I fix runtime error?

I'm trying to solve the next problem: https://codeforces.com/contest/1744/problem/B
When I run the code in my terminal, it works with the example given in the exercise; but it doesn't when I submit it in CodeForces, it cause a runtime error which I cannot figure out.
def increment(arr, length, option, add):
for i in range(length):
if(option == '0') and (arr[i]%2 == 0):
arr[i] += add
elif(option == '1') and (arr[i]%2 != 0):
arr[i] += add
else:
pass
return arr
def main():
quantityOperation = int(input())
while quantityOperation > 0:
length, times = input().split()
length = int(length)
times = int(times)
arr = [int(x) for x in input().split()]
while times > 0:
opt, add = input().split()
add = int(add)
res = sum(increment(arr, length, opt, add))
print(res)
times -= 1
quantityOperation -= 1
main()
The loop inside your main function doesn't end. You should put quantityOperation -= 1 inside the while loop.
However, your code will still become time limit exceeded after fixing this. The correct idea is to precalculate odd and even sum and modify them according to the queries instead of looping all elements inside increment function every time. You can check the editorial for this problem.

A function to manipulate strings ad numbers

I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo”
instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.
i = 0
while I < 100:
i += 1
print(i)
if i == 3:
print("Foo")
You will have to use mod (%) to check the remainder of a division.
See if i % 3 is equal to 0. If this is true, then print FOO.
If i % 5 equal 0, print Bar; and so on.
I would recommend using an if else statement in your while loop after the index counter. Something like...
i = 0
while i <= 100:
i += 1
if i % 15 == 0:
print("foobar")
elif i % 3 == 0;
print("foo")
elif i % 5 == 0:
print("bar")
else:
print(i)
Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.
i = 0
while i < 100:
i += 1
if i%15 == 0:
print('FooBar')
elif i%3 == 0:
print('Foo')
elif i%5 == 0:
print('Bar')
else:
print(i)
Apply if and else statement to decide which is the situation during the while loop.
Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.

Why this script doesn't run after the first line

tweak = int(input("Input an integer"))
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print(number)
collatz(tweak)
If you are trying to implement a Collatz conjecture script, then your first if is wrong - you should divide the number by 2. Also, your return causes the function to end, so you get only one while loop, doesn't matter what happens inside - so you basically return the number you inputed or that number * 3 + 1.
Here is the correct code with slight modifications:
tweak = int(input("Input an integer"))
def collatz(number):
steps = 0
num = number
while number != 1:
if number % 2 == 0:
number = number / 2
else:
number = int(3 * number + 1)
steps +=1
print("Reached 1 in {} iterations for number {}.".format(steps, num))
collatz(tweak)
You also don't need the elif, because number can only be dividable by 2 or not.
Example outputs:
collatz(22)
collatz(55)
collatz(234)
Reached 1 in 15 iterations for number 22.
Reached 1 in 112 iterations for number 55.
Reached 1 in 21 iterations for number 234.
Your question has only code, but I think this is what you might be looking for:
def collatz(tweak):
while tweak != 1:
if tweak % 2 == 0:
return int(tweak)
elif tweak % 2 != 0:
return int((3 * tweak) + 1)
print(tweak)
tweak = int(input("Input an integer:"))
result = collatz(tweak)
print(result)
Your returning values in if and else so it wont print beyond..
instead assign it in variable and do print..
tweak = input("Input an integer")
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print number # this wont work.. your returned already
print "output:%s"%collatz(tweak)
output:
me#dev-007:~/Desktop$ python test.py
Input an integer10
number 10
output:10

who to pass index of a loop (for loop) in python

I put this pre defined part in my python code, the aim of code is to get last 2 digits and put it on cluster list based on the predefined logic in cluster (index as list[1] and variable of index in cluster(2).
Now I have problem with my loop that says there are indentation error.
def find_min(matrix=[]):
i,j=0,0
min1=[1000,0,0]
while i <len(matrix):
while j <len(matrix):
if matrix[i][j] != 0:
if min1[0]>matrix[i][j]:
min1[0]=matrix[i][j]
min1[1]=i
min1[2]=j
j+=1
j=0
i+=1
return min1[1:]
def check_min(variable,list2=[]):
i=0
min=1000
list3=list2[:]
result=0
while i<len(list3):
if variable-list3[i]>0:
result=variable-list3[i]
list3[i]=result
else:
result=list3[i]-variable
list3[i]=result
i+=1
i=0
while i<len(list3):
if min>list3[i]:
min=list3[i]
i+=1
return min
def grouped(variable,cluster=[]):
cluster1=cluster[:]
k=0
list3=[]
index=0
while k<3:
index=k
if variable in cluster1[index]:
list3.append(1)
list3.append(cluster[index])
return list1
else:
continue
K+=1
return [0,-1]
list1=[10,11,30,40,70,80]
cluster=[[0,1][10,11],[2,3],[30,40],[],[]]
Then I want to have this loop to work but it shows me idiot errors!
w, h = len(list1), len(list1)
matrix = [[None for x in range(w)] for y in range(h)]
i,j,z=0,0,0
check=0
check2=0
k,e=0,0
flag1=0
index1,index2=0,0
index_i=0
index_j=0
index_cluster_i=0
index_cluster_j=0
temp1=[]
while i <len(list1):
index1=i
while j <len(list1):
index2=j
#if i is in a cluster already
temp1=grouped(index1,cluster)
index_i=temp1[0]
index_cluster_i=temp1[1]
#if j is in a cluster already
temp1=grouped(index2,cluster)
index_j=temp1[0]
index_cluster_j=temp1[1]
if(i>j):
matrix[i][j]=0
elif (index_i==1 and index_j==1):
matrix[i][j]=0
elif(index_i==1 and index_j==0):
matrix[i][j]=check_min(list1[j],cluster[index_cluster_i])
elif(index_i==0 and index_j==0):
if list1[i]>list1[j]:
matrix[i][j]=list1[i]-list1[j]
else:
matrix[i][j]=list1[j]-list1[i]
j+=1
i+=1
error is:
unindent does not match any outer indentation level
This error is for improper indentations align each block under its statement.
Like:
if i === True:
pass
else:
pass

FizzBuzz with commas instead of newlines

def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i))
Where and how would do a new line command here with commas?
Trying to get an output like this: 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19, Buzz
but sideways and with commas.
Pass end=',' to print()
def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i), end=',')
# prints
1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,
If you do not want the trailing comma, end the range at 20 and follow with print(fizz_buzz(20))
Consider making a list & joining the elements with a comma. There are some great examples here.
For example:
def fizz_buzz(i):
# your code
my_list = []
for i in range(1,21):
my_list.append( str(fizz_buzz(i)) )
print ",".join(my_list)
There are more elegant ways of doing this -- using generators &c, as in the linked answer --, but this simple code will do what you want. Note that the join() method accepts string only, hence the str() in the list.append(); alternatively you could ensure that your fizz_buzz function returns strings regardless.

Resources