Error with len() function or something else? - python

So I've been trying to get my program to loop through this pke equation with only the e changing 15 times into a list. I thought I had it solved but in my print statement instead of len just printing a single number for each exponent it's lopping through and printing a number for every unique number it has. I'm having trouble with seeing where I'm going wrong. My program is this:
def greatest_common_divisor(a_int, b_int):
if a_int > b_int:
dividend = a_int
divisor = b_int
else: # b >= a
dividend = b_int
divisor = a_int
remainder = dividend % divisor
quotient = dividend // divisor
while remainder != 0:
dividend = divisor
divisor = remainder
remainder = dividend % divisor
quotient = dividend // divisor
return divisor # which is the gcd
p =5
q = 7
n = p*q
header = ["p","q","n","e","diminished","gcd","unique remainders","max remainders"]
print(header)
for e in range(12,27):
unique_remainders_list = []
for x in range(1,(n+1)):
y = x**e % n
diminished = (p - 1)*(q - 1)
gcd = greatest_common_divisor(e, diminished)
max_uni_val = n-1
if not (y in unique_remainders_list):
unique_remainders_list.append(y)
print("{:>2} {:>4} {:>6} {:>4} {:>10} {:>9} {:>10} {:>16}".\
format(p,q,n,e,diminished,gcd,len(unique_remainders_list),max_uni_val, end = ' '))
Example of print:
['p', 'q', 'n', 'e', 'diminished', 'gcd', 'unique remainders', 'max remainders']
5 7 35 12 24 12 1 34
5 7 35 12 24 12 2 34
5 7 35 12 24 12 3 34
5 7 35 12 24 12 4 34
5 7 35 13 24 1 1 34
5 7 35 13 24 1 2 34
5 7 35 13 24 1 3 34
5 7 35 13 24 1 4 34
5 7 35 13 24 1 5 34
5 7 35 13 24 1 6 34
5 7 35 13 24 1 7 34
5 7 35 13 24 1 8 34
So I think I'm having trouble with the range of e in the end, I'm just not sure where.

Figured it out, needed to move my print statement over. I hate when I miss such small things, but thanks for the help hagubear.
for e in range(12,27):
unique_remainders_list = []
for x in range(1,(n+1)):
y = x**e % n
diminished = (p - 1)*(q - 1)
gcd = greatest_common_divisor(e, diminished)
max_uni_val = n-1
if not (y in unique_remainders_list):
unique_remainders_list.append(y)
print("{:>2} {:>4} {:>6} {:>4} {:>10} {:>9} {:>10} {:>16}".\
format(p,q,n,e,diminished,gcd,len(unique_remainders_list),max_uni_val, end = ' '))

Related

i would like to print following pattern but i can't (I just started 10 days):

check the pattern of image, I want to make it.
I just can do bellow and not more:
n = 5
d = n
for x in range(1, n + 1):
for y in range(1, n * 2 + 1):
if (y >= d) != 0 and y <= n + x - 1:
print(x * y, end=" ")
elif y <= n:
print(" ", end=" ")
else:
pass
d -= 1
print()
this is my output:
5
8 10 12
9 12 15 18 21
8 12 16 20 24 28 32
5 10 15 20 25 30 35 40 45
what should i do?
how should complete this?
One approach is to continue your work with a second for loop. Also, note that there is no need for the else: pass clause.
n = 5
d = n
for x in range(1, n + 1):
for y in range(1, n * 2 + 1):
if (y >= d) != 0 and y <= n + x - 1:
print(x * y, end=" ")
elif y <= n:
print(" ", end=" ")
d -= 1
print()
d+=2
for x in range(n+1, 2*n):
for y in range(1, n * 2 + 1):
if (y >= d) != 0 and y <= 3*n - x-1:
print(x * y, end=" ")
elif y <= n:
print(" ", end=" ")
d += 1
print()
Which results in this output:
5
8 10 12
9 12 15 18 21
8 12 16 20 24 28 32
5 10 15 20 25 30 35 40 45
12 18 24 30 36 42 48
21 28 35 42 49
32 40 48
45
On the other hand, you might appreciate this script, which takes advantage of the str.format method.
n = 5
d = n
form = '{0:<4}'
rows = [[' '*4 for _ in range(2*n)] for _ in range(2*n)]
for x in range(1,n):
for y in range(d,n+x):
rows[x][y] = form.format(x*y)
d-=1
for x in range(n, 2*n):
for y in range(d, 3*n - x):
rows[x][y] = form.format(x*y)
d+=1
for row in rows:
print(''.join(row))
Here's the resulting output:
5
8 10 12
9 12 15 18 21
8 12 16 20 24 28 32
5 10 15 20 25 30 35 40 45
12 18 24 30 36 42 48
21 28 35 42 49
32 40 48
45
You might find it interesting to see how the outputs change as n is varied.
We could also get the same result as the above without the d parameter:
n = 5
form = '{0:<4}'
rows = [[' '*4 for _ in range(2*n+1)] for _ in range(2*n+1)]
for x in range(1,n):
for y in range(n-x+1,n+x):
rows[x][y] = form.format(x*y)
for x in range(n, 2*n):
for y in range(x-n+1, 3*n - x):
rows[x][y] = form.format(x*y)
for row in rows:
print(''.join(row))

Indexing in Polybius cipher produce error in python

I'm making a polybius cipher. So I made a table to convert with the keyword tomato
alp = "abcdefghijklmnopqrstuvwxyz0123456789"
s = str(input("keyword: "))
for i in s:
alp = alp.replace(i,"")
s2 = "".join(dict.fromkeys(s))
jaa = s2+alp
x = list(jaa)
array = np.array(x)
re = np.reshape(array,(6,6))
dt = pd.DataFrame(re)
dt.columns = [1,2,3,4,5,6]
dt.index = [1,2,3,4,5,6]
dt
1 2 3 4 5 6
1 t o m a b c
2 d e f g h i
3 j k l n p q
4 r s u v w x
5 y z 0 1 2 3
6 4 5 6 7 8 9
I want to translate poly with this code
poly = '25 34 14 12 35 22 43 21 25 34 24 33 51 23 12 25 13 34 22'
a = poly.split(" ")
for i in range (len(a)):
hur = a[i]
w = dt._get_value(hur[0],hur[1])
print(w)
But, keyerror : '5'. I've tried to get value with (2,5), the output is good, but can't run it with the indexing. Which part is missing?
It's because hur[0] and hur[1] is a string, not an integer.
You need to do:
for hur in a:
w = dt._get_value(int(hur[0]),int(hur[1]))
print(w, end="") # end="" will print it as one text instead of over multiple lines
Note that your poly has a double space which will mess up the split method.

How to calculate the sum faster

Memory limit: 256 MB
Time limit: 1 s
Hello.
We have the following code:
N, M = list(map(int, input().split()))
stones = list(map(int, input().split()))
for __ in range(M):
command, index, num = input().split()
index, num = int(index), int(num)
if command == "S":
print(sum(stones[index:num + 1]))
elif command == "M":
stones[index] = num
Where:
N is the length of list stones
M is number of commands
1 ≤ N, M ≤ 10**5
commands in form {type} {index} {index2 or value} of two types:
'S' to print sum of items in range [index; index2]
'M' to change value of item on index to new 0 ≤ value ≤ 10
This code exceeds the time limit. So, how to optimize it?
Sample Input:
9 10
1 1 2 3 5 0 4 9 4
S 2 4
S 8 8
S 0 8
S 4 5
M 5 9
S 0 8
S 4 5
M 0 7
S 1 8
S 0 5
Sample Output:
10
4
29
5
38
14
37
27

Python 2.7 list comprehension number pyramid

I am trying to create the following number pyramid using nested list comprehension and string formatting.
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 40 47
I figured out how to create the pyramid using nested for loops but can't quite get it to work using list comprehension. Here is my code:
for n in range(1,8):
print
for x in range(n):
if x>0:
print '%2d' % (n+(n*x)),
else:
print '%d' % n,
The same code using list comprehension gives me a syntax error:
rows = [
'%2d' % (n+(n*x)), if x > 0 else '%d' % n,
for n in range(1,8)
for x in range(n)
]
print '\n' +'\n'.join(rows)
Any ideas on how to format the pyramid correctly using list comprehension?
You could use range to build up each nested list, like so:
# Generation
result = [range(x, x**2 + 1, x) for x in range(1, 8)]
# Formatting
print('\n'.join(''.join(str(x).ljust(4) for x in row) for row in result))
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
You can join a list of lists (in this case, a generator of generators) by newlines
print('\n'.join(' '.join(str(i*j) for j in range(1, i+1)) for i in range(1, n+1)))
#1
#2 4
#3 6 9
#4 8 12 16
#5 10 15 20 25
#6 12 18 24 30 36
#7 14 21 28 35 42 49
and if you want to have the list that creates it just do:
rows = [[i*j for j in range(1, i+1)] for i in range(1, n+1)]

Pascal's triangle code

I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this
from math import factorial
def binomial (n,k):
if k==0:
return 1
else:
return int((factorial(n)//factorial(k))*factorial(n-k))
def pascals_triangle(rows):
rows=20
for n in range (0,rows):
for k in range (0,n+1):
print(binomial(n,k))
print '\n'
This is what it keeps printing
1
1 1
1
2
1
1
12
3
1
1
144
24
4
1
1
2880
360
40
5
1
1
86400
8640
720
60
6
1
1
3628800
302400
20160
1260
and on and on. any help would be welcomed.!!
from math import factorial
def binomial (n,k):
if k==0:
return 1
else:
return int((factorial(n)//factorial(k))*factorial(n-k))
def pascals_triangle(rows):
for n in range (rows):
l = [binomial(n, k) for k in range (0,n+1)]
print l
pascals_triangle(5)
output:
[1]
[1, 1]
[1, 2, 1]
[1, 12, 3, 1]
[1, 144, 24, 4, 1]
there are many wrong things.
The first one is the way you compute the values : if building a pascal triangle, you want to use the previous line to compute the current one, and not use the binomial computation (which is expensive due to the number of multiplications).
then by default, print appends a "\n"
Correct implementation:
def print_line(x):
print (" ".join(map(str,x)))
def pascals_triangle(rows):
cur_line=[1,1]
for x in range (2,rows):
new_line=[1]
for n in range (0,len(cur_line)-1):
new_line.append(cur_line[n]+cur_line[n+1])
new_line.append(1)
print_line (new_line)
cur_line=new_line
this provides the following output
$ python pascal.py
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Your binomial function had a small bracketing mistake in it, which was giving you incorrect output:
from math import factorial
def binomial(n, k):
if k==0:
return 1
else:
return int((factorial(n)/(factorial(k)*factorial(n-k))))
def pascals_triangle(rows, max_width):
for n in range (0,rows):
indent = (rows - n - 1) * max_width
print(' ' * indent, end='')
for k in range(0, n+1):
print("{:^{w}}".format(binomial(n, k), w = max_width*2), end='')
print()
pascals_triangle(7, 2)
With the addition of a padding parameter, the output can be made to look like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1

Categories