I have a programm, which uses binary search.
And in the end, i need to print a count of loops.
How it would be better to do?
import re
def binarySearch(sumList, whattofind):
a=0
if len(sumList) == 0:
return False
else:
midpoint = len(sumList)/2
if sumList[midpoint]==whattofind:
a=a+1
print(a)
return True
else:
if whattofind<sumList[midpoint]:
a+=1
return binarySearch(sumList[:midpoint],whattofind)
else:
a+=1
return binarySearch(sumList[midpoint+1:],whattofind)
print(a)
result = re.findall(r'\w\w', open("text.txt","r").read())
sumList=[]
for line in result:
sumList.append(ord(line[0])+ord(line[1]))
sumList.sort()
whattofind=int(input('Enter number: '))
print (sumList)
print(binarySearch(sumList, whattofind))
do the following
count = 0
def binarySearch(sumList, whattofind):
global count
count += 1
and at the last line of code just print value of count
Related
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Output:
Enter number33
None -> (I want this to be 'True')
Your code reaches no return statement for the break case. You can return from there though:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
return "False"
else:
return "True"
else:
return "False"
This can be simplified as you are returning from every if-block:
def acc_p(num):
if num <= 1:
return "False"
for i in range (2, int(num/2)+1):
if num % i == 0:
return "False"
return "True"
Ultimately you would probably want to return bool values. And with the short-circuiting pattern in your loop, you can use any:
def acc_p(num):
if num <= 1:
return False
return not any(num % i == 0 for i in range (2, int(num/2)+1))
It returns None when the for loop breaks, meaning the else statement will never be met:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break # If it breaks here...
else:
return "True" # This will never be met
else:
return "False" # And of course this one will never be met
x = int(input("Enter number"))
c = acc_p(x)
print(c)
What you'll want to do is return another value under the inner else statement:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
return "False"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Test run:
Enter number7
True
Again:
Enter number33
False
(Note that 33 is not a prime number.)
If I have a number 13245. What I need is to return how many times 2 follows behind number 3.
def thirtyTwos(n):
lst=(map(int,str(n)))
count=0
i=0
j=1
while i<len(lst):
while j<len(lst):
if lst[i]==3>lst[j]==2:
count+=1
j+=1
j=i+1
i+=1
return count
But it turns wrong on some numbers. What should I do now?
This appears to work:
def count_32(number):
number = str(number)
prev_char = ""
count = 0
for char in number:
if char == "2" and prev_char == "3":
count += 1
prev_char = char
return count
for x in [13245, 2345, 32432, 3323232]:
print(x, count_32(x))
Output:
13245 1
2345 0
32432 2
3323232 3
An approach using regex:
import re
def count_32(number):
if not isinstance(number, str):
number = str(number)
return len(re.findall('32', number))
I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum
def SNP(seq1, seq2):
result = []
counter = 0
for position, base in enumerate(seq1):
for position2, base2 in enumerate(seq2):
if base != base2:
result.append(position)
result.append(base)
result.append(base2)
counter += 1
if counter == 2:
return None
result2 = tuple(result)
return result2
print(SNP('AAGCCTA', 'AAGCTTA'))
If the "if statement" is invalid, the loop starts again with the 2nd for loop which I did not intend to...
So the question is after the if statement, how should I let the code start again with the first loop instead of 2nd for loop after 1 loop?
def SNP(seq1, seq2):
result = []
counter = 0
for position, base in enumerate(seq1):
for position2, base2 in enumerate(seq2):
if base != base2:
result.append(position)
result.append(base)
result.append(base2)
counter += 1
if counter == 2:
break
result2 = tuple(result)
return result2
Added the break to the if. Sorry if that's the wrong if statement.
You simply neead a break in the if block, like this
if base != base2:
result.append(position)
result.append(base)
result.append(base2)
counter += 1
if counter == 2:
return None
else:
break
my prime function is working fine for numbers greater than 3,i have accounted for that in loop folowing afterward,question is to find 10001st prime
but i am getting wrong answer that is a prime number but not the 10001st,should be 104743
def pr(n):
for i in range(2,int(n**(0.5))+1):
if n%i==0:
return False
break
else:
return True
num = 3
count = 2
while count < 10001:
num += 1
x = pr(num)
if x == True:
count += 1
print num
try;
def pr(n):
if n%2 == 0:
return False
for i in range(3,int(n**(0.5))+1,2):
if n%i==0:
return False
return True
def pgen(): # Sieve of Eratosthenes generator
yield 2
np_f, q = {}, 3
while True:
f = np_f.pop(q, None)
if f:
np = q + f
while np in np_f:
np += f
np_f[np] = f
else:
yield q
np_f[q*q] = q+q
q += 2
>>> p = pgen()
>>> [next(p) for i in xrange(10001)][-1]
104743