Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- from random import randint
- def random_char(num_of_char):
- charset="".join(chr(x) for x in range(48,122))
- #return charset[random.randint(0,74)]
- password="".join(charset[random.randint(0,73)] for y in range(num_of_char))
- return password
- ##Example 1 - A while loop
- #position = 0
- #while position < len(sequence):
- #print(sequence[position], "is at position", str(position))
- #position += 1
- ##Example 2 - A for loop over a range
- #for position in range(len(sequence)):
- #print(sequence[position], "is at position", str(position))
- ##Example 3 - The enumerate function
- #for position, item in enumerate(sequence):
- #print(item, "is at position", position)
- def search_for_enumerate(list_to_search, target, is_sorted):
- for position, item in enumerate(list_to_search):
- if target==item:
- print(target, "is at position", position)
- elif is_sorted and position > len(list_to_search):
- print (" Taget not found in sorted list")
- return False
- elif position >= len(list_to_search)-1:
- print (" Taget not found in unsorted list")
- return False
- return True
- def binary_search(sorted_list, value, direction, around):
- if around==True:
- value=round(value)
- if direction=="left":
- left = 0
- right = len(sorted_list) - 1
- while left <= right:
- mid = int((right + left)/2) # mid to int between left and right
- if sorted_list[mid] > value: # if sorted_list[mid] > value set right to mid
- right = mid - 1
- elif sorted_list[mid] < value: # if sorted_list[mid] < value set left to mid
- left = mid + 1
- else: # if sorted_list[mid] == value return mid
- return mid
- return False # loop ends return `False`
- elif direction=="right":
- right = 0
- left = len(sorted_list) - 1
- while left >= right:
- mid = int((right + left)/2) # mid to int between left and right
- if sorted_list[mid] < value: # if sorted_list[mid] > value set right to mid
- right = mid - 1
- elif sorted_list[mid] > value: # if sorted_list[mid] < value set left to mid
- left = mid + 1
- else: # if sorted_list[mid] == value return mid
- return mid
- return False # loop ends return `False`
- list_of_num = [randint(0,50) for i in range(100)]
- print(list_of_num)
- list_of_char = random_char(50)
- print(list_of_char)
- search_for_enumerate(list_of_num, 50, False)
- search_for_enumerate(list_of_char, "a", False)
- list_sorted=sorted(list_of_num)
- print(list_sorted)
- print("First value found by left", binary_search(list_sorted, 15, "left"))
- print("First value found by right", binary_search(list_sorted, 15, "right"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement