def binary(arr,key):
low = 0
high = len(arr)-1
found = False
while low<=high and not found:
mid = (low+high)//2
if arr[mid] == key:
found = True
index = mid
elif key<arr[mid]:
high = mid-1
else:
low = mid+1
if found == True:
print("key found index: ",index)
else:
print("not found")
This list ask user how many values u want to add
value = int(input("how many number u want to add"))
arr = [0] * value
for n in range(value):
arr[n] = input("Enter value")
print("unsorted array: ")
for n in arr:
print(n, end=" ")
for n in range(1, len(arr)):
temp = arr[n]
j = n - 1
while temp < arr[j] and (j >= 0):
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = temp
it show error if value < alist[midpoint]:
TypeError: '<' not supported between instances of 'int' and 'str'
in line 10
The reason for the type error is that arr is a List[str]. You can fix this by changing it to type List[int]:
for n in range(value):
arr[n] = int(input("Enter value"))
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 24 days ago.
Improve this question
import sys
import timeit
import DSAsorts
import random
REPEATS = 3 #No times to run sorts to get mean time
NEARLY_PERCENT = 0.10 #% of items to move in nearly sorted array
RANDOM_TIMES = 100 #No times to randomly swap elements in array
def usage():
print(" Usage: java TestHarness n xy [xy ...]")
print(" where")
print(" n is number of integers to sort")
print(" x is one of")
print(" b - bubblesort")
print(" i - insertion sort")
print(" s - selection sort")
print(" q - quicksort")
print(" m - mergesort")
print(" y is one of")
print(" a - 1..n ascending")
print(" d - 1..n descending")
print(" r - 1..n in random order")
print(" n - 1..n nearly sorted (10% moved)")
def doSort(n, sortType, arrayType):
A = np.arange(1, n+1, 1) #create array with values from 1 to n
if arrayType == 'a':
...
elif arrayType =='d': #convert to descending
for i in range(0, int(n/2)):
temp = A[i]
A[i] = A[n-i-1]
A[n-i-1] = temp
print("Descending: ", A)
elif arrayType == 'r':
for i in range(RANDOM_TIMES*n):
x = int(random.random()*n)
y = int(random.random()*n)
temp = A[x]
A[x] = A[y]
A[y] = temp
print("Random: ", A)
elif arrayType == 'n':
for i in range(int(n*NEARLY_PERCENT/2+1)):
x = int(random.random()*n)
y = int(random.random()*n)
temp = A[x]
A[x] = A[y]
A[y] = temp
print("Nearly sorted: ", A)
else:
print("Unsupported array type")
if sortType == "b":
DSAsorts.bubbleSort(A)
elif sortType == "s":
DSAsorts.selectionSort(A)
elif sortType == "i":
DSAsorts.insertionSort(A)
elif sortType == "m":
DSAsorts.mergeSort(A)
elif sortType == "q":
DSAsorts.quickSort(A)
else:
print("Unsupported sort algorithm")
for i in range(n-2):
if (A[i] > A[i+1]):
raise ValueError("Array not in order")
#main program
if len(sys.argv) < 3:
usage()
else:
for aa in range(2, len(sys.argv)):
n = int(sys.argv[1])
sortType = sys.argv[aa][0]
arrayType = sys.argv[aa][1]
runningTotal = 0
for repeat in range(REPEATS):
startTime = timeit.default_timer()
doSort(n, sortType, arrayType)
endTime = timeit.default_timer()
runningTotal += (endTime - startTime)
print(sortType + arrayType + " " + str(n) + " " + str(runningTotal/(REPEATS - 1)))
n = len(A)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if A[j] > A[j+1]:
A[j], A[j+1] = A[j+1], A[j]
swapped = True
if not swapped:
break
return A
def insertionSort(A):
for i in range(1, len(A)):
key = A[i]
j = i - 1
while j >= 0 and key < A[j]:
A[j + 1] = A[j]
j -= 1
A[j + 1] = key
return A
def selectionSort(A):
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
# start the next pass after the first element
i += 1
return A
def mergeSort(A):
""" mergeSort - front-end for kick-starting the recursive algorithm
"""
...
def mergeSortRecurse(A, leftIdx, rightIdx):
...
def merge(A, leftIdx, midIdx, rightIdx):
...
def quickSort(A):
""" quickSort - front-end for kick-starting the recursive algorithm
"""
...
def quickSortRecurse(A, leftIdx, rightIdx):
...
def doPartitioning(A, leftIdx, rightIdx, pivotIdx):
...
The following code represents the sorting algorithm written. The output for the sorting algorithms is right but I need to create a table of results to determine the average/best/worst cases and investigate the scalability of the sorting algorithms. I need to create a table of runtime results using at least four array sizes and at least three of the ascending/descending/random/nearly sorted options across each of the implemented sorting algorithms. How would I do that?
what‘s the problem with my code and how can I fix it.
The problems are in lines:
world[r].append(element)
world = createWorld()
world = createWorld()
Now I show all of the code, but it seems too long need more text to make it available to post, so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.
This was the error given:
IndexError: list index out of range
There are more details in the code below, appreciate it if you can help:)
import random
SIZE = 4
EMPTY = " "
PERSON = "P"
PET = "T"
POOP = "O"
ERROR = "!"
CLEANED = "."
MAX_RANDOM = 10
def clean(world, endRow, endColumn):
print("Scooping the poop")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == POOP:
world[r][c] = CLEANED
def count(world, endRow, endColumn):
print("Counting number of occurances of a character")
number = 0
element = input("Enter character: ")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == element:
number += 1
return(element, number)
def createElement():
tempNum = random.randrange(MAX_RANDOM)+1
if ((tempNum >= 1) and (tempNum <= 5)):
tempElement = EMPTY
elif ((tempNum >= 6) and (tempNum <= 7)):
tempElement = PERSON
elif (tempNum == 8):
tempElement = PET
elif ((tempNum >= 9) and (tempNum <= 10)):
tempElement = POOP
else:
tempElement = ERROR
return(tempElement)
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return(world)
def display(world):
print("OUR WORLD")
print("========")
r = 0
while (r < SIZE):
c = 0
while (c < SIZE):
print(world[r][c], end="")
c = c + 1
print()
r = r + 1
print("========\n")
def getEndPoint():
endRow = int(input("Enter the row: "))
while not 0 <= endRow <= 3:
print("Invalid input. Row value should be in range 0-3")
endRow = int(input("Enter the row: "))
endColumn = int(input("Enter the column: "))
while not 0 <= endColumn <= 3:
print("Invalid input. Column value should be in range 0-3")
endColumn = int(input("Enter the column: "))
return (endRow, endColumn)
def start():
world = createWorld()
display(world)
endRow, endColumn = getEndPoint()
element, number = count(world, endRow, endColumn)
print("# occurances of %s=%d" % (element, number))
clean(world, endRow, endColumn)
display(world)
start()
You need to update the r value in the outer loop, currently it is being updated in the inner loop.
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return (world)
This code is for the Google codejam competition. The below code is compiling correctly on my PC and gives the correct result for the sample code. However it is showing runtime error whenever I try to run it on the google website. I have been messing with it for one hour and still have no idea what's wrong with it.
def reversort(reverList):
global totalScore
length = len(reverList)
score = 0
for i in range(length - 1):
minimum = reverList.index(min(reverList[i: ]))
tempList = reverList[i:minimum + 1]
tempList.reverse()
reverList[i: minimum + 1] = tempList
score += minimum - i + 1
totalScore.append(score)
if __name__ == "__main__":
t = int(input())
totalScore = []
rev = []
for i in range(t):
n = int(input())
apen = []
for j in range(n):
apen.append(int(input()))
reversort(apen)
print("Case #{}: {}".format(i+1,totalScore[i]))
rev.append(apen)
try this
reverse = int(input())
for i in range(1, reverse + 1):
a = int(input())
b = list(map(int, input().split()))
out = 0
for index in range(a-1):
min_index = b.index(min(b[index:a]))
b[index: min_index + 1] = reversed(b[index: min_index + 1])
out += (min_index) - (index) + 1
print("Case #{}: {}".format(i, out))
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))
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