I am trying to implement Quicksort using Python.
This is my code:
import random
def quickSort(lst):
randomIndex = random.randint(0,len(lst)-1)
pivot = lst[randomIndex]
greater = []
less = []
equal = []
if len(lst) > 1:
for num in lst:
if num > pivot:
greater.append(num)
elif num == pivot:
equal.append(num)
else:
less.append(num)
return quickSort(less)+equal+quickSort(greater)
else:
return lst
def main():
lst = [1000000,100000,1000,10000,100,10]
sortedLst = quickSort(lst)
print("Quicksorted List: ", sortedLst)
main()
How come when I run my code, it says that it runs into this error:
ValueError: empty range for randrange() (0,0, 0)
The only problem is that you try to select randomIndex even, when lst is empty, just move your initializations into if condition where you are sure that they are non empty
import random
def quickSort(lst):
if len(lst) > 1:
randomIndex = random.randint(0,len(lst)-1)
pivot = lst[randomIndex]
greater = []
less = []
equal = []
for num in lst:
if num > pivot:
greater.append(num)
elif num == pivot:
equal.append(num)
else:
less.append(num)
return quickSort(less)+equal+quickSort(greater)
else:
return lst
def main():
lst = [1000000,100000,1000,10000,100,10]
sortedLst = quickSort(lst)
print("Quicksorted List: ", sortedLst)
main()
Related
I'm creating a calculator and here's part of the code:
def _digit_formatting(x):
numbers = '1234567890.'
start_idxs = []
end_idxs = []
is_start = True
try:
for idx, value in enumerate(x):
if value in numbers and is_start:
start_idxs.append(idx)
is_start = False
elif value in numbers and idx == len(x) - 1:
end_idxs.append(len(x) - 1)
elif value in numbers and not is_start:
pass
elif value not in numbers and len(start_idxs) > len(end_idxs):
end_idxs.append(idx-1)
is_start = True
except:
...
if len(start_idxs) > len(end_idxs):
end_idxs.append(start_idxs[-1])
start_idxs.reverse()
end_idxs.reverse()
x = list(x)
for idx in range(len(start_idxs)):
if start_idxs[idx] == end_idxs[idx]:
num = x[start_idxs[idx]:end_idxs[idx]+1]
else:
num = x[start_idxs[idx]:end_idxs[idx]+1]
num = ''.join(num)
x = ''.join(x)
x = x[::-1]
num = num[::-1]
x = x.replace(num, '', 1)
x = list(x)
x.reverse()
num = num[::-1]
temp = f'{int(num):,}'
x.insert(start_idxs[idx], temp)
x = ''.join(x)
return x
def calculate(sv):
# This function is called when there's changes in entry box
if self.input_string_var.get() == '':
self.result_string_var.set('')
# Start
real_result = self.input_string_var.get().replace(',', '')
percent_count = self.input_string_var.get().count('%')
# Formatting input string
x = _digit_formatting(real_result)
print(x)
self.input_string_var.set(x)
if percent_count != 0:
numbers = '0123456789.'
for cnt in range(percent_count):
percent_idx = real_result.find('%', 0)
limit_operator = 2
percent_number = ''
for i in range(percent_idx - 1, -1, -1):
if real_result[i] not in numbers:
limit_operator -= 1
if limit_operator == 0:
break
if limit_operator == 1:
if real_result[i] in '*/':
percent_number = ''
break
else:
percent_number += real_result[i]
if percent_number == '':
percent_number = '1'
else:
percent_number = percent_number[1:][::-1]
real_result = list(real_result)
real_result[percent_idx] = f'/100*{percent_number}'
real_result = ''.join(real_result)
else:
real_result = self.input_string_var.get().replace(',', '')
try:
if eval(real_result) == int(eval(real_result)):
self.result_string_var.set(f'{int(eval(real_result)):,}')
else:
self.result_string_var.set(f'{int(eval(real_result)):,}')
except:
None
if self.input_string_var.get() == '':
self.result_string_var.set('')
# Entry box string variable
self.input_string_var = tk.StringVar()
self.input_string_var.trace('w', lambda name, index, mode: calculate(self.input_string_var))
There is two functions, first is _digit_formatting which is to format the equation to put comma like thousands, million and billion. The calculate function is called every time there's changes on the input string variable. But when I try to set the string variable to equation after formatting there seems to be a mistake, but if I print the value, it is correct. Example if I enter 1200 the value I printed is 1,200 which is correct but the value on the text box is not correct. Sorry if the code is messy, I'm still learning to make a clean code.
I cannot reproduce your code.
If you can take a look of my example.
n = 1234567890
print(f"I have {n:,} Reputations")
Result:
I have 1,234,567,890 Reputations
I was trying to get this recursion faster but when I use numbers 50 and 44.4 it takes too long my desired outcome for those numbers is -800555.6302016332
z = int(input())
x = float(input())
def rec(n):
global x
l = {}
if n == 0:
return -1
elif n == 1:
return x
elif n == 2:
return -(x+1)/3
else:
if n in l:
return l[n]
value = float((n/x)*rec(n-1) + ((-1)**n)*((n+1)/(n-1)) * rec(n-2) + ((n-1)/(2*x))*rec(n-3))
l[n] = value
return value
print(rec(z))
You are reinitializing your dictionary l = {} each time you recurse. Making l a global var should fix your problem:
l = {}
def rec(n):
global x
global l
if n == 0:
return -1
elif n == 1:
return x
elif n == 2:
return -(x+1)/3
else:
if n in l:
return l[n]
value = float((n/x)*rec(n-1) + ((-1)**n)*((n+1)/(n-1)) * rec(n-2) + ((n-1)/(2*x))*rec(n-3))
l[n] = value
return value
You could also use functools.lru_cache which does memoization for you:
import functools
#functools.lru_cache
def rec(n):
global x
if n == 0:
return -1
elif n == 1:
return x
elif n == 2:
return -(x+1)/3
else:
return float((n/x)*rec(n-1) + ((-1)**n)*((n+1)/(n-1)) * rec(n-2) + ((n-1)/(2*x))*rec(n-3))
I would also suggest avoiding the use of global variables:
import functools
def rec(n, x):
#functools.lru_cache
def recurse(n):
if n == 0:
return -1
elif n == 1:
return x
elif n == 2:
return -(x+1)/3
else:
return float((n/x)*recurse(n-1) + ((-1)**n)*((n+1)/(n-1)) * recurse(n-2) + ((n-1)/(2*x))*recurse(n-3))
return recurse(n)
def main():
n = int(input())
x = float(input())
print(rec(n, x))
if __name__ == "__main__":
main()
The question is this :
Write a Python function to find all the Strong numbers in a given list of numbers.
Write another function to find and return the factorial of a number. Use it to solve the problem.
Note: 0!=1
The code I tried so far :
def factorial(number):
sum1=0
temp=number
while(number):
i=1
f=1
r=number%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
number=number//10
return sum1
return temp
def find_strong_numbers(num_list):
for item in num_list:
for number in range(1,item+1):
if(sum1==temp):
print(number)
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
Expected output : [145, 2]
I am facing error which is :
NameError: name 'sum1' is not defined
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
if item==0:
break
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10,40585,0]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
List item
Hi I am learning Python from the week, and I got the idea to make maze in python. After a long time trying to do this, I always came to this starting point:
I would like to get the effect of what is on the 2 selection
My code:
def make(x):
if x%2 !=0:
return False
else:
table = []
for i in range(0,x):
if i == 0:
table.append([0]*x)
elif i == x-1:
table.append([0]*x)
return table
else:
if i == 1:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
elif i==x-2:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
else:
table.append([0]*(x))
for j in make(20):
print j
Try this. It's generic enough for any value of x that satisfies x%2==0:
def make(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,x):
if i>=x/2:
fac, rem = divmod(x-i-1,2)
else:
fac, rem = divmod(i,2)
table.append([0,1]*(fac+rem))
table[i].extend([rem]*(x-4*(fac+rem)))
table[i].extend([1,0]*(fac+rem))
return table
Probably better form to raise an exception instead of returning false but I don't know the larger context of what this fits into so I'll just leave it as is.
Or using the same approach as above you can split the single loop into two loops with a separate function like this:
def makeRow(x,fac,rem):
row=[0,1]*(fac+rem)
row.extend([rem]*(x-4*(fac+rem)))
row.extend([1,0]*(fac+rem))
return row
def make2(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,int(x/2)):
table.append(makeRow(x,*divmod(i,2)))
for i in range(int(x/2),x):
table.append(makeRow(x,*divmod(x-i-1,2)))
return table
Or if you prefer to turn the above into something more pythonic:
def make3(x):
if x%2 != 0:
return False
else:
table=[makeRow(x,*divmod(i,2)) for i in range(0,int(x/2))]
table.extend([makeRow(x,*divmod(x-i-1,2)) for i in range(int(x/2),x)])
return table
Why point out the error "table [i + j]. extend ([int (j% 2)] * (x-(4 * s))) IndexError: list index out of range" and whether in general has the right to work
def fun(x):
table=[]
s=0
for i in range(0,int(x/2)):
if i ==0:
table.append([0]*x)
else:
if i==((x/2)-1):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i==(x/2):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i == (x/2-1):
table.append([0]*x)
return table
else:
if i<(((x/2)/2)-2):
s+=1
for j in range(0,2):
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
if i>((x/2)/2):
for j in range(0,2):
if len(table) == (x-2):
break
else:
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
s-=1
for j in fun(20):
print j
def makeArray(a):
a = []
for i in range(n):
a.append(i)
return a
print makeArray(a)
import random
def shuffleArray(a):
size = len(a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
print shuffleArray(makeArray(a))
if __name__ == '__main__':
a = raw_input("please enter size of array: ")
print ("you entered " + a)
makeArray(a)
shuffleArray(a)
how do I make this piece of code ask for input via terminal and take that input through both of the functions then returning a result? I'm asking the user for input storing that input in a variable printing the result and then shuffling by randominzing.
def makeArray(n):
a = [] #you were using 'a' for the size and the array itself at the same time
for i in range(n):
a.append(i)
return a
import random
def shuffleArray(a):
size = len (a)
for i in range(size):
r = random.randrange(0,size)
if r != i:
temp = a[r]
a[r] = a[i]
a[i] = temp
return a
if __name__ == '__main__':
n = int(raw_input("please enter size of array: ")) #'n' needs to be an integer because it's the size of the array
print ("you entered " + str(n))
anArray = makeArray(n)
print shuffleArray(anArray)
you can also replace:
def makeArray(n):
a = []
for i in range(n):
a.append(i)
return a
with:
def makeArray(n):
a = list(range(n))
return a