Appending numbers to emptylist - python

im trying to return the divisors of 2 numbers that i appended to an empty list. why is nothing being printed? im expecting for 1,2,3 to be returned to mw but i get returned "[]" and "none"
def fun (t,g) :
list1 = []
i = 1
r = 1
while i < t :
if i % t == 0 :
list1.append(i)
i = i + 1
while r < g :
if r % g == 0 :
list1.append(r)
r = r + 1
print list1
x = 4
y = 6
t = fun(x,y)
print t

i % t is never 0 since you are exiting the while loop when i == t. Perhaps you meant t % i?
Likewise for r and g.
Your function doesn't have a return so it will implicitly return None
You should add return list1 to the end of it.
def fun (t,g) :
list1 = []
i = 1
r = 1
while i < t :
if t % i == 0 :
list1.append(i)
i = i + 1
while r < g :
if g % r == 0 :
list1.append(r)
r = r + 1
print list1
return list1
x = 4
y = 6
t = fun(x,y)
print t
prints
[1, 2, 1, 2, 3]
[1, 2, 1, 2, 3]
So you still need to work out the duplicates

Related

remove commas , and [ ] from a list python 3

I have a this funtion
n=5
nums=5 1 4 2 3
def LIS(nums, n):
dp = []
dp_list = []
for i in range(n):
dp.append(1)
dp_list.append([nums[i]])
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
if len(dp_list[i]) <= len(dp_list[j]):
dp_list[i] = dp_list[j] + [nums[i]]
print(dp_list[dp.index(max(dp))])
return dp_list
And I get this result:
[1, 2, 3]
But I wan something like this as result
1 2 3
I have tried using this, but the result still been the same
values = ''.join([str(i) for i in LIS(nums,n)])
print(*dp_list[dp.index(max(dp))])

Converting "for loop" to "while loop" in python

I am trying to convert the code by replacing for loop with while loop.
This is the code which I want to be converted
Functions for the code in the below snippet. Asked by #Sameer
from random import sample
def shuffle(s): return sample(s,len(s))
rBase = range(base)
base = 2
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
Code in which I have the problem
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
Here is my attempted code
rows = []
cols = []
data = []
s = shuffle(rBase)
i,j = 0,0
while i < len(s):
r = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
rows.append(g*base+r)
j+=1
i += 1
i,j = 0,0
s = shuffle(rBase)
while i < len(s):
c = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i,j =0,0
while i < len(rows):
r = rows[i]
while j < len(cols):
c = cols[i]
data.append(nums[pattern(r,c)])
j += 1
i += 1
Some part of the code is omitted due to privacy reasons.
Expected output, ie output of for loop snippet is a list with length (base ** 4) containing each number from 1 to base ** 2 exactly base ** 2 times.
For Eg:
if base is 2:
expected output would be like [3, 2, 1, 4, 4, 1, 3, 2, 1, 4, 2, 3, 2, 3, 4, 1]
Actual output is a list of length base with each element is a random number between 1 and base ** 2.(Including base ** 2)
For Eg:
if base is 2:
Actual output is like [1,1] or [2,2] or [3,3] or [4,4]
Variable j = 0 should be defined before the inner while loop. Currently, your inner while is running 'len(s)' times only also you are indexing with 'i' in your second loop, you should have used j there.
This Should Work
from random import sample
def shuffle(s): return sample(s,len(s))
base = 2
rBase = range(base)
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
print(rows)
print(cols)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
print(data)
rows = []
cols = []
data = []
s = shuffle(rBase)
s2 = shuffle(rBase)
i = 0
while i < len(s):
r = s[i]
j = 0
while j < len(s):
g = s2[j]
j = j + 1
rows.append(g*base+r)
i = i + 1
i = 0
s = shuffle(rBase)
s2 = shuffle(rBase)
while i < len(s):
c = s[i]
j = 0
while j < len(s):
g = s2[j]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i =0
while i < len(rows):
r = rows[i]
j = 0
while j < len(cols):
c = cols[j]
data.append(nums[pattern(r,c)])
j += 1
i += 1
print(rows)
print(cols)
print(data)

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

Trying to outputting a math equation with for loop in python

So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:
z= 1
while z > 0:
for i in range(len(list)):
print(list[i],"+", end=" ")
z = 0
print("=",sum(list),end=" ")
This is what i am trying and output is:
2 + 5 + 6 + 9 + 1 + = 23
What should I do if I want to output n integers and n-1 plus signs between integers?
You may use str.join that accept an iterable of strings. You need to map each int to str then join them using the + and print the result
values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values)) # 2 + 5 + 6 + 9 + 1 = 23
# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)
Use join:
def printfn(alist):
expr = " + ".join((map(str, alist)))
sum_val = sum(alist)
print("{} = {}".format(expr, sum_val))
a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6
b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10
Another possibility is to use sep= parameter of print() function.
For example:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
Prints:
2 + 5 + 6 + 9 + 1 = 23
You can use enumerate(), starting with an index of 1
>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
if i == len(l):
# If the current item is the length of the list then just append the number at this index, and the final sum
s += str(v) + ' = ' + str(sum_)
else:
# means we are still looping add the number and the plus sign
s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23
Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0
list = [2,5,6,9,1]
z= 1
while z > 0:
for i in range( len(list)-1 ):
print(list[i],"+", end=" ")
print (list[len(list)-1],end=" ")
print("=",sum(list),end=" ")
z = 0

Python- Solving code by hand? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My professor wants us to solve this code and several other ones that are similar by hand. Since I'm new to programming I have no clue how to do that at all and I'm completely lost
num = 0
for i in range(2,5):
for j in range(-1, 1):
num = num*j + i
print("i =", i, "j =", j, "num =", num)
I take a stab at this.
for i in range(2,5):
for j in range(-1, 1):
translates to
2
-1, 0
3
-1, 0
4
-1, 0
Why? the for loop says "For each number in the range of 2 to 5 (not including 5) do SOMETHING"
That something is another loop.
"For the number 2, give me the range of -1 to 1 (not including 1).
After that its just some basic math.
num = 0 * -1 + 2 = 2 (new value of num is now 2, not the original 0, remember this going to next iteration)
num = 2 * 0 + 2 = 2
num = 2 * -1 +3 = 1
etc
I would do it this way.
This is your code:
num = 0
for i in range(2,5):
for j in range(-1, 1):
num = num*j + i
print("i =", i, "j =", j, "num =", num)
range(2, 5) = [2, 3, 4] and range(-1, 1) = [-1, 0], So:
num = 0
for i in [2, 3, 4]:
for j in [-1, 0]:
num = num*j + i
print("i =", i, "j =", j, "num =", num)
Now for the first iteration, i = 2, j = -1 and num = 0, So:
num = 0 * -1 + 2 = 0 + 2 = 2
^ ^ ^
| | |
num j i
So, the print statement print("i =", i, "j =", j, "num =", num) would print the following:
"i = 2 j = -1 num = 2"
For the second iteration, i = 2, j = 0 and num = 2, So:
num = 2 * 0 + 2 = 0 + 2 = 2
^ ^ ^
| | |
num j i
So, the print statement print("i =", i, "j =", j, "num =", num) would print the following:
"i = 2 j = 0 num = 2"
For the third iteration, i = 3, j = -1 and num = 2, So:
num = 2 * -1 + 3 = -2 + 3 = 1
^ ^ ^
| | |
num j i
So, the print statement print("i =", i, "j =", j, "num =", num) would print the following:
"i = 3 j = -1 num = 1"
Altogether your print statements would look like this:
"i = 2 j = -1 num = 2"
"i = 2 j = 0 num = 2"
"i = 3 j = -1 num = 1"
"i = 3 j = 0 num = 3"
"i = 4 j = -1 num = 1"
"i = 5 j = 0 num = 4"
Here is how I would follow the program:
#A
num = 0
#B
for i in range(2,5):
for j in range(-1, 1):
#C
num = num*j + i
#D
print("i =", i, "j =", j, "num =", num)
#E
A: num is undefined, i is undefined, j is undefined.
B: num is 0, i is undefined, j is undefined.
C: num is 0, i is 2, j is -1.
D: num is 2, i is 2, j is -1.
E: same as D, but this just got printed: i = 2, j = -1, num = 2
C: num is 2, i is 2, j is 0.
...

Categories

Resources