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
Related
Output screen:
enter the number of elements:3
1
23
3
Traceback (most recent call last):
File "<string>", line 18, in <module>
ValueError: invalid literal for int() with base 10: ''
>
Code :
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input())
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
I'm trying to solve sum of 1d array question from Leetcode, while I'm appending the list I'm getting the value error. Why am I getting this issue?
Just a SLIGHT modification
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input("")) # <<============= HERE
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
Your Code works fine.
The problem may come when you put input anything other than numbers. You may have pressed the "enter" button without any number in your error case. That's why the error said '' in the end.
To avoid such an error, you can write a try-block like the below.
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ +temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
while True:
user_input = input('Enter an int element: ')
try:
ele = int(user_input)
except ValueError:
print(f"Invalid integer '{user_input}', try again")
else:
break
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
I'm trying to write a function that would recursively hash a key for n times, alternating between sha224 and sha256. Each iteration would be hash_256(hash_224)--a hash256 for the hash224 of the key--so that it would yield n * (hash_256(hash_224)). However, I'm new to coding and can't figure out how to write a recursive function with these parameters.
import hashlib
def shasum(key, n):
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8'))
hash_b = hashlib.sha256(hash_a).hexdigest()
if n == 0 or 1:
return hash_b #one iteration of 256(224)
else:
return n-1
return hash_b #stuck here
Edited: now it behaves like a number generator. What's wrong?
import hashlib
n = 0
def sha480(seed):
hashed_224 = str(hashlib.sha224(seed)).encode('utf-8')
hashed_256 = hashlib.sha256(hashed_224).hexdigest()
hashed_480 = str(hashed_256)
print("hash: " + hashed_480)
def repeater(key, n):
if n == 0:
return key
seed = str(key).encode('utf-8')
while n > 0:
return sha480(repeater(seed, n-1))
repeater('what', 2)
You have no recursive calls at all. You could change it to:
def hash_a(key):
return hashlib.sha224(key).hexdigest().encode('utf-8')
def hash_b(key):
return hashlib.sha256(key).hexdigest()
def shasum(key, n):
if n == 0: # base case: 0 iterations -> return key itself
return key
key = str(key).encode('utf-8')
return hash_b(hash_a(shasum(key, n - 1))) # recursve call
A side note: n == 0 or 1 is equivalent to (n == 0) or 1 which is always true. For that pattern, use n == 0 or n == 1 or shorter n in (0, 1)
Your code is nearly correct. just some minor issues fixed as below
import hashlib
def shasum(key, n):
print ("n: " + str(n))
key = str(key).encode('utf-8')
hash_a = hashlib.sha224(key).hexdigest().encode('utf-8')
print ("hash_a: " + str(hash_a))
hash_b = hashlib.sha256(hash_a).hexdigest()
print ("hash_b: " + str(hash_b))
if n == 0:
return hash_b #one iteration of 256(224)
else:
return shasum(hash_b, n-1)
def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
command = input("Enter a command: ")
while command == 'squares' :
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
print('Sum = ', sq_sum)
I want to know how to print out a summation line (Ex: Sum = 2**2 + 3**2 + 4**2 + 5**2 = 54). My code only prints out Sum = 54.
You can use for loop to generate strings "number**2" and keep on list, and later you can use ' + '.join(list) to concatename this strings
def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
terms = []
for number in range(a, a+b):
terms.append("{}**2".format(number))
terms = ' + '.join(terms)
print(terms, '=', sq_sum)
EDIT: or shorter:
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = sum(i**2 for i in range(a, a+b))
terms = ' + '.join("{}**2".format(i) for i in range(a, a+b))
print(terms, '=', sq_sum)
You can change your squares() to return a string as well.
def squares(start, num):
s_sum = 0
output = ""
for i in range(num):
s_sum += start**2
output += '{}**2+'.format(start)
start += 1
return s_sum, output[:-1]
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()
I have a program that is supposed to ask how many primes to calculate then write them all to a text file. However, it creates the file then dosen't run.
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
while(True):
constantcall()
Your problem is the code:
while len(primes) < int(ask):
k = 2
at this point len(primes) is less than int(ask), and there is nothing that add items to primes, so infinite loop.
Your code must be (in order to avoid infinite loop):
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
constantcall()
Using Sieve of Eratosthenes algorithm
You could use the algorithm Sieve of Eratosthenes:
def primes(count):
"""
Returns a list with the first `count` prime numbers.
An advice: If you will be using this functiona a lot it's better
for performance if you precalculate cribe.
"""
# Calculate primes up to 50, you can change this to your preference.
MAX = 50
sieve = [1] * MAX
for i in range(2, int(MAX ** 0.5) + 2 ):
for j in range(i + i, MAX, i):
sieve[j] = 0
# Finally primes are indexes in the list that still has 0.
result = []
for index, elem in enumerate(sieve):
if elem == 1: result.append(index)
return result[1:count + 1]
Your code can then be rewrited as:
def constantcall():
f = open("primes.txt", "w")
ask = int(input("how many primes? "))
prime_numbers = primes(ask)
f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))
if __name__ == '__main__':
constantcall()
Your code does nothing.
while len(primes) < int(ask):
k = 2
Is useless.
while not(k==j) and not(j%k==0):
k = k + 1
Is useless as j is always 2.
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
Here you append 2 to primes once.
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close()
return
So len(primes) is always 1.
Here is a solution. Sorry for C language, but you could easily pythonize it.
#include <stdio.h>
typedef unsigned long long ull;
int main(){
ull numb=10000,stop=20000;
ull i,c;
int cnt;
printf("Here are the primes between %lld and %lld :\n\n",numb,stop);
while(numb<=stop){
for(i=1;i<=numb;++i){
if(!(numb%i)) ++cnt;
}
if ((cnt==2) || (i==1)) printf("%lld; ",numb);
cnt=0;
++numb;
}
printf("\n\nThat's all\n");
}