Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- #randomly generated list of size specified by user
- n_list = [randint(1, 100) for i in range(int(input("Size of random number list:")))]
- #demo list for testing value recognition
- #n_list = [5,3,4,1,2]
- '''#linear search: FOR loop; searches sequence list and if value matches, returns position+1 for human recognition; otherwise False
- def linear_search(sequence, value):
- n = len(sequence)
- for position in range(n):
- print(sequence[position], "is at position", str(position+1))
- if sequence[position] == value:
- return position+1
- elif position == (n-1) and sequence[position] != value:
- return False
- '''
- #linear search: ENUMERATE loop; searches sequence list and if value matches returns exact position (already increase by 1 in enumerate); otherwise False
- def linear_search(sequence, value):
- n = len(sequence)
- for position, item in enumerate(sequence,1):
- print(item, "is at position", position)
- if item == value:
- return position
- elif position == n and item != value:
- return False
- #collects user guess for value to search for and feeds into linear_search function; stores result in search variable
- guess = int(input("Number to search list for:"))
- search = linear_search(n_list, guess)
- #prints success or failure message
- if search != False:
- print(str(guess), "was found at position", search)
- else:
- print(str(guess), "is not in the list!")
- #print list for visual inspection outside of function
- #print(n_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement