Getting the 983rd prime number instead of 1000th - python

I have just started coding, and I don't seem to be getting it quite right. I would like some feedback on my program.
I am getting 7753 instead of 7919
primes = []
sk = [] # list for all None values
def primtal(a):
if ((2 ** a) - 2) % a == 0:
return a
t = 2
while len(primes) < 1001:
kand = primtal(t)
if kand == None:
sk.append(kand)
else:
primt = kand
primes.append(primt)
t = t + 1
print primes[1000]

Related

How to solve Luhn algoritm

there is a lot of information about how to write Luhn algortim. I'm trying it too and I think that I'am very close to succes but I have some mistake in my code and dont know where. The test card is VALID card but my algorithm says otherwise. Don't you know why? Thx for help
test = "5573497266530355"
kazde_druhe = []
ostatni = []
for i in test:
if int(i) % 2 == 0:
double_digit = int(i) * 2
if double_digit > 9:
p = double_digit - 9
kazde_druhe.append(p)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(i))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k
if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
Finally! Thank you all for your help. Now it is working :-)
test = "5573497266530355" kazde_druhe = [] ostatni = []
for index, digit in enumerate(test):
if index % 2 == 0:
double_digit = int(digit) * 2
print(double_digit)
if double_digit > 9:
double_digit = double_digit - 9
kazde_druhe.append(double_digit)
else:
kazde_druhe.append(double_digit)
else:
ostatni.append(int(digit))
o = sum(ostatni)
k = sum(kazde_druhe)
total = o+k if total % 10 == 0:
print(f"Your card is valid ")
else:
print(f"Your card is invalid ")
From this description
2. With the payload, start from the rightmost digit. Moving left, double the value of every second digit (including the rightmost digit).
You have to check the digit position, not the number itself.
Change to this:
for i in range(len(test)):
if i % 2 == 0:
This code works. :)
I fixed you code as much as i could.
test = "5573497266530355"
#test = "3379513561108795"
nums = []
for i in range(len(test)):
if (i % 2) == 0:
num = int(test[i]) * 2
if num > 9:
num -= 9
nums.append(num)
else:
nums.append(int(test[i]))
print(nums)
print((sum(nums) % 10) == 0)
I found where your code went wrong.
On the line:
for i in test:
if int(i) % 2 == 0:
It should be:
for i in range(len(test)):
if i % 2 == 0:
You should not be using the element of the string you should be using the index of the element.

Why does my hexadecimal to base64 converter break down on large numbers?

I'm working on a cryptopals problem. Specifically, the first one. I have a, what I feel, decent solution for it, in that it works for given inputs, and for the example they give, but I've been looking at further testing to see if it holds up, and it doesn't seem to. Here's my code:
hex="0123456789abcdef"
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def hexNumeralToBinary(hexNumeral):
index = hex.index(hexNumeral)
binaryNumber = []
while index > 0:
if (index % 2) == 0:
binaryNumber = ["0"] + binaryNumber
index = index / 2
else:
binaryNumber = ["1"] + binaryNumber
index = (index-1)/2
while len(binaryNumber) < 4:
binaryNumber = ["0"] + binaryNumber
return ''.join(binaryNumber)
def hexToBinary(hexNumber):
length = len(hexNumber) + 1
binaryNumber = []
for i in range(1, length):
hexNumeral = hexNumber[-1*i]
binaryNumeral = hexNumeralToBinary(hexNumeral)
binaryNumber = [binaryNumeral] + binaryNumber
return ''.join(binaryNumber)
def splitString(binaryNumber):
while (len(binaryNumber) % 6) != 0:
binaryNumber = "0" + binaryNumber
binaryNumberSplit = []
while binaryNumber != "":
binaryNumberSplit.append(binaryNumber[0:6])
binaryNumber = binaryNumber[6:]
return binaryNumberSplit
def hexToBase64(hexNumber):
base64Number = []
binaryNumber = hexToBinary(hexNumber)
binaryNumberSplit = splitString(binaryNumber)
for sixBitNum in binaryNumberSplit:
#Convert 6 bit binary number into the base64 index
index = 0
for i in range(1, 7):
index += int(sixBitNum[-1*i]) * (2**(i-1))
base64Digit = base64[index]
base64Number = base64Number + [base64Digit]
return ''.join(base64Number)
hexNumber = input("Please enter a hexadecimal number to convert to base64: ")
print(hexToBase64(hexNumber))
It seems like the hexadecimal number needs to have a number of digits divisible by 3, or it just gets stuck while running. I don't know where, and I'm really stumped. I'm a total beginner to programming, and this is easily the most complex thing I've done, just trying to work it out as I go, and this isn't coming to me.

The "3n+1" Programming Challenge in Pythonallenge

I'm a Python beginner. I'm trying to solve the 3n+1 problem on UVa Online Judge. The program worked fine with the input files. However, I submitted several times but still got Runtime error.
import sys
def compute(i, j):
maxCycleLength = 1
if i <= j/2:
k = j/2+1
else:
k = i
for n in range(k, j+1):
num = n
cycleLength = 1
while (num != 1):
if num%2 != 0:
num = 3*num+1
else:
num = num/2
cycleLength += 1
if cycleLength > maxCycleLength:
maxCycleLength = cycleLength
return maxCycleLength
while True:
nums = sorted(int(x) for x in next(sys.stdin).split())
m = compute(nums[0], nums[1])
print("{} {} {}\n".format(nums[0], nums[1], m))

How do I run a binary search for words that start with a certain letter?

I am asked to binary search a list of names and if these names start with a particular letter, for example A, then I am to print that name.
I can complete this task by doing much more simple code such as
for i in list:
if i[0] == "A":
print(i)
but instead I am asked to use a binary search and I'm struggling to understand the process behind it. We are given base code which can output the position a given string. My problem is not knowing what to edit so that I can achieve the desired outcome
name_list = ["Adolphus of Helborne", "Aldric Foxe", "Amanita Maleficant", "Aphra the Vicious", "Arachne the Gruesome", "Astarte Hellebore", "Brutus the Gruesome", "Cain of Avernus"]
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
found = False
while low_b <= up_b and found == False:
midPos = ((low_b + up_b) // 2)
if list[midPos] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
if found:
print("The name is at positon " + str(midPos))
return midPos
else:
print("The name was not in the list.")
Desired outcome
bin_search(name_list,"A")
Prints all the names starting with A (Adolphus of HelBorne, Aldric Foxe .... etc)
EDIT:
I was just doing some guess and check and found out how to do it. This is the solution code
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
true_list = []
count = 100
while low_b <= up_b and count > 0:
midPos = ((low_b + up_b) // 2)
if list[midPos][0] == item:
true_list.append(list[midPos])
list.remove(list[midPos])
count -= 1
elif list[midPos] < item:
low_b = midPos + 1
count -= 1
else:
up_b = midPos - 1
count -= 1
print(true_list)
Not too sure if this is what you want as it seems inefficient... as you mention it seems a lot more intuitive to just iterate over the entire list but using binary search i found here i have:
def binary_search(seq, t):
min = 0
max = len(seq) - 1
while True:
if max < min:
return -1
m = (min + max) // 2
if seq[m][0] < t:
min = m + 1
elif seq[m][0] > t:
max = m - 1
else:
return m
index=0
while True:
index=binary_search(name_list,"A")
if index!=-1:
print(name_list[index])
else:
break
del name_list[index]
Output i get:
Aphra the Vicious
Arachne the Gruesome
Amanita Maleficant
Astarte Hellebore
Aldric Foxe
Adolphus of Helborne
You just need to found one item starting with the letter, then you need to identify the range. This approach should be fast and memory efficient.
def binary_search(list,item):
low_b = 0
up_b = len(list) - 1
found = False
midPos = ((low_b + up_b) // 2)
if list[low_b][0]==item:
midPos=low_b
found=True
elif list[up_b][0]==item:
midPos = up_b
found=True
while True:
if found:
break;
if list[low_b][0]>item:
break
if list[up_b][0]<item:
break
if up_b<low_b:
break;
midPos = ((low_b + up_b) // 2)
if list[midPos][0] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
break
if found:
while True:
if midPos>0:
if list[midPos][0]==item:
midPos=midPos-1
continue
break;
while True:
if midPos<len(list):
if list[midPos][0]==item:
print list[midPos]
midPos=midPos+1
continue
break
else:
print("The name was not in the list.")
the output is
>>> binary_search(name_list,"A")
Adolphus of Helborne
Aldric Foxe
Amanita Maleficant
Aphra the Vicious
Arachne the Gruesome
Astarte Hellebore

Binary Subtraction - Python

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]

Categories

Resources