BinarySearch missing required positional arguments - python

Sorry - still new to Python, but having trouble with my code working. I can't really figure out where to move the declared variables and getting it to work. However, if I put them outside the function, the other functions are ignored and go straight to n's input request. Any way to fix this?
EDIT: Added the entire code and also the errors I am getting at the bottom, I don't know if this is a simple indentation error.
# menu selector
from tkinter.tix import Select
select = 0
def DisplayMenu() :
print ("enter your choice")
print ("1 for a Linear Search")
print ("2 for a Binary Search")
print ("3 for a Bubble Sort")
print ("4 for a Selection Sort")
print ("5 for a Insertion Sort")
def SelectRoutine() :
global select
DisplayMenu()
select = int(input())
if (select == 1) :
print ("Call the Linear Search Routine")
LinearSearch()
elif (select == 2) :
print ("Call the Binary Search Routine")
BinarySearch()
elif (select == 3) :
print ("Call the Bubble Sort Routine")
BubbleSort()
elif (select == 4) :
print ("Call the Selection Sort")
SelectionSort()
elif (select == 5):
print ("Call the Insertion Sort")
InsertionSort()
else :
print("invalid selection")
def LinearSearch() :
elements = [10, 20, 80, 70, 60, 50]
x = int(input("please enter the number to search: "))
found = False
for i in range(len(elements)) :
if(elements[i] == x) :
found = True
print("%d found at %dth position" % (x, i))
break
if (found == False) :
print("%d is not in list" % x)
def BinarySearch(n, sortedlist, x) :
start = 0
end = n - 1
for i in range(n) :
sortedlist.append(int(input("Enter %dth element: " % i)))
while(start <= end) :
mid = int((start + end) / 2)
if (x == sortedlist[mid]) :
return mid
elif(x < sortedlist[mid]) :
end = mid - 1
else :
start = mid + 1
return -1
n = int(input("Enter the size of the list: "))
sortedlist = []
x = int(input("Enter the number to search: "))
position = BinarySearch(n, sortedlist, x)
if (position != -1) :
print("element number %d is present at position: %d" % (x,position))
else :
print("element number %d is not present in the list" % x)
SelectRoutine()
enter your choice
1 for a Linear Search
2 for a Binary Search
3 for a Bubble Sort
4 for a Selection Sort
5 for a Insertion Sort
2
Call the Binary Search Routine
Traceback (most recent call last):
File "/Users/uglycode.py", line 68, in <module>
SelectRoutine()
File "/Users/uglycode.py", line 22, in SelectRoutine
BinarySearch()
TypeError: BinarySearch() missing 3 required positional arguments: 'n', 'sortedlist', and 'x'
Actual

You should pass n, sortedlist, position variables when you run BinarySearch function.
You should define variables n, sortedlist, position from out of the BinarySearch function.
Your indent under while loop is wrong. You should run binary search logic under your while function.
If you want to run BinarySearch function when you want, make it all to one function as run_binary_search()
If 1. and 2. are not modified, the code will fall into an infinite loop.
If you apply it to SelectRoutine() then, you should define def BinarySearch() function like it.
def BinarySearch():
def _binary_serach(n, sortedlist, x):
start = 0
end = n - 1
while (start <= end) :
mid = int((start + end) / 2)
if (x == sortedlist[mid]):
position = mid
break
elif(x < sortedlist[mid]):
end = mid - 1
else:
start = mid + 1
position = -1
if (position != -1) :
print("element number %d is present at position: %d" % (x,position))
else :
print("element number %d is not present in the list" % x)
return position
n = int(input("Enter the size of the list: "))
sortedlist = []
for i in range(n):
sortedlist.append(int(input("Enter %dth element: " % i)))
x = int(input("Enter the number to search: "))
position = _binary_serach(n, sortedlist, x)
return position

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.

How to show that using 'cache' in a Python program is more efficient?

The program uses two ways to calculate the Collatz Conjecture sequence, I want to show that the method using cache, rather than starting from scratch is more efficient - uses fewer processes. I have tried using the time module and it keeps giving inconsistent results - sometimes the cache method appears to be slower than calculating the sequence from scratch.
cache = {}
def in_cache(n):
if n in cache.keys():
return True
else:
return False
def calculate_collatz(n):
count = 0
collatz_sequence = "N: " + str(n)
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = (3 * n) + 1
count += 1
collatz_sequence += " -> {}".format(n)
return (collatz_sequence, count)
def collatz(n):
if in_cache(n):
print("Using cache...")
return cache[n]
else:
print("Calculating from scratch...")
result = calculate_collatz(n)
cache[n] = result
return result
choice = ""
while choice != 'Q':
#print('The cache: ', cache)
choice = input("Enter an integer to calculate the Collatz Conjecture sequence. Enter Q to quit\n")
try:
n = int(choice)
print(collatz(n))
except:
print("You did not enter a whole number")

"List index out of range" error in python 3 file

I have a homemade text encryption script which outputs a "List index out of range" error when I input "Hey dude, how are you doing?" as a text to encrypt and "KFC" as an encryption key.
I get this more precisely:
Traceback (most recent call last):
File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 75, in <module>
main(userIn, a)
File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 47, in main
currentscrtrank += 1 + scrtlst[scrtrankcounter]
IndexError: list index out of range
I have two files used in this script (the main script and a function library). I just can't figure where this error is coming from...
Here is my main script:
import random
from cryptolib import *
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
print("Content-Type: text/plain;charset=utf-8") # Definit le code d'ecriture
print() # Insere une ligne d'espacement.
def main(userin, numberedsecretkey): # Fonction principale (le gros de l'encryption)
"""
This is my main.
>>> main("Allo", "Hey")
10842839726
"""
comments = True # Definit si les commentaires lors de l'impression sont actif ou non (False les desactive)
total = convdecimal(userin) # Time to deal with the encryption key:
scrtkeytotal = convdecimal(numberedsecretkey)
# converting numbered message to list
msglst = [int(elem) for elem in str(total)]
if comments == True:
printdebug("The initial numbered message is:%s " % msglst)
# converting numbered key to list
scrtlst = [int(thingy) for thingy in str(scrtkeytotal)]
if not comments != True:
printdebug("The initial encryption key is:%s" % scrtlst)
# Attempting Encryption
scrtrankcounter = 0
currentscrtrank = scrtlst[scrtrankcounter]
while currentscrtrank < len(msglst):
randomgen = random.randint(0, 9)
msglst.insert(currentscrtrank, randomgen)
if comments:
printdebug(str(randomgen) + " was inserted at rank: " + str(
scrtrankcounter) + ", therefore, at index position: " + str(currentscrtrank) + ".")
printdebug("List now appears as: " + str(msglst))
scrtrankcounter += 1
if scrtrankcounter > len(scrtlst):
scrtrankcounter = 0
currentscrtrank += 1 + scrtlst[scrtrankcounter]
return listtoint(msglst)
def convdecimal(userin):
rank = len(userin)
total = 0
for character in userin:
rank -= 1 # decreasing the letter rank by one
letter = ord(character)
if letter < 32:
pass
elif letter == 27:
pass
else:
rankmult = 255 ** rank # Making a multiplier
lettervalue = letter * rankmult # Multiplying the letter by this multiplier
total += lettervalue # Adding the letter's value to the total
return total
if __name__ == "__main__":
userIn = input("Enter the word/Sentence you want to encrypt:")
a = input("Enter a password with which you would like to encrypt your message:")
print(userIn)
main(userIn, a)
And here is my function library file:
import os
DEBUG = True
def printdebug(log: object) -> object:
if DEBUG:
print(log)
def loading(sec=10):
start = 1
input("Press Enter to continue")
printdebug("loading...")
while start <= sec:
printdebug("...")
start += 1
def codepause():
os.system("Pause")
input("press enter to continue")
def listtoint(msglst):
# Conversion from list to int
"""
>>> listtoint([1,2,3,4,5,6,7,8,9,0])
1234567890
"""
ncryptedkey = 0
base = 10
for d in msglst:
ncryptedkey = base * ncryptedkey + d
# printDebugJob:
printdebug("The encrypted message is:" + str(ncryptedkey))
return ncryptedkey
def convdecimal(userin):
rank = len(userin)
total = 0
for character in userin:
rank -= 1 # decreasing the letter rank by one
letter = ord(character)
if letter < 32:
pass
elif letter == 27:
pass
else:
rankmult = 255 ** rank # Making a multiplier
lettervalue = letter * rankmult # Multiplying the letter by this multiplier
total += lettervalue # Adding the letter's value to the total
def letterprint(nb):
nb = chr(nb)
print(nb, end='')
Thanks Already!
I've not tested this, but it looks like you need to swap the greater than sign for greater than or equals, as it's probably going 1 index too high.
if scrtrankcounter >= len(scrtlst):
scrtrankcounter = 0
currentscrtrank += 1 + scrtlst[scrtrankcounter]
For example, if scrtlst has a length of 5, the highest index is 4, so it'll give an error if you try scrtlst[5].

Trouble with Python Code. Objective is to code suffix during input

Objective: Write a function that takes an integer as its only parameter and returns the ordinal abbreviation for that integer as its only result. For example, if your function is passed the integer 1 then it should return the string "1st". If it is passed the integer 12 then it should return the string "12th". If it is passed 2003 then it should return the string "2003rd". Your function must not print anything on the screen.
def convert (n):
self.num = num
n = int(self.num)
if 4 <= n <= 20:
suffix = 'th'
elif n == 1 or (n % 10) == 1:
suffix = 'st'
elif n == 2 or (n % 10) == 2:
suffix = 'nd'
elif n == 3 or (n % 10) == 3:
suffix = 'rd'
elif n < 100:
suffix = 'th'
ord_num = str(n) + suffix
return ord_num
def main ():
day = int(input("Enter the day:"))
month = int(input("Enter the month:"))
year = int(input("Enter the year:"))
print("on the %n" %n, convert(day), "day of the %n" %month,
convert(month), "month of the %n" %year, convert(year),",
something amazing happened!")
main()
This is my code however it keeps saying I haven't defined n when I run it. But above I've already defined it so not sure what the problem is.
This is probably closer to what you want:
def convert(n):
n = int(n)
suffix = ''
if 4 <= n <= 20:
suffix = 'th'
elif n == 1 or (n % 10) == 1:
suffix = 'st'
elif n == 2 or (n % 10) == 2:
suffix = 'nd'
elif n == 3 or (n % 10) == 3:
suffix = 'rd'
elif n < 100:
suffix = 'th'
return str(n) + suffix
def main ():
day = int(input("Enter the day: "))
month = int(input("Enter the month: "))
year = int(input("Enter the year: "))
print("on the %s day of the %s month of the %s, something amazing happened!" %
(convert(day), convert(month), convert(year)))
main()
There are few issues. You cannot use n in main() when you define it in convert(). Also %n is not a valid format character. You need to define suffix = '' when also want run the year through the conversion function as the year can be larger than 100. Also, you probably copied the code from within a class definition. I removed the self.

python: program hanging! (print issue maybe?)

So, I'm quite nooby at python. I decided to make a program that makes prime numbers. I know there's probably a function built in that does this but I decided to do it myself.
number = 1
numlist = list()
for x in range (0, 1000):
numlist.append("")
print "Created list entry " + str(x)
while True:
number = number + 1
if number % 2 != 0:
numscrollerA = 1
numscrollerB = 1
while numscrollerA <= number:
if float(number) / float(numscrollerA) == float(int(number)):
numlist[numscrollerA] = "true"
if float(number) / float(numscrollerA) != float(int(number)):
numlist[numscrollerA] = "false"
numscrollerA = numscrollerA + 1
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
if primestatus == "true":
print number
I get "Created list entry x" 1000 times as I should. Then the program just hangs.
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
You don't increase numscrollerB in this loop, so it runs infinitedly. Anyway, You should rather use 'for loop':
for numscrollerB in range(1, number+1):
pass # do something
Your code is very unpythonic. Typical of a newcomer experienced in a different style of coding.
Your list is uneccessary.
In python you could create the list like this
def check_even(val):
#this contains your logic
return val % 2 == 0
evenslist = [check_even(i) for i in xrange(1, 1001)]
print numlist

Categories

Resources