text
stringlengths
37
1.41M
import random import pprint import sys import re spin = 0 next_move = '' landed_on_dict = { 'straight_up': list(range(37)), 'red': [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36], 'black': [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 21, 22, 24, 26, 28, 29, 31, 33, 35], 'even': list(range(2, 37, 2)), 'odd' : list(range(1, 37, 2)), 'low': list(range(19)), 'high': list(range(19, 37)), 'first_col': list(range(1, 35, 3)), 'second_col': list(range(2, 36, 3)), 'third_col': list(range(3, 37, 3)), 'first_doz': list(range(1, 13)), 'second_doz': list(range(13, 26)), 'third_doz': list(range(26,37)) } street = [] for i in range (1, 37, 3): street.append(list(range(37))[i:i+3]) # Nested Array of all # Eleven Streets (11:1) landed_on_dict['street'] = street multiply_by_dict = {'straight_up': 35, 'red': 2, 'black': 2, 'even': 2, 'odd': 2, 'high':2, 'low': 2, 'first_col': 3, 'second_col': 3, 'third_col': 3, 'first_doz': 3, 'second_doz': 3, 'third_doz': 3, 'street': 11} bankroll = 0 instructions = """Instructions: Type the desired bet followed by what you're willing to bet in parenthesis, followed by commas. For example: first_column(20), third_column(20) Odds, Evens: odd(x), even(x) (1:1) High, Low: high(x), low(x) (1:1) First, Second, Third Column: first_col(x), second_col(x), third_col(x) (3:1) First, Second, Third Dozen: first_doz(x), second_doz(x), third_doz(x) (3:1) Straight Up: (x-x) (36:1) Street: (x-x) (11:1) For streets, enter which street you would like to bet on, followed by your desired bet. Leave the text field blank for a free spin! Type 'leave' to close software. """ initial_board = """ -------------------------------------- | |3|6|9|12|15|18|21|24|27|30|33|36|3rd| | -------------------------------------| |0|2|5|8|11|14|17|20|23|26|29|32|35|2nd| | -------------------------------------| | |1|4|7|10|13|16|19|22|25|28|31|34|1st| -------------------------------------- | 1st 12 | 2nd 12 | 3rd 12 | ---------------------------------- | 1-18|Even|Red|Black|Odd|19-36 | -------------------------------- """ number_dictionary = {52: '3', 54: '6', 56: '9', 58: '12', 61: '15', 64: '18', 67: '21', 70: '24', 73: '27', 76: '30', 79: '33', 82: '36', 140: '0', 142: '2', 144: '5', 146: '8', 148: '11', 151: '14', 154: '17', 157: '20', 160: '23', 163: '26', 166: '29', 169: '32', 172: '35', 232: '1', 234: '4', 236: '7', 238: '10', 241: '13', 244: '16', 247: '19', 250: '22', 253: '25', 256: '28', 259: '31', 262: '34'} def initial_print_board(): print(initial_board) def calculate(next_move, bankroll): if next_move == '': spin_wheel_and_modify_board(bankroll) elif next_move == 'leave': sys.exit() next_move = next_move.split(',') temp_next_move = {} for i in range(len(next_move)): formatRegex = re.compile(r'(\w+)(\(\d+\))|(\w+)(\(\d+-\d+\))') mo = formatRegex.search(next_move[i]) mo_single_name = mo.group(1) mo_single_format = mo.group(2) mo_double_name = mo.group(3) mo_double_format = mo.group(4) if mo_single_format == None: temp_next_move[mo_double_name] = mo_double_format.strip('()') elif mo_double_format == None: temp_next_move[mo_single_name] = mo_single_format.strip('()') bet_amount = list(temp_next_move.values()) for i in range(len(temp_next_move)): if bet_amount[i].find('-') != -1: bet_amount[i] = bet_amount[i][bet_amount[i].find('-')+1:] bet_amount[i] = int(bet_amount[i]) for bet_name, bet_placed in temp_next_move.items(): if bet_placed.find('-') > -1: dashIndex = bet_placed.find('-') temp_next_move[bet_name] = temp_next_move[bet_name][:dashIndex] for name, sList in landed_on_dict.items(): if name != 'street' and name != 'straight_up': if name in temp_next_move.keys(): if spin in landed_on_dict[name]: bankroll += (int(temp_next_move[name]) * multiply_by_dict[name]) elif name == 'street': dashIndex = bet_placed.find('-') if name in temp_next_move.keys(): if spin in landed_on_dict[name][:dashIndex]: bankroll += (int(temp_next_move[name][dashIndex+1:]) * multiply_by_dict[name]) elif name == 'straight_up': dashIndex = bet_placed.find('-') if name in temp_next_move.keys(): if temp_next_move[name][:dashIndex] == spin: bankroll += (int(temp_next_move[name][dashIndex+1:]) * multiply_by_dict[name]) if sum(bet_amount) > bankroll: print("That number is higher than your bankroll! Try again.") next_move = input() calculate(next_move) else: global x x = bankroll x -= sum(bet_amount) return bankroll # Example Move: high(10), low(20), street(20-100) def spin_wheel_and_modify_board(bankroll): global spin spin = random.randint(0,36) temp_initial_board = list(initial_board) for i, o in number_dictionary.items(): if str(o) == str(spin): temp_initial_board[i] = 'x' if spin > 9: temp_initial_board[i+1] = 'x' temp_initial_board = ''.join(temp_initial_board) global next_move next_move = input('Your move: ') print(temp_initial_board) print(instructions) print("\n" + "Winning Number: " + str(spin)) calculate(next_move, bankroll) print("Bankroll: " + str(x) + "\n") while bankroll == 0: try: print("Enter the number of credits you want to play with\n") bankroll = int(input()) except ValueError or NameError: print("This isn't a number\n") print(instructions) while next_move != 'leave': spin_wheel_and_modify_board(bankroll) bankroll = x
vowels = {'a', 'e', 'i', 'o', 'u'} word = 'aeou' if set(word).issuperset(vowels) or set(word) == vowels: print(f'{word} is supervocalic.') else: print(f'{word} is not supervocalic.')
class Scoop(): def __init__(self, flavor): self.flavor = flavor def create_scoops(): scoops = [Scoop('chocolate'), Scoop('vanilla'), Scoop('persimmon')] for scoop in scoops: print(scoop.flavor) create_scoops() class Beverage(): def __init__(self, name, temperature = 0): self.name = name self.temperature = temperature def create_beverages(): beverages = [Beverage('coffee', 45), Beverage('water', 10), Beverage('soda', 5), Beverage('mystery liquid')] for beverage in beverages: print(beverage.name, beverage.temperature) create_beverages()
def join_numbers(integer): return ','.join(str(i) for i in range(integer)) print(join_numbers(15)) # With list comprehension print(sum(x*x for x in range(10) if x%2 == 0)) # Without list comprehension total = 0 for i in range(0,10): if i % 2 == 0: total += i*i print(total)
#!/usr/bin/python3 """ Module 7-rectangle Module that contains the class MyList """ class MyList(list): """ Rectangle class A empty MyList class. """ def print_sorted(self): """Returns nothing This function prints the list in order. """ print(sorted(self)) def append(self, i): """Returns None Added a validation in case of a not number """ if not isinstance(i, int): raise TypeError("Must be an integers list.") super(MyList, self).append(i)
#!/usr/bin/python3 """ Module 6-peak Function to find the peak number """ def find_peak(list_of_integers): """ Returns the peak number Function to find the peak number Args: list_of_integers (list): The numners list. """ li = list_of_integers if li == []: return (None) if len(li) == 1: return (li[0]) if li[0] > li[len(li) - 1]: return (find_peak(li[:(len(li) + 1)//2])) else: return (find_peak(li[(len(li))//2:]))
#!/usr/bin/python3 """ Module 8-load_from_json_file Module that contains the function load_from_json_file that return a Python object from a JSON sting file. """ def load_from_json_file(filename): """Returns an object from a JSON string. A function that get the Python object from the JSON string in an textfile. Args: filename (str): The JSON filename file.. """ if not isinstance(filename, str): raise TypeError("It's not a valid filename.") import json with open(filename, mode="r", encoding="utf-8") as f: return (json.loads(f.read()))
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Module 7-base_geometry This module contains the BaseGeometry class """ class BaseGeometry: """BaseGeometry class A simple empty BaseGeometry class """ def area(self): """Returns an Exception""" raise Exception("area() is not implemented") def integer_validator(self, name, value): """Returns a TypeError or ValuError exception Args: name (str): The """ if not isinstance(name, str): raise TypeError("The first parameter must \ be an string") if not isinstance(value, int) or\ value.__class__ is bool: raise TypeError("{:s} must be an integer" .format(name)) if value <= 0: raise ValueError("{:s} must be greater tha\ n 0".format(name))
#!/usr/bin/python3 """multiple_returns Function to return a tuple with the lengt and first character """ def multiple_returns(sentence): new_tuple = [] lengt = len(sentence) new_tuple.append(lengt) new_tuple.append(None if lengt is 0 else sentence[0]) return (tuple(new_tuple))
#!/usr/bin/python3 """print_list_integer Function to print all the integers of a list. """ def print_list_integer(my_list=[]): for i in my_list: print("{:d}".format(i))
#!/usr/bin/python3 """element_at Function to get an elemen of a list. """ def element_at(my_list, idx): if idx < 0 or idx > len(my_list) - 1: return (None) return (my_list[idx])
#!/usr/bin/python3 """safe_print_integer Python function to print an integer of a list. """ def safe_print_integer(value): try: print("{:d}".format(value)) return (True) except (TypeError, ValueError): pass return (False)
#!/usr/bin/python3 """ Read n lines of a text file """ def read_lines(filename="", nb_lines=0): """ Function that reads n lines of a text file """ with open(filename, encoding="UTF-8") as myFile: if nb_lines <= 0: print(myFile.read(), end="") else: counter = 0 for line in myFile: if counter != nb_lines: print(line, end="") counter += 1 else: break
#!/usr/bin/python3 """ Write an object to a text file """ import json def save_to_json_file(my_obj, filename): """ Function that wrutes an obkedct to a text file """ with open(filename, mode="w") as myFile: json.dump(my_obj, myFile)
import numpy as np import time import matplotlib.pyplot as plt #--------------------------------------- heap part def max_heapify(a, i, n): left_i = (2*i)+1 right_i = (2*i)+2 max_i = i if right_i < n and a[right_i] > a[i]: max_i = right_i if left_i < n and a[left_i] > a[max_i]: max_i = left_i if max_i != i: a[i], a[max_i] = a[max_i], a[i] max_heapify(a, max_i, n) def build_max_heap(a): n = len(a) for i in range((n-2)//2, -1, -1): max_heapify(a, i, n) def heapsort(a): build_max_heap(a) n = len(a) for i in range(n-1, 0, -1): a[i], a[0] = a[0], a[i] max_heapify(a, 0, i) return a #--------------------------------------- heap part def mergesort(arr): if len(arr) < 2: return arr half = len(arr)//2 left = mergesort(arr[0:half]) right = mergesort(arr[half:len(arr)]) res = [] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) if left: res.extend(left) if right: res.extend(right) return res def quicksort(arr): if len(arr) < 2: return arr pivot = arr[0] left = [x for x in arr if x < pivot] right = [x for x in arr[1:] if x >= pivot] return quicksort(left) + [pivot] + quicksort(right) def plot(merge_t, quick_t, heap_t, title): plt.title(title) plt.xlabel("Array size") plt.ylabel("Time") plt.plot(merge_t) plt.plot(quick_t) plt.plot(heap_t) # plt.legend(["MergeSort", "HeapSort"], loc ="upper left") plt.legend(["MergeSort", "QuickSort", "HeapSort"], loc ="upper left") plt.show() def srt_perf(fn, a_input, time_arr): start = time.time() merge_res = fn(a_input) end = time.time() time_arr.append(end-start) def perf(): # random array input merge_t = [] quick_t = [] heap_t = [] for i in range(3000): random_arr = np.random.randint(-100, high=100, size=i).tolist() srt_perf(mergesort, random_arr, merge_t) srt_perf(quicksort, random_arr, quick_t) srt_perf(heapsort, random_arr, heap_t) plot(merge_t, quick_t, heap_t, "performance for randomly sorted array") # sorted array input merge_t = [] quick_t = [] heap_t = [] for i in range(2500): sorted_arr = sorted(np.random.randint(-100, high=100, size=i).tolist()) srt_perf(mergesort, sorted_arr, merge_t) srt_perf(quicksort, sorted_arr, quick_t) srt_perf(heapsort, sorted_arr, heap_t) plot(merge_t, quick_t, heap_t, "performance for array that is already sorted") #----------------------------------------Kth element---------------------------------------------- def kth_element(arr1, arr2, begin1, begin2, end1, end2, k) : # let n = length of array 1 # let m = length of array 2 # to handle the case that k is out of bound if k > len(arr1) + len(arr2) - 1: return "no element" # output from another array when there is no remaining element needed to be considered from another array # when an 2 pointers of an array has reach the same point (begin = end), # it means that we will consider k's element from another array if begin1 == end1: return arr2[begin2+k] if begin2 == end2: return arr1[begin1+k] # find the middle point of each array input mid1 = (end1 - begin1) // 2 mid2 = (end2 - begin2) // 2 if k > mid1 + mid2: # If k > mid1 + mid2, we know that the index that we are looking for is either on the higher value side of # one array or it is in another array. if arr1[begin1+mid1] > arr2[begin2+mid2]: # If k > mid1 + mid2 and the value where the mid1 pointer points in array1 is more than # the value where the mid2 pointer points in array2, we know that we can ignore # the small value of arr2 from the begining to the element that mid2 points to. # therefore, we will set the new begin2 pointer to begin2 + mid2 + 1 # as we reduce the array size by half in array2, the time complexity will be T(m/2) return kth_element(arr1, arr2, begin1, begin2 + mid2 + 1, end1, end2, k - mid2 - 1); else: # If k > mid1 + mid2 and the value where the mid1 pointer points in array1 is less than or equal to # the value where the mid2 pointer points in array2, we know that we can ignore # the small value of arr1 from the begining to the element that mid1 points to. # therefore, we will set the new begin1 pointer to begin1 + mid1 + 1 # as we reduce the array size by half in array2, the time function will be T(n/2) return kth_element(arr1, arr2, begin1 + mid1 + 1, begin2, end1, end2, k - mid1 - 1) else: # In the case that k <= mid1 + mid2, we know that we can ignore half of the part of one of the arrays # that has the middle value more than another array. if arr1[begin1+mid1] > arr2[begin2+mid2] : # When middle value of the position that we pay attention to in array1 is more than array2, # we can move the pointer that points to the end of array1 to middle part of the space we are considering. # Therefore, we can reduce number of elements in array1 that we focus on by half, # which bring the time function to T(n/2) return kth_element(arr1, arr2, begin1, begin2, begin1 + mid1, end2, k) else: # This part do the same thing as the if condition but in this case the middle of the space # ,that we pay attention to, in array2 is more than or equal to the middle element's value in array 1. # Therefore, we can reduce number of elements in array2 that we focus on by half, # which bring the time function to T(m/2) return kth_element(arr1, arr2, begin1, begin2, end1, begin2 + mid2, k) random_arr = np.random.randint(-10, high=10, size=10) print("random arr:", random_arr) print("heap sort:", heapsort(random_arr)) print() print("kth element") arr1 = [2,4,6,7] arr2 = [1,3,5,8] for k in range(8): res = kth_element(arr1, arr2, 0, 0, len(arr1), len(arr2), k) print("k:", k, ", res:", res)
class req: """class representing the requirements a player must meet in order to be considered for an invitation to a tournament""" def __init__(self, req_list): """req_list should be a list of strings in the form of a boolean test, all references to the player should use 'p' (for example: "p.GetCountry().GetName() is 'russia'" )""" self.req_list = req_list def setReqs(self, req_list): self.req_list = req_list def appendReq(self, req): self.req_list.append(req) def Test(self, p): for r in self.req_list: if not eval(r): return 0 return 1
import os def ClearScreen(): os.system("cls") def Pause(): os.system("pause") def DisplayStringTable(string_table, pre_clear = 1, pause = 0, horizontal_padding = 3): if pre_clear: ClearScreen() Display(str(string_table)) if pause: Pause() def DisplayTable(string_table, pre_clear = 1, pause = 0, horizontal_padding = 3): """Takes a table of strings and formats it, then displays it""" if pre_clear: ClearScreen() disp_str = "" horizontal_pad = "" for buff in range(horizontal_padding): horizontal_pad += " " collumn_width = [] if not cmp(string_table[0][0], "header"): Display(string_table[0][1]) string_table.remove(string_table[0]) max_row_length = 0 for row in string_table: if len(row) > max_row_length: max_row_length = len(row) for num in range(max_row_length): collumn_width.append(1) for row in string_table: for collumn_index in range(len(row)): if len(row[collumn_index]) > collumn_width[collumn_index]: collumn_width[collumn_index] = len(row[collumn_index]) for row in string_table: for collumn_index in range(len(row)): disp_str += row[collumn_index].ljust(collumn_width[collumn_index]) disp_str += horizontal_pad disp_str += "\n" Display(disp_str) if pause: Pause() def Display(string): print str(string)
import math class vector_t: def __init__(self, vec=(0, 0)): self.x = vec[0] self.y = vec[1] def length(self): return math.sqrt(self.x * self.x + self.y * self.y) def __float__(self): return self.length() def __add__(self, other): return vector_t((self.x + other.x, self.y + other.y)) def __sub__(self, other): return vector_t((self.x - other.x, self.y - other.y)) def __mul__(self, other): return vector_t((self.x * other, self.y * other)) def __truediv__(self, other): return vector_t((self.x / other, self.y / other)) def __str__(self): return '({x}, {y})'.format(x=self.x, y=self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __tuple__(self): return tuple((int(self.x), int(self.y)))
#Author: Charles D. Maddux #Date: 12/28/2020 #Description: Think Python Chapter 5 exercises import time import turtle def exercise_1(current_time): """ times the current time and converts to days, hours, minutes, seconds since the epoch """ #declare variables unit_min = 60 #[seconds/minute] unit_hour = 60 #[minutes/hour] unit_day = 24 #[hours/day] hours = unit_min * unit_hour #[seconds/hour] days = hours * unit_day #[seconds/day] current_days = int(current_time // days) current_day = current_time % days current_hours = int(current_day // hours) current_hour = current_day % hours current_minutes = int(current_hour // unit_min) current_seconds = round(current_hour % unit_min, 1) print(current_time, "seconds have passed since January 1, 1970 GMT") print("That equates to", current_days, "days,", current_hours, "hours,", current_minutes, "minutes, and ", current_seconds, "seconds.") def check_fermat(num_a, num_b, num_c, num_n=2): """ verifies Fermat's Theorem - "there are no positive integers (n > 2) such that a^n + b^n = c^n :param num_a: int :param num_b: int :param num_c: int :param num_n: int :return: 0 """ left_side = num_a**num_n + num_b**num_n right_side = num_c**num_n if left_side == right_side: print("Holy smokes! Fermat was wrong!") else: print("No, that doesn't work.") return left_side == right_side def exercise_2(): """ retrieves inputs for "check_fermat" function and prints results :return: 0 """ check_a = False check_b = False check_c = False check_n = False while check_a == False: num_a = int(input("Enter 1st positive integer:")) if num_a > 0: check_a = True else: print("Input MUST be an integer greater than zero.") while check_b == False: num_b = int(input("Enter 2nd positive integer:")) if num_b > 0: check_b = True else: print("Input MUST be an integer greater than zero.") while check_c == False: num_c = int(input("Enter 3rd positive integer:")) if num_c > 0: check_c = True else: print("Input MUST be an integer greater than zero.") while check_n == False: num_n = int(input("Enter Exponent (must be a positive integer greater than 2):")) if num_n > 2: check_n = True else: print("Input MUST be an integer greater than two.") verify = check_fermat(num_a, num_b, num_c, num_n) #print(verify) def is_triangle(leg_a, leg_b, leg_c): """ checks if 3 given sides can form a triangle :param leg_a: int :param leg_b: int :param leg_c: int :return: str """ if leg_a > (leg_b + leg_c): return "No" elif leg_b > (leg_a + leg_c): return "No" elif leg_c > (leg_a + leg_b): return "No" else: return "Yes" def exercise_3(): """ retrieves user input for triangle sides :return: 0 """ leg_1 = input("Enter the length of the first leg: ") leg_1 = int(leg_1) leg_2 = input("Enter the length of the second leg: ") leg_2 = int(leg_2) leg_3 = input("Enter the length of the third leg: ") leg_3 = int(leg_3) possible = is_triangle(leg_1, leg_2, leg_3) print(possible) def recurse(n, s): """ copy from text """ if n == 0: print(s) else: recurse(n - 1, n + s) def draw(pencil, length, num): """ aefe """ if num == 0: return angle = 50 pencil.fd(length* num) pencil.lt(angle) draw(pencil, length, num - 1) pencil.rt(2* angle) draw(pencil, length, num - 1) pencil.lt(angle) pencil.bk(length* num) def kock(pencil, length, a=1): """ draws a Kock curve """ angle = 60 * a pencil.fd(length) pencil.lt(angle) pencil.fd(length) pencil.rt(2*angle) pencil.fd(length) pencil.lt(angle) pencil.fd(length) pencil.lt(angle) def snowflake(pencil, length, num, a=1): """ adf """ if num == 0: return for j in range(2): for i in range(3): kock(pencil, length, a) a = (-1)* a pencil.lt(60) snowflake(pencil, length, num - 1, a) def main(): current_time = round(time.time(), 1) exercise_1((current_time)) # print("\n") # exercise_2() # print("\n") # exercise_3() recurse(5, 0) bobo = turtle.Turtle() snowflake(bobo, 10, 3) turtle.mainloop() main()
number1, number2 = map(int, input().strip().split()) minimum_number = number1 if number1 < number2 else number2 print(minimum_number)
# Formatting : # Here are some basic argument specifiers you should know: # %s - String (or any object with a string representation, like numbers) # %d - Integers # %f - Floating point numbers # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # %x/%X - Integers in hex representation (lowercase/uppercase) name = 'himanshu' age = 21 print("My name is %s and I am %d year old." % (name, age)) pi = 3.14159265358979 print("Value of pi is %f" % pi) print("Value of pi is %.2f" % pi) # f-string print(f"My name is {name} and I am {age} old.") print(f'{2*3}') # format() print("My name is {} and I am {} year old.".format(name, age)) print("My name is {0} and I am {1} year old.".format(name, age)) print("My name is {1} and I am {0} year old.".format(name, age)) print("My name is {f_name} and I am {u_age} year old.".format(f_name=name, u_age=age)) print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12)) print("The float number is:{:f}".format(123.4567898)) print("The float number is:{}".format(123.4567898)) print("The float number is:{:f}".format(123)) # integer numbers with minimum width print("{:5d}".format(12)) # padding for float numbers print("{:8.3f}".format(12.2346)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346)) # Formatting dictionary members using format() person = {'age': 23, 'name': 'Adam'} print("{p[name]}'s age is: {p[age]}".format(p=person))
# list data-types with their built-in functions : l = [1, 2, 3, 4, 5, "0.354"] bif_of_list = dir(l) print("\n\n", "Built-in function of list data".upper().center(160, '-')) print("Total functions are : ", len(dir(l))) for i in range(0, len(dir(l))): print(bif_of_list[i], end=" ") if (i % 10) == 0 and (i != 0): print() print() print("\n\n", "Practise of Built-in function of list data type".upper().center(160, '-')) # append clear copy count extend index insert pop remove reverse sort # len # animals list animals = ['cat', 'dog', 'rabbit'] # 'guinea pig' is appended to the animals list animals.append('guinea pig') # Updated animals list print('Updated animals list: ', animals) # animals list animals = ['cat', 'dog', 'rabbit'] # list of wild animals wild_animals = ['tiger', 'fox'] # appending wild_animals list to the animals list animals.append(wild_animals) print('Updated animals list: ', animals) # Defining a list list = [{1, 2}, ('a'), ['1.1', '2.2']] # clearing the list list.clear() print('List:', list) # Defining a list list = [{1, 2}, ('a'), ['1.1', '2.2']] # clearing the list del list[:] print('List:', list) old_list = [1, 2, 3] new_list = old_list # add an element to list new_list.append('a') print('New List:', new_list) print('Old List:', old_list) # mixed list my_list = ['cat', 0, 6.7] # copying a list new_list = my_list.copy() print('Copied List:', new_list) # shallow copy using the slicing syntax # mixed list list = ['cat', 0, 6.7] # copying a list using slicing new_list = list[:] # Adding an element to the new list new_list.append('dog') # Printing new and old list print('Old List:', list) print('New List:', new_list) # vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # count element 'i' count = vowels.count('i') # print count print('The count of i is:', count) # count element 'p' count = vowels.count('p') # print count print('The count of p is:', count) # random list random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] # count element ('a', 'b') count = random.count(('a', 'b')) # print count print("The count of ('a', 'b') is:", count) # count element [3, 4] count = random.count([3, 4]) # print count print("The count of [3, 4] is:", count) # language list language = ['French', 'English'] # another list of language language1 = ['Spanish', 'Portuguese'] # appending language1 elements to language language.extend(language1) print('Language List:', language) # language list language = ['French'] # language tuple language_tuple = ('Spanish', 'Portuguese') # language set language_set = {'Chinese', 'Japanese'} # appending language_tuple elements to language language.extend(language_tuple) print('New Language List:', language) # appending language_set elements to language language.extend(language_set) print('Newer Language List:', language) a1 = [1, 2] a2 = [1, 2] b = (3, 4) # a1 = [1, 2, 3, 4] a1.extend(b) # a2 = [1, 2, (3, 4)] a2.append(b) # vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # index of 'e' in vowels index = vowels.index('e') print('The index of e:', index) # element 'i' is searched # index of the first 'i' is returned index = vowels.index('i') print('The index of i:', index) # vowels list vowels = ['a', 'e', 'i', 'o', 'u'] # index of'p' is vowels # index = vowels.index('p') print('The index of p:', index) # alphabets list alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u'] # index of 'i' in alphabets index = alphabets.index('e') # 2 print('The index of e:', index) # 'i' after the 4th index is searched index = alphabets.index('i', 4) # 6 print('The index of i:', index) # 'i' between 3rd and 5th index is searched # index = alphabets.index('i', 3, 5) # Error! print('The index of i:', index) # programming languages list languages = ['Python', 'Java', 'C++', 'French', 'C'] # remove and return the 4th item return_value = languages.pop(3) print('Return Value:', return_value) # Updated List print('Updated List:', languages) # programming languages list languages = ['Python', 'Java', 'C++', 'Ruby', 'C'] # remove and return the last item print('When index is not passed:') print('Return Value:', languages.pop()) print('Updated List:', languages) # remove and return the last item print('\nWhen -1 is passed:') print('Return Value:', languages.pop(-1)) print('Updated List:', languages) # remove and return the third last item print('\nWhen -3 is passed:') print('Return Value:', languages.pop(-3)) print('Updated List:', languages) # animals list animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # 'rabbit' is removed animals.remove('rabbit') # Updated animals List print('Updated animals list: ', animals) # animals list animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog'] # 'dog' is removed animals.remove('dog') # Updated animals list print('Updated animals list: ', animals) # animals list animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # Deleting 'fish' element # animals.remove('fish') # Updated animals List print('Updated animals list: ', animals) # Operating System List systems = ['Windows', 'macOS', 'Linux'] print('Original List:', systems) # List Reverse systems.reverse() # updated list print('Updated List:', systems) # Operating System List systems = ['Windows', 'macOS', 'Linux'] print('Original List:', systems) # Reversing a list #Syntax: reversed_list = systems[start:stop:step] reversed_list = systems[::-1] # updated list print('Updated List:', reversed_list) # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels) # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels # The sort() method accepts a reverse parameter as an optional argument. # Setting reverse = True sorts the list in the descending order. vowels.sort(reverse=True) # print vowels print('Sorted list (in Descending):', vowels) # take second element for sort def takeSecond(elem): return elem[1] # random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # sort list with key random.sort(key=takeSecond) # print list print('Sorted list:', random) print(len([10, 20, 30, 40, 50, 55, 60, 50])) # list comprehension : # generally, we do this. h_letters = [] for letter in 'human': h_letters.append(letter) print(h_letters) # by using list comprehension technique. # syntax : [expression for item in list] h_letters = [letter for letter in 'human'] print(h_letters) # conditional in list comprehension. number_list = [x for x in range(20) if x % 2 == 0] print(number_list) # one more technique for list ; string to list. # input format : # 1 # 2 3 45 58 n = int(input("Enter input : ")) array_values = input("Enter array elements space separated : ").strip().split() array_elements = [int(i) for i in input().split()][:n] print("input value : ", n) print("array values : ", array_values) print("array elements : ", array_elements)
def string_test(s): a = len(s) if a > 2 and s[0] == s[-1]: return('True') else: return('False') def add_x(s):
# Automating google search using python - selenium # for this task we need browser driver running . I used chrome browser which can be downloaded form 'http://chromedriver.chromium.org/downloads' #pip install selenium #Tested on windows machine. we have to give local installation path while loading chrome webdriver from selenium import webdriver _browser=webdriver.Chrome(r'c:\chromedriver_win32\chromedriver.exe') _query='test automation is awesome' _browser.get('http://google.com/search?q='+_query) #browser.get() method returns all the properties of the webpage as elements. I'm filtering by xpath which returns # element object of hyperlinks print('Title : '+_browser.title) _results=_browser.find_elements_by_xpath('.//a') for _link in _results: print(_link.getattribute('href'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from threading import Thread, Lock from time import time, sleep from random import uniform # mutex resource class Fork: def __init__(self): self.lock = Lock() def use(self): self.lock.acquire() # lock def put(self): self.lock.release() # unlock class Philosopher: def __init__(self, ID, left, right, num=100): self.ID = ID self.left = left self.right = right self.num = num def dine(self): print("%dが食事開始" % self.ID) for i in range(self.num): print("%d %2d回目の食事" % (self.ID, i+1)) self.useLeftFork() self.useRightFork() self.eat() self.putLeftFork() self.putRightFork() print("%dが食事終了" % self.ID) def useLeftFork(self): start = time() self.left.use() print("%d 思索時間: %f [sec]" % (self.ID, (time() - start))) def useRightFork(self): start = time() self.right.use() print("%d 思索時間: %f [sec]" % (self.ID, (time() - start))) def putLeftFork(self): self.left.put() def putRightFork(self): self.right.put() def eat(self, eating_time=None): if eating_time: sleep(eating_time) else: sleep(uniform(0.02, 0.05)) class Table: def __init__(self): self.forks = [Fork() for i in range(5)] self.philosophers = [Philosopher(i, self.forks[i], self.forks[(i+1)%5]) for i in range(5)] self.threads = [Thread(target=self.philosophers[i].dine) for i in range(5)] def start(self): for t in self.threads: t.start() if __name__ == "__main__": table = Table() table.start()
menu=input() stri="" for i in menu: uppercase=i.upper() if(uppercase==i): stri=stri+i.lower() else: stri=stri+i.upper() print(stri)
n=int(input()) l=[] for i in range(n): l.append(int(input())) sum=l[0] print(round(sum/1,3)) j=1 for i in range(1,n): j=j+1 sum=sum+l[i] avg=sum/j print(round(avg,3))
n=int(input()) l=[] for i in range(n): l.append(int(input())) print(l[0]) sum=l[0] for i in range(1,n): sum=sum+l[i] print(sum)
password = input() contains_digit = False for character in password: is_digit = character.isdigit() if is_digit: contains_digit = True is_all_lower = (password.lower() == password) is_all_upper = (password.upper() == password) contains_lower_and_upper = (not is_all_lower) and (not is_all_upper) is_valid_password = (contains_digit and contains_lower_and_upper) if is_valid_password: print("Valid Password") else: print("Invalid Password")
""" MTRX5700 - Experimental Robotics Major Project - Blackjack Robot Year: 2021 Group 5 - Curry Shop File: Info: . """ # Imports from blackjack_classes.BlackjackCard import BlackjackCard # Class declaration class BlackjackDealer: # Class constructor def __init__(self): # Initialise empty hand self.hand = [] self.player_id = -1 # Initialise value of hand self.value = 0 # Flag to track if player actions are eligible self.action = True # Flag to track if player actions are eligible self.bust = False def reset(self): self.hand = [] self.value = 0 self.action = True self.bust = False # Add a card to player's hand def add_card_to_hand(self, card): # Add card to hand self.hand.append(card) # Update value of hand self.update_hand_value() # Update the value of cards held def update_hand_value(self): # Initialise total total = 0 ace_count = 0 # Iterate through each card in hand for card in self.hand: # Cumulatively add value of cards in hand if card.value == 11: ace_count += 1 total = total + card.value # Save value self.value = total if total > 21: for i in range(ace_count): self.value -= 10 if self.value < 21: break if self.value <= 21 and len(self.hand) >= 6: self.value = 21 # Print cards held in hand def print_hand(self): # Get list of card names cards_list = [str(card.value) for card in self.hand] # Print list print("[{}]: Hand: {}; Value:{}".format(str(self.player_id), cards_list, self.value)) # Reveal first card def print_first_card(self): # Print first card print("[{}]: Hand: {}".format(str(self.player_id), self.hand[0].name)) # Print message if dealer gets blackjack def print_blackjack_msg(self): # Print message print("[{}]: Blackjack!".format(str(self.player_id)))
# -*- coding:utf-8 -*- import json import urllib2 date = "20181002" server_url = "http://www.easybots.cn/api/holiday.php?d=" vop_url_request = urllib2.Request(server_url + date) vop_response = urllib2.urlopen(vop_url_request) vop_data = json.loads(vop_response.read()) print vop_data if vop_data[date] == '0': print "this day is weekday" elif vop_data[date] == '1': print 'This day is weekend' elif vop_data[date] == '2': print 'This day is holiday' else: print 'Error'
inputData = "" with open("input.txt") as fp: inputData = fp.read().strip() def solve(testdata): stringSum = int(testdata[0]) if testdata[0] == testdata[-1] else 0 for i in range(1, len(testdata)): if testdata[i-1] == testdata[i]: stringSum += int(testdata[i]) return stringSum print(solve(inputData))
"""============================================================================ Game object is the base of an in game object ============================================================================""" import pygame import globals class Gameobject: def __init__(self, boundry, position, size, speed, direction): # Set boundry (Default to screen size) if boundary is None: self.boundary = globals.game.rect else: self.boundary = pygame.Rect(boundary) # Place on screen (Default to center of boundry) if position is None: self.position = (self.boundry.width//2 + self.boundry.x, self.boundry.height//2 + self.boundry.y) else self.position = position # Set scaled size (Default to real image size) if size is None: self.size = Alien1.sprite.size else self.size = size self.rect = pygame.Rect(self.position, self.size) self.speed = speed self.direction = direction self.move_pattern = 'horisontal' self.delete = False # Needs work .... # Move a rectangle in a direction, with a equcalent horisontal pixel speed, within a boundary recangle def move_rect(rect, direction, speed, boundary=False): if not boundary: boundary = globals.game.rect radie = -math.radians(direction) x = speed * math.cos(radie) y = speed * math.sin(radie) new_rect = rect.move(x,y) new_rect.clamp_ip(boundary) return new_rect def rect_touch(rect, boundary): return rect.x == boundary.x or rect.y == boundary.y or rect.x == boundary.width - rect.width or rect.y == boundary.height - rect.height
"""============================================================================ Animation Loads an animation series (or just a still) and creates a pygame surface for it. Animations are a collection of images, displayed with a given frame rate. The images can be separate files, named so that only index numbers differ, or a single image, containing multible frames within parameters: name: name of image file to load. if the file name contains "{index}" it is replaced with an index number, starting with 0. * frame_size: the rectangle (width, height) of the first frame within the image. frames are then picked out, from left to right, top to bottom order * size: Images are scaled to size if specified and rect variable is set to the given position. * frame_rate: number of images shown pr. second. If omitted, it is assumed that the whole series of images represents 1 second of animation * loop: The number of loop to perform. 0 = using first image in the series as a still image. 1 = animating the series one time, and ends with the last one -1 = loop forever n > 1 = number of loops performed, ending with the last image. * = optional This class can be used for images, that are not part of an animation. Just ommit the text "{index}" in the filename and the frame_size parameter. ============================================================================""" import os import math import pygame import config class Animation: def __init__(self, name, frame_size = None, size = None, frame_rate = None, loop = -1): self.file_name = os.path.join(os.getcwd(),config.gfx_path, name) if frame_size is None and size is not None: frame_size = size if size is None and frame_size is not None: size = frame_size self.frame_size = frame_size self.size = size self.frame_rate = frame_rate self.loop = loop self.collection = [] self.frames = 0 self.current_frame = 0 self.frame_time = 0 self.rect = None # Load multiple image files as frames if "{index}" in name: self.collection = self.__load_image_sequence(self.file_name) # Load a single image file else: try: image = pygame.image.load(self.file_name).convert_alpha() # If failing to load image file, create a default image except Exception as error: print(error, self.file_name, "Using default image") image = self.__default_image(self.rect) # split sprite map image into frames self.collection = self.__load_sprite_map(image) # Set meta data self.frames = len(self.collection) if self.frames > 0: # Set animation size if size is None: if frame_size is None: self.size = pygame.Rect(self.collection[0].get_rect()).size self.frame_size = self.size else: self.size = frame_size # Set default frame rate to all frames in one second if frame_rate is None: self.frame_rate = self.frames # Load one or multiple image files as frames def __load_image_sequence(self, name): frame_list = [] index = 0 done = False while not done: try: image = pygame.image.load(self.file_name.format(index = index)).convert_alpha() if silf.size is not None: image = pygame.transform.smoothscale(image, self.size) except Exception as error: if index <= 0: print(error, self.file_name.format(index = self.frames), "not loaded") image = self.__default_image(self.rect) done = True frame_list.append(image) index += 1 return frame_list # Load one image and split it into frames (Sprite map) def __load_sprite_map(self, image): frame_list = [] rect = image.get_rect() if self.frame_size is None: cols = 1 rows = 1 else: cols = rect.width // self.frame_size[0] rows = rect.height // self.frame_size[1] for row in range(rows): for col in range(cols): # Mark positions of frame in map x = self.frame_size[0] * col y = self.frame_size[1] * row # Create a surface to hold the clip and cut it out clip = pygame.Surface(self.frame_size, pygame.SRCALPHA) clip.blit(image, (0,0), pygame.Rect((x,y),self.frame_size)) # Scale clip and append it to the frame list if self.size is not None: clip = pygame.transform.smoothscale(clip, self.size) frame_list.append(clip) return frame_list # Create an image, with a rectangle arround and a cross in it def __default_image(self, rect): if self.size is None: self.size = (100,100) image = pygame.Surface(self.size) pygame.draw.rect(image, (200,0,0), ((0, 0), self.size), 2) pygame.draw.line(image, (200,0,0), (0,0) , self.size, 2) pygame.draw.line(image, (200,0,0), (0,self.size[1]) , (self.size[0], 0), 2) return image # return a pointer to the current surface frame of this animation def get_surface(self): if self.frame_time < (pygame.time.get_ticks() - 1000 // self.frame_rate) : if not self.loop == 0: if len(self.collection) -1 == self.current_frame: if not self.loop == 0: if self.loop > 0: self.loop -= 1 self.current_frame = 0 self.frame_time = pygame.time.get_ticks() else: self.current_frame += 1 self.frame_time = pygame.time.get_ticks() return self.collection[self.current_frame] class Sound: def __init__(self, file_name): if not pygame.mixer.get_init(): print("Failed to use pygame mixer") try: self = pygame.mixer.Sound(os.path.join(globals.sound_path, name) ) except: print("Failed to use pygame mixer") class Music: def __init__(self, file_name): try: pygame.mixer.music.load(os.path.join(globals.sound_path, name)) except Exception as ex: print("failed to load music",ex, "using sound file:", file_name) # Return true at random, on avarage at <freq> times pr. second def random_frequency(freq): return random.randint(0, setting.frame_rate // (freq * globals.game.game_speed) ) == 0 # Move a rectangle in a direction, with a equcalent horisontal pixel speed, within a boundary recangle def move_rect(rect, direction, speed, boundary=False): if not boundary: boundary = globals.game.rect radie = -math.radians(direction) x = speed * math.cos(radie) y = speed * math.sin(radie) new_rect = rect.move(x,y) new_rect.clamp_ip(boundary) return new_rect def rect_touch(rect, boundary): return rect.x == boundary.x or rect.y == boundary.y or rect.x == boundary.width - rect.width or rect.y == boundary.height - rect.height
ativo = True while ativo: try: print("Informe agora os dados para obtenção do volume do cilindro: ") raioCilindro = float(input("raio(r) -> ")) alturaCilindro = float(input("altura(h) -> ")) volume = (3.14 * (raioCilindro ** 2)) * alturaCilindro print(f"Volume do Cilindro: 3.14 * r² * h = {volume}³") onOff = str(input("S para sair - C para continuar: ")) if onOff == "S" or onOff == "s": print("Saindo do programa!") ativo = False # você pode usar o break aq no lugar de mudar pra False elif onOff == "C" or onOff == "c": print("Reiniciando!") ativo = True else: raise ValueError("Informação não reconhecida! Reiniciando aplicação!") except ValueError as e: print("Erro", e)
import random from storage import * def carve_passages_from(maze, row, col): directions = ["N", "S", "E", "W"] random.shuffle(directions) for d in directions: maze.print_maze() p = maze.cell_in_direction(row, col, d) # Check if the cell in the given direction is not outside the maze # and is not yet visited (not yet visited means the open directions # is the empty list). if p != None and maze.open_directions(p[0], p[1]) == []: maze.break_wall(row, col, d) carve_passages_from(maze, p[0], p[1]) #///the first back track occurs at the top left of the maze #this code doesnt generate circles because of the backtracking therefore #once you hit a wall you have to retract and go back to find a different path # Below I have another implementation of the above function, using a # stack instead of recursion but still working the same way. class MazeCell: """ Each entry on the stack is an instance of this class. It represents a cell we have visited but not yet backtracked out of, so stores the list of wall locations that have not yet been checked. """ def __init__(self, r, c): self.row = r self.col = c self.directions = ["N", "S", "E", "W"] random.shuffle(self.directions) def pop_direction(self): if len(self.directions) == 0: return None else: return self.directions.pop() def carve_passages_stack(maze): stack = [] stack.append(MazeCell(0,0)) while len(stack) > 0: # Look at the top of the stack, which is the last element in the list c = stack[-1] # Get the next wall to look at direction = c.pop_direction() if direction == None: # We have looked at all the walls, time to backtrack by poping the cell stack.pop() else: # Check the cell in the given direction p = maze.cell_in_direction(c.row, c.col, direction) if p != None and maze.open_directions(p[0], p[1]) == []: # Go to this cell by pushing onto the stack maze.break_wall(c.row, c.col, direction) stack.append(MazeCell(p[0], p[1])) def random_maze(rows, cols): maze = Maze(rows, cols) carve_passages_stack(maze) return maze #dead end function def random_maze_without_deadends(rows, cols): maze = random_maze(rows, cols) for row in range(rows): for col in range(cols): e = maze.open_directions(row,col) if len(e) == 1: walls = ['N','S','W','E']; boundary = [] if row == 0: walls.remove('N') elif row == rows -1: boundary.append('S') if col == 0: boundary.append('W') elif col == cols -1: boundary.append('E') for x in boundary: walls.remove(x) walls.remove(e[0]) maze.break_wall(row, col, walls[0]) return maze #Question 1 #The maze goes into a infinte loop because since there are no deadends the path will currently #end up in a circle causing the program constantly look for a path to solve since there are no deadends #to break walls down.the program freezes and you must end the program #Question 2-Extra credit #The solution to the maze is to bring the deadends back to the program so that the program #can solve a solution to the maze by breaking th deadends now if __name__ == '__main__': # Some test code m = random_maze_without_deadends(7, 7) m.print_maze()
""" 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры. """ NUMB_ONE = int(input("Количество вводимых чисел? ")) NUMB_TWO = int(input("Цифра, которую необходимо посчитать: ")) COUNT = 0 for i in range(1, NUMB_ONE + 1): m = int(input("Введите число " + str(i) + ": ")) while m > 0: if m % 10 == NUMB_TWO: COUNT += 1 m = m // 10 print("Было введено %d цифр %d" % (COUNT, NUMB_TWO))
""" #5. В массиве найти максимальный отрицательный элемент. # Вывести на экран его значение и позицию (индекс) в массиве. """ from random import randint IN_LIST = [randint(-30, 30) for i in range(30)] MIN_EL = -30 MIN_EL_KEY = 0 for key, value in enumerate(IN_LIST): # поиск минимального элемента и его индекса if 0 > value > MIN_EL: MIN_EL = value MIN_EL_KEY = key # при случае, MIN_EL минимально возможному - прекращаем поиск # if MIN_EL == -30: # break print(f'Исходный массив {IN_LIST}') if MIN_EL >= 0: print('В массиве нет отрицательных элементов') else: print(f'Минимальный отрицательный элемент в массве {MIN_EL} и его индекс {MIN_EL_KEY}')
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. """ NUMB = int(input('Введите число: ')) """ Решение MY_STR[::-1] будет более простым тут, но ... """ NUMB_R = 0 while NUMB > 0: NUMB_R = NUMB_R * 10 + NUMB % 10 NUMB = NUMB // 10 print(NUMB_R)
""" 3. Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой – не больше медианы. Задачу можно решить без сортировки исходного массива. Но если это слишком сложно, то используйте метод сортировки, который не рассматривался на уроках """ from random import randint from statistics import median def my_median(my_list): """ Поиск медианы :param my_list: Исходный массив :return: Выводит медиану """ len_list = len(my_list) sum_list = sum(my_list) avg = sum_list // len_list one_list = [] two_list = [] for val in my_list: if val < avg: one_list.append(val) else: two_list.append(val) # не исходный же массив) one_list.sort(), two_list.sort() one_len, two_len = len(one_list), len(two_list) # Идея такая: разбить исходный массив на два "равных" массива # тогда медиана будет, либо в первом массиве, последним элементом, # либо во втором первым элементом # код ниже извлекает значение медины из массива согластно # логике выше. Но эта логика работает, если длины массивов различны # на 1 # но т.к. длина одного из массива может быть больше длины # другого на более чем 1, то нужны некоторые манипуляции(махинации) if one_len > two_len: index = one_len - two_len if index > 1: index = index // 2 one_list = one_list[:one_len - index] one_list = one_list[::-1] return one_list[index - 1] else: index = two_len - one_len if index > 1: index = index // 2 two_list = two_list[:two_len - index] return two_list[index] return two_list[index - 1] m = randint(1, 500) SIZE = 2 * m + 1 IN_LIST = [randint(0, 500) for i in range(SIZE)] print(IN_LIST) print(my_median(IN_LIST)) print(median(IN_LIST)) # Результат # [136, 115, 299, 29, 439, 341, 189, 84, 108, 292, 315, 299, 489, 281, 362, 92 .... ] # 265 # 265 # P.S. # было сделано куча тестов, все они дали верный результат. # если по какой-то причение "говнокод" выше не работает, то пес с ним. # Медиана находится через сортировку исходного массива с извлечением # среднего элемента.
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. """ from random import randint NUMB_RAND = randint(1, 100) i = 1 while i <= 10: NUMB = int(input('Отгадай число: ')) if NUMB == NUMB_RAND: print('Вы отгадали число за %s попытки(ок)' % i) break print('Осталось попыток %s' % (10 - i)) i = i + 1
#!/usr/bin/env python3 import sys import time from math import * def display_binomial(d): i = 0 p = d / (3600 * 8) n = 3500 overload = 0 begin = time.time() print("Binomial distribution:") while (i <= 50): if ((i % 6) != (0)): print("\t", end='') a = (binomial(n, i)) * (p**i) * ((1 - p)**(n - i)) if (i < 26): overload += a print("%d -> %0.3f" %(i, a), end='') if ((i == 5) or (i == 11) or (i == 17) or (i == 23) or (i == 29) or (i == 35) or (i == 41) or (i == 47)): print("") i += 1 print("") end = time.time() print("overload: {0:.1f}%".format(100 - (overload * 100))) print("computation time: %0.2f ms" %((end - begin) * 1000)) def display_poisson(d): i = 0 l = 3500 * (d / (3600 * 8)) overload = 0 begin = time.time() print("Poisson distribution:") while (i <= 50): if ((i % 6) != (0)): print("\t", end='') a = exp(-l) * pow(l, i) / factorial(i) if (i < 26): overload += a print("%d -> %0.3f" %(i, a), end='') if ((i == 5) or (i == 11) or (i == 17) or (i == 23) or (i == 29) or (i == 35) or (i == 41) or (i == 47)): print("") i += 1 print("") end = time.time() print("overload: {0:.1f}%".format(100 - (overload * 100))) print("computation time: %0.2f ms" %((end - begin) * 1000)) def binomial(n, k): res = factorial(n) // (factorial(k) * factorial(n - k)) return (res) def binomial_and_poisson(d): display_binomial(d) print('') display_poisson(d) def combination(n, k): print("%d-combination of a %d set:\n%d" %(k, n, binomial(n, k))) if (len(sys.argv) > 3 or len(sys.argv) < 2): print ("Error: Number of arguments must be 2 or 3 (see -h)") exit(84) if (len(sys.argv) == 2 and sys.argv[1] == "-h"): print("USAGE\n\t./203hotline [n k | d]\n\nDESCRIPTION\n\tn\tn value for the computation of (n k)\n\tk\tk value for the computation of (n k)\n\td\taverage duration of calls (in seconds)") exit(84) if(len(sys.argv) == 2): try: d = int(sys.argv[1]) except: print("Error: Bad arguments") exit(84) if (d <= 0): print("d must be positive") exit(84) binomial_and_poisson(d) if(len(sys.argv) == 3): try: n = int(sys.argv[1]) k = int(sys.argv[2]) except: print("Error: n or k is and unvalid parameter") exit(84) if (k > n): print("Error: k must be lower than n") exit(84) if (k <= 0 or n <= 0): print("Error: n or k must be positive") exit(84) combination(n, k) exit(0)
import requests from bs4 import BeautifulSoup from urllib.parse import urljoin base_site = "https://en.wikipedia.org/wiki/Music" response = requests.get(base_site) html = response.content soup = BeautifulSoup(html, "lxml") headings = soup.find_all('h2') print(headings) print("\n") heading_text = [a.text for a in headings if a.text != None] print(heading_text)
""" 1. Gather the parameters of interest 2. Construct the URL and send a GET request to it 3. For unsuccessful requests: print the error message 4. For successful requests: extract the relevant data and calculate the result 5. Display the results to the user """ import json import requests base_url = "https://api.exchangeratesapi.io" date = input("Please enter the date (in the format 'yyyy-mm-dd' or 'latest'):") base = input("convert from (currency):") curr = input("Convert to (currency):") quan = float(input("How much {} do you wan to convert: ".format(base))) url = base_url + "/" + date + "?base=" + base + "&symbols=" + curr response = requests.get(url) if(response.ok is False): print("\nError {}:".format(response.status_code)) print(response.json()['error']) else: data = response.json() rate = data['rates'][curr] result = quan*rate print(json.dumps(data, indent=4)) print(result) print("\n{0} {1} is equal to {2} {3}, based upon exchange rates on {4}".format(quan,base,result,curr,data['date']))
import numpy as np arr1 = np.array([1,2,3,4,5,6,7,8,9,10]) print(arr1) print(arr1[0:5]) print(arr1.size) print(arr1[::-1]) #Copying a Array arr2 = arr1[5:].copy() print(arr2) #Reverse an Array arr3 = arr1[::-1].copy() print(arr3)
# _*_ encoding=utf-8 _*_ # author zdh # date 2021/4/21--19:24 #第一种方法: # def singleton(cls): # instances = {} # def weapper(*args,**kwargs): # if cls not in instances: # instances[cls] = cls(*args,**kwargs) # return instances[cls] # return weapper() # # @singleton # class Foo(object): # pass # # foo1 = Foo() # foo2 = Foo() # print(foo1 is foo2) #第二中方法:使用基类 #New是真正创建实例对象的方法,所以重写基类的new方法,以此保证创建对象的时候只生成一个shil # class Singleton(): # def __new__(cls, *args, **kwargs): # if not hasattr(cls,'_instance'): # cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs) # return cls._instance # # class Foo(Singleton): # pass # # foo1 = Foo() # foo2 = Foo() # # print(foo1 is foo2) class Singleton(): def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs) return cls._instance class Foo(Singleton): pass foo1 = Foo() foo2 = Foo() print(foo1 is foo2)
# _*_ encoding=utf-8 _*_ # author zdh # date 2021/4/23--12:01 # map函数 遍历列表的每一个 from functools import reduce l1 = map(lambda x: x * x, [1, 2, 3, 4, 5]) print(list(l1)) l2 = map(lambda x, y: x * y, [1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) print(list(l2)) l3 = map(lambda x, y: (x * y, x + y), [1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) print(list(l3)) # 通过map还可以实现类型转换 # 将元组转换为list l4 = map(int, (1, 2, 3)) print(list(l4)) # 可以直接把元组转换为列表 a = (1, 2, 3) print(list(a)) # 将字符串转换为list: l5 = map(int, '1234') print(list(l5)) # 提出字典中的key,并将结果放在一个list中: l6 = map(int, {1: 2, 2: 3, 3: 4, 4: 5, 5: 6}) print(list(l6)) # reduce 函数 ''' reduce(function,sequence,initial=None) reduce有三个函数,第一个是函数function,第二个是序列sequence,第三个是initial,为初始值,默认为None ''' # 传入自定义的函数 def add(x, y): return x + y print(reduce(add, [1, 2, 3, 4, 5, 6])) # 求积 x = reduce(lambda x, y: x * y, [1, 2, 3, 4]) print(x) # 求和 y = reduce(lambda x, y: x + y, [1, 2, 3, 4]) print(y)
class Pokemon: def __init__(self, name, level, type, is_knocked_out): self.name = name self.level = level self.type = type self.is_knocked_out = is_knocked_out self.exp = 0 self.max_health = level self.health = self.max_health def __repr__(self): return "Pokemon info. {}, current level: {}, type: {}, maximun health: {}, current health: {}.\n".format(self.name, self.level, self.type, self.max_health, self.health) def lose_health(self, dmg): self.health -= dmg if self.health <= 0: self.health = 0 self.knock_out() def gain_health(self, heal): self.health += heal print("{} gained {} health".format(self.name, heal)) print("{}'s health: {}".format(self.name, self.health)) def knock_out(self): if self.is_knocked_out: print("{name} is already knocked out.".format(name = self.name)) else: self.is_knocked_out = True print("{name} is knocked out!".format(name = self.name)) def revive(self): if self.is_knocked_out: self.is_knocked_out = False self.health = 1 print("{name} has been revived with {health} health!".format(name = self.name, health = self.health)) else: print("{name} is not knocked out.".format(name = self.name)) def attack(self, other, dmg): if self.is_knocked_out == True: print("You can not attack. {pokemon} is knocked out!".format(pokemon = self.name)) return if self.type == 'Water': if other.type == 'Fire': dmg *= 2 elif other.type == 'Grass': dmg /= 2 elif self.type == 'Fire': if other.type == 'Grass': dmg *= 2 elif other.type == 'Water': dmg /= 2 elif self.type == 'Grass': if other.type == 'Water': dmg *= 2 elif other.type == 'Fire': dmg /= 2 other.lose_health(dmg) print("{} attacked {}".format(self.name, other.name)) print("{} dealt {} damage to {}. His health is {}.".format(self.name, dmg, other.name, other.health)) self.gain_exp(1) def gain_exp(self, exp): self.exp += exp print("{} gained {} xp.\n".format(self.name, exp)) if self.exp >= 3: self.level_up() def level_up(self): self.exp = 0 self.level += 1 self.max_health += 1 self.health = self.max_health print("{} leveled up to level {}! Max health now is {}. Health fully regenerated.\n".format(self.name, self.level, self.max_health)) class Trainer: def __init__(self, name, pokemons, potions, current_pokemon): self.name = name self.pokemons = pokemons self.potions = potions self.current_pokemon = current_pokemon def __repr__(self): return "Trainer info. {name}, has pokemons: {pokemons}, has {potions} potions, current pokemon is {current_pokemon}.".format(name = self.name, pokemons = self.pokemons, potions = self.potions, current_pokemon = self.current_pokemon) def use_potion(self): if self.potions > 0: if self.current_pokemon.health < self.current_pokemon.max_health: self.current_pokemon.gain_health(1) self.potions -= 1 print("{} has {} potions left.\n".format(self.name, self.potions)) else: print("{} failed to use a potion on {}. Your pokemon has maximum health.\n".format(self.name, self.current_pokemon.name)) else: print("{}, you have no potions!\n".format(self.name)) def attack(self, other, dmg): self.current_pokemon.attack(other.current_pokemon, dmg) def switch_pokemon(self, pokemon): if pokemon.is_knocked_out == True: print("You can't switch to a knocked out pokemon!") elif pokemon in self.pokemons: self.current_pokemon = pokemon print("{} switched a pokemon. {}'s current pokemon now is {}.\n".format(self.name, self.name, self.current_pokemon.name)) class Charmander(Pokemon): def __init__(self, name, level, type, is_knocked_out): super().__init__(name, level, type, is_knocked_out) def destroy(self, other): other.lose_health(other.health) print("{} totally destroyed {}!".format(self.name, other.name)) # The game pikachu = Pokemon("Pikachu", 3, "Fire", False) bulbasaur = Pokemon("Bulbasaur", 3, "Grass", False) squirtle = Pokemon("Squirtle", 3, "Water", False) charmander = Charmander("Charmander", 3, "Fire", False) erika = Trainer('Erika', [pikachu], 2, pikachu) ramos = Trainer('Ramos', [bulbasaur, squirtle], 2, bulbasaur) print(pikachu) print(bulbasaur) pikachu.lose_health(1) pikachu.gain_health(1) pikachu.gain_exp(3)
import re #import pyperclip #text = pyperclip.paste() #Reads the data to be extracted from list.txt file with open("list.txt", 'r') as f: email = re.findall(r'[\w.-]+@[\w-]+[\.][\w]+', f.read()) with open("emailid.txt", 'w+') as f: for line in email: f.write(line+"\n") print(line) with open("list.txt", 'r') as f: phone = re.findall(r'\+?\d{3}?\s?98[.-]?0?\d{0,10}', f.read()) with open("phone.txt", 'w+') as f: for line in phone: f.write(line+"\n") print(line)
import random import logging class LetsMakeADealGame: def __init__(self, switch: bool = False): self.switch = switch self.doors = [False, False, False] # initialise all the doors to have no prize self.doors[random.randint(0, 2)] = True # put the prize behind a random door logging.debug("We're ready to play!") def play(self) -> bool: random_doors = list(range(0, 3)) random.shuffle(random_doors) chosen_door = random_doors[0] logging.debug("The Contestant has chosen door number %i", chosen_door + 1) if self.doors[random_doors[1]] is True: switch_door = random_doors[1] reveal_door = random_doors[2] else: switch_door = random_doors[2] reveal_door = random_doors[1] logging.debug("The host has revealed the prize is not behind door number %i", reveal_door + 1) if self.switch: logging.debug("The contestant has decided to switch to door number %i", switch_door + 1) final_choice = switch_door else: logging.debug("The contestant has decided to stick with door number %i", chosen_door + 1) final_choice = chosen_door if self.doors[final_choice] is True: logging.debug("Congratulations you're a winner!") return True else: logging.debug("Sorry, you're going home with nothing.") return False
# a123_apple_1.py import turtle as trtl import random as rand #-----setup----- apple_image = "apple.gif" # Store the file name of your shape xOffset = -20 yOffset = -47 wn = trtl.Screen() wn.setup(width=1.0, height=1.0) wn.addshape(apple_image) # Make the screen aware of the new file wn.bgpic("background.gif") apple = trtl.Turtle() wn.tracer(False) screen_width = 400 screen_height = 400 letter_list = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] current_letter = "G" #-----functions----- # given a turtle, set that turtle to be shaped by the image file def reset_apple(active_apple): global current_letter length = len(letter_list) if(length != 0): index = rand.randint(0, length-1) active_apple.goto(rand.randint(-screen_width/2, screen_width/2),rand.randint(-screen_height/2, screen_height/2)) current_letter = letter_list.pop(index) draw_apple(active_apple, current_letter) def draw_apple(active_apple, letter): active_apple.penup() active_apple.shape(apple_image) active_apple.showturtle() draw_letter(letter, active_apple) wn.update() def appledrop(): wn.tracer(True) apple.penup() apple.goto(apple.xcor(), -250) apple.hideturtle() apple.clear() wn.tracer(False) reset_apple(apple) def draw_pear(active_apple): active_apple.shape(pear_image) wn.update() def draw_letter(letter, active_apple): active_apple.color("white") rememberPos = active_apple.position() active_apple.setpos(active_apple.xcor() + xOffset, active_apple.ycor() + yOffset) active_apple.write(letter, font=("Arial",50, "bold")) active_apple.setpos(rememberPos) def checkA(): if(current_letter == "A"): appledrop() def checkB(): if(current_letter == "B"): appledrop() def checkC(): if(current_letter == "C"): appledrop() def checkD(): if(current_letter == "D"): appledrop() def checkE(): if(current_letter == "E"): appledrop() def checkF(): if(current_letter == "F"): appledrop() def checkG(): if(current_letter == "G"): appledrop() def checkH(): if(current_letter == "H"): appledrop() def checkI(): if(current_letter == "I"): appledrop() def checkJ(): if(current_letter == "J"): appledrop() def checkK(): if(current_letter == "K"): appledrop() def checkL(): if(current_letter == "L"): appledrop() def checkM(): if(current_letter == "M"): appledrop() def checkN(): if(current_letter == "N"): appledrop() def checkO(): if(current_letter == "O"): appledrop() def checkP(): if(current_letter == "P"): appledrop() def checkQ(): if(current_letter == "Q"): appledrop() def checkR(): if(current_letter == "R"): appledrop() def checkS(): if(current_letter == "S"): appledrop() def checkT(): if(current_letter == "T"): appledrop() def checkU(): if(current_letter == "U"): appledrop() def checkV(): if(current_letter == "V"): appledrop() def checkW(): if(current_letter == "W"): appledrop() def checkX(): if(current_letter == "X"): appledrop() def checkY(): if(current_letter == "Y"): appledrop() def checkZ(): if(current_letter == "Z"): appledrop() #-----function calls----- draw_apple(apple,"G") wn.onkeypress(checkA, "a") wn.onkeypress(checkB,"b") wn.onkeypress(checkC,"c") wn.onkeypress(checkD,"d") wn.onkeypress(checkE,"e") wn.onkeypress(checkF,"f") wn.onkeypress(checkG,"g") wn.onkeypress(checkH,"h") wn.onkeypress(checkI,"i") wn.onkeypress(checkJ,"j") wn.onkeypress(checkK,"k") wn.onkeypress(checkL,"l") wn.onkeypress(checkM,"m") wn.onkeypress(checkN,"n") wn.onkeypress(checkO,"o") wn.onkeypress(checkP,"p") wn.onkeypress(checkQ,"q") wn.onkeypress(checkR,"r") wn.onkeypress(checkS,"s") wn.onkeypress(checkT,"t") wn.onkeypress(checkU,"u") wn.onkeypress(checkV,"v") wn.onkeypress(checkW,"w") wn.onkeypress(checkX,"x") wn.onkeypress(checkY,"y") wn.onkeypress(checkZ,"z") wn.listen() wn.mainloop()
# Python program to display the Fibonacci sequence up to nth term using recursive function """Fibonacci is a sequence of number in which each number is the sum of two preceeding number. In this program, I am using swap technique of python""" print("Hi, This program will tell you the Fibonacci Series for a given number") def fibonacci(in_val): n_first, n_second = 0, 1 fibo = [] while n_first < in_val: fibo.append(n_first) n_first,n_second = n_second, n_first+n_second print(fibo) while True: try: in_val = int(input("Enter a integer: ")) if in_val > 1: print("Fibonacci Series: ") fibonacci(in_val) break elif in_val <= 1: print("Entered value is incorrect, Try again..") except ValueError: print("Entered value is incorrect, Try again..")
# Python program to display the Fibonacci sequence up to nth term using recursive function """Fibonacci is a sequence of number in which each number is the sum of two preceeding number. In this program, I am using swap technique of python""" print("Hi, This program will tell you the Fibonacci Series for a given number using recursion") def fibo_seq(value): if(value <= 1): return value else: return (fibo_seq(value-1) + fibo_seq(value-2)) in_val = int(input("Enter a integer:")) print("Fibonacci sequence using Recursion :") for iter in range(0,in_val): print(fibo_seq(iter))
import RPi.GPIO as gpio val = None; pin = None; state = None; gpio.setmode(gpio.BCM) # gpio.setup(17, gpio.IN, pull_up_down=gpio.PUD_DOWN) # gpio.output(12, gpio.HIGH) # gpio.output(12, gpio.LOW) while(True): try: val = input("Enter GPIO number [0, 27] or set the current GPIO to [h | high] or [l | low]: ") if (val.isdigit()): # Print the ADC values. print("\nCurrent GPIO: {}, state: {}\n".format(pin, state)) pin_no = int(val) if (pin_no >= 0 and pin_no <= 27): if (pin is not None): print("@@@@ Switching GPIO {} -> {}".format(pin, pin_no)) pin = pin_no gpio.setup(pin, gpio.OUT) print("@@ GPIO {} is now set to OUT\n".format(pin)) else: print("\n!!!! Value error; out of range. [0, 27]\n") else: if (pin is not None and (val == 'high' or val == 'h')): state = 'high' gpio.output(pin, gpio.HIGH) print("\n@@ GPIO {} is now HIGH\n".format(pin)) elif (pin is not None and (val == 'low' or val == 'l')): state = 'low' gpio.output(pin, gpio.LOW) print("\n@@ GPIO {} is now LOW\n".format(pin)) else: print("\n!!!! Value error! Must enter either 'h' / 'high' for high or 'l' / 'low' for low.\n") except KeyboardInterrupt: print("@@ Keyboard Interrupt - exiting the test..") gpio.cleanup() exit();
##Texto Criptografado = (Texto normal ^ E) mod N def encrypt(mensagem, eh, mod): codigo = "" for i in range(0,len(mensagem)): codigo += chr( ord(mensagem[i]) ** eh % mod ) return codigo ##Texto Normal = (Texto Criptografado ^ D) mod N def decrypt(mensagem, de, mod): msg = "" for i in range(0,len(mensagem)): msg += chr( ord(mensagem[i]) ** de % mod ) return msg ##Verifica se o numero eh primo def ehPrimo(num): for i in range(2,(num/2)+1): if num % i == 0: return False return True ##Nao sei bem se eh o melhor jeito de fazer esse metodo, mas funcionou aqui def primoRelacao(menor , maior): o = 0 for i in range(2, (maior/2)+1): if maior / float(i) == menor: return i return o ##Esse metodo serve para achar o menor E ##que complete a equacao usada no if. def achaE(de, ze): for i in range (1, ze): if (i * de) % ze == 1: return i ##main?? P = input("Digite o primo P. ") ##P = 17 if ehPrimo(P): Q = input("Digite o primo Q. ") ##Q = 11 if ehPrimo(Q): ##Criacao de N e Z N = P * Q Z = (P-1) * (Q-1) print("Z: " , Z) D = input("Digite um primo em relacao a Z e menor que ele. ") ##D = 7 O = primoRelacao(D, Z) if O == 0: E = achaE(D, Z) print("P: ", P) print("Q: ", Q) print(" ") print("N: ", N) print("Z: ", Z) print(" ") print("D: ", D) print("E: ", E) print(" ") texto = raw_input("Digite um texto para ser codificado: ") if E != None: cod = encrypt(texto, E, N) print(cod) print (decrypt(cod, D, N)) else: print ("Erro na procura de um E") else: print("D nao eh primo em relacao a Z, valor encontrado no metodo: ", O) else: print("Q nao eh primo") else: print("P nao eh primo")
#Question #You Are given an array representing the heights of neighboring buildings on a city street from east to west (rises in the east sets in the west) #The city assessor would like you to write an algorithm that returns how many of these buildings have a view of the setting sun, in order to properly value the street def property_val(buildings): #Counter for number of buildings that should see the sun set total=0 finalView=[] #Iterate through list right to left(backwards) westView=buildings[::-1] num=len(westView) while num>0: if return total print finalView
#Calculates the sum of an input list of integers grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(scores): total=0 for i in scores: total+=i return total print grades_sum(grades) #Calculates average based on sum calculations def grades_average(grades_input): tot=grades_sum(grades_input) avg=tot/float(len(grades_input)) return avg print grades_average(grades) #Calculates Variance of input based on average calculations def grades_variance(scores): average=grades_average(scores) variance=0 for score in scores: variance=variance+(average-score)**2 return variance/len(scores) print grades_variance(grades) #Calculates Std Deviation of Variance def grades_std_deviation(variance): return variance**0.5 variance=grades_variance(grades) print grades_std_deviation(variance)
t = 12345, 54321, 'hello!' print(t[0]) # 12345 print(t) # (12345, 54321, 'hello!') # Tuples may be nested: u = t, (1, 2, 3, 4, 5) print(u) # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# 嵌套列表解析 # Python的列表还可以嵌套。 # # 以下实例展示了3X4的矩阵列表: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] # 以下实例将3X4的矩阵列表转换为4X3列表: print([[row[i] for row in matrix] for i in range(4)]) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] print("------------------------") # 以下实例也可以使用以下方法来实现: transposed = [] for i in range(4): transposed.append([row[i] for row in matrix]) print(transposed) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] print("------------------------") # 另外一种实现方法: transposed = [] for i in range(4): # the following 3 lines implement the nested listcomp transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed.append(transposed_row) print(transposed) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
# 集合 # 集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。 # 可以用大括号({})创建集合。注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;后者创建一个空的字典,下一节我们会介绍这个数据结构。 # 以下是一个简单的演示: basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 删除重复的 # {'orange', 'banana', 'pear', 'apple'} print('orange' in basket) # 检测成员 # True print('crabgrass' in basket) # False # 以下演示了两个集合的操作 a = set('abracadabra') b = set('alacazam') print(a) # a 中唯一的字母 # {'a', 'r', 'b', 'c', 'd'} print(a - b) # 在 a 中的字母,但不在 b 中 # {'r', 'd', 'b'} print(a | b) # 在 a 或 b 中的字母 # {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} print(a & b) # 在 a 和 b 中都有的字母 # {'a', 'c'} print(a ^ b) # 在 a 或 b 中的字母,但不同时在 a 和 b 中 # {'r', 'd', 'b', 'm', 'z', 'l'} print("------------------------") # 集合也支持推导式: a = {x for x in 'abracadabra' if x not in 'abc'} print(a) # {'r', 'd'}
"""Write a python program to find the square root of the given number""" def main(): """Writing inside this function""" squ_apprx = int(input()) epsilon_1 = 0.01 guess_1 = 0.0 step = 0.1 num_guesses = 0 while abs(guess_1**2 - squ_apprx) >= epsilon_1 and guess_1 <= squ_apprx: guess_1 += step num_guesses += 1 if abs(guess_1**2 - squ_apprx) >= epsilon_1: print('Failed on square root of', squ_apprx) else: print(guess_1) if __name__ == "__main__": main()
'''Problem 1 - Build the Shift Dictionary and Apply Shift''' # The Message class contains methods that could be used to apply a # cipher to a string, either to encrypt or to decrypt a message # (since for Caesar codes this is the same action). # In the next two questions, you will fill in the methods of the # Message class found in ps6.py according to the specifications in the # docstrings. The methods in the Message class already filled in are: # __init__(self, text) # The getter method get_message_text(self) # The getter method get_valid_words(self), notice that this one # returns a copy of self.valid_words to prevent someone from mutating the # original list. # In this problem, you will fill in two methods: # Fill in the build_shift_dict(self, shift) method of the Message class. # Be sure that your dictionary includes both lower and upper case # letters, but that the shifted character for a lower case letter and its # uppercase version are lower and upper case instances of the # same letter. What this means is that if the original letter is "a" and # its shifted value is "c", the letter "A" should shift to the letter "C". # If you are unfamiliar with the ordering or characters of the English alphabet, # we will be following the letter ordering displayed by # string.ascii_lowercase and string.ascii_uppercase: # >>> import string # >>> print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz # >>> print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ # A reminder from the introduction page - characters such as the space character, # commas, periods, exclamation points, etc will not be encrypted by this cipher # Basically, all the characters within string.punctuation, plus the space (' ') # and all numerical characters (0 - 9) found in string.digits. # Fill in the apply_shift(self, shift) method of the Message class. # You may find it easier to use build_shift_dict(self, shift). # Remember that spaces and punctuation should not be changed by the cipher. import string # Helper code def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. ''' # inFile: file in_file = open(file_name, 'r') # line: string line = in_file.readline() # word_list: list of strings word_list = line.split() in_file.close() return word_list WORDLIST_FILENAME = 'words.txt' # Helper code End class Message: ''' message class fot implementing cipher text ''' ### DO NOT MODIFY THIS METHOD ### def __init__(self, text): ''' Initializes a Message object text (string): the message's text a Message object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words ''' self.cipher_dict = {} self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) ### DO NOT MODIFY THIS METHOD ### def get_message_text(self): ''' Used to safely access self.message_text outside of the class Returns: self.message_text ''' return self.message_text ### DO NOT MODIFY THIS METHOD ### def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class Returns: a COPY of self.valid_words ''' return self.valid_words[:] def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). ''' lower_keys = list(string.ascii_lowercase) lower_values = list(string.ascii_lowercase) shift_lower_values = lower_values[shift:] + lower_values[:shift] upper_keys = list(string.ascii_uppercase) upper_values = list(string.ascii_uppercase) upper_shift_values = upper_values[shift:] + upper_values[:shift] full_keys = lower_keys + upper_keys full_values = shift_lower_values + upper_shift_values self.shift_dict = {full_keys[i]: full_values[i] for i in range(len(full_keys))} return self.shift_dict def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' new_text = [] for letter in self.message_text: if letter in self.build_shift_dict(shift).keys(): new_text.append(self.build_shift_dict(shift)[letter]) else: new_text.append(letter) return ''.join(new_text) def main(): ''' Function to handle testcases ''' data = Message(input()) data.get_message_text() print(data.apply_shift(int(input()))) if __name__ == "__main__": main()
"""Exercise: eval quadratic. This function takes in four numbers and returns a single number.""" def eval_quadratic(a_in, b_in, c_in, x_in): """square""" return a_in*(x_in**2) + b_in*x_in + c_in def main(): """Writing inside this function""" data = input() data = data.split(' ') data = list(map(float, data)) for x_i in range(len((data))): temp = str(data[x_i]).split('.') if temp[1] == '0': data[x_i] = int(float(str(data[x_i]))) else: data[x_i] = data[x_i] print(eval_quadratic(data[0], data[1], data[2], data[3])) if __name__ == "__main__": main()
# Exercise: PowerRecr # Write a Python function, recurPower(base, exp), that takes in two numbers and returns the base^(exp) of given base and exp. # This function takes in two numbers and returns one number. def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' if exp == 0: return 1 elif exp == 1: return base else: return base * recurPower(base, exp-1) def main(): """Writing inside this function""" data = input() data = data.split() print(recurPower(int(data[0]),int(data[1]))) if __name__ == "__main__": main()
''' Write a function to clean up a given string by removing the special characters and retain alphabets in both upper and lower case and numbers. ''' import re def clean_string(string): '''Clean string function''' regex = re.compile('[^a-zA-z0-9]') cleared_string = regex.sub('', string).replace('^', '') return cleared_string def main(): '''Main function''' string = input() print(clean_string(string)) if __name__ == '__main__': main()
''' This is a continuation of the social network problem There are 3 functions below that have to be completed Note: PyLint score need not be 10/10 for this assignment. We expect 9.5/10 ''' def follow(network, arg1, arg2): ''' 3 arguments are passed to this function network is a dictionary representing the social network arg1 and arg2 are two people in the network follow function is called when arg1 wants to follows arg2 so, this should result in adding arg2 to the followers list of arg1 update the network dictionary and return it ''' if arg1 and arg2 in network: network[arg1].append(arg2) network.update() return network def unfollow(network, arg1, arg2): ''' 3 arguments are passed to this function network is a dictionary representing the social network arg1 and arg2 are two people in the network unfollow function is called when arg1 wants to stop following arg2 so, this should result in removing arg2 from the followers list of arg1 update the network dictionary and return it ''' if arg1 and arg2 in network: network[arg1].remove(arg2) network.update() return network def delete_person(network, arg1): ''' 2 arguments are passed to this function network is a dictionary representing the social network arg1 is a person in the network delete_person function is called when arg1 wants to exit from the network so, this should result in deleting arg1 from network also, before deleting arg1, remove arg1 from the everyone's followers list update the network dictionary and return it ''' if arg1 in network: del network[arg1] network.update() return network def main(): ''' handling testcase input and printing output ''' network = eval(input()) lines = int(input()) for i in range(lines): i += 1 line = input() output = line.split(" ") if output[0] == "follow": network = follow(network, output[1], output[2]) elif output[0] == "unfollow": network = unfollow(network, output[1], output[2]) elif output[0] == "delete": network = delete_person(network, output[1]) print(network) if __name__ == "__main__": main()
"""Exercise: coordinate""" class Coordinate(object): '''This is a class and its name is Coordinate''' def __init__(self, x_input, y_input): self.x_input = x_input self.y_input = y_input def getx_input(self): '''Getter method for a Coordinate object's x coordinate.''' return self.x_input def gety_input(self): '''Getter method for a Coordinate object's y coordinate''' return self.y_input def __str__(self): '''Used while we print an object''' return '<' + str(self.getx_input()) + ',' + str(self.gety_input()) + '>' def __eq__(self, other): '''This is used when the two co-ordinates are equal''' assert type(other) == type(self) if self.getx_input() == other.getx_input(): if self.gety_input() == other.gety_input(): return True return False def __repr__(self): '''Represenation of a co-ordinate''' return 'Coordinate(' + str(self.getx_input()) + ',' + str(self.gety_input()) + ')' #X_NEW = Coordinate(10, 10) #X1_NEW = Coordinate(10, 10) #print(X_NEW.__eq__(X1_NEW)) #print(X_NEW.__repr__()) def main(): '''Writing inside this function''' data = input() data = data.split(' ') data = list(map(int, data)) print(Coordinate(data[0], data[1]) == Coordinate(data[2], data[3])) print(Coordinate(data[4], data[5]).__repr__()) if __name__ == "__main__": main()
#!/bin/python3 import sys def insertionSort1(n, arr): last = arr[-1] last = arr[-1] x = 0 while arr[n-(n+2) - x] > last: arr[-1-x] = arr[n-(n+2) - x] print (' '.join(str(y) for y in arr)) if x+2 == len(arr): arr[n-(n+2) - x] = last break else: x += 1 if arr[n-(n+2) - x] < last: arr[-x-1] = last print (' '.join(str(y) for y in arr)) else: print (' '.join(str(y) for y in arr)) if __name__ == "__main__": n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) insertionSort1(n, arr)
import math import MathUtils import StringUtils def TrouverClePrivee(n, c): """ Trouve la clé privée associée à une clé publique param n: n de la clé publique param c: d de la clé publique return: l'entier d de la clé publique """ divider = [d for d in range(2, int(math.sqrt(n))) if n%d == 0] p = divider[0] q = n/p d = int(MathUtils.inverseModulaire(c, (p - 1) * (q - 1))) return d if __name__ == '__main__': n=int(input("entrez la valeur 'n' de votre cle publique: ")) c=int(input("entrez la valeur 'd' de votre cle publique: ")) d=TrouverClePrivee(n, c) print ("la cle privee est {}".format(d)) choix=input("voulez vous utiliser cette cle pour dechiffrer un message? (o/n)") if choix == "o": message = input("Entrez le message chiffre:") messageInt = StringUtils.stringToInt(message) print("message int: {}".format(messageInt)) messageDecripte=MathUtils.dechiffrement(messageInt, n, d) print("message descripte: {}".format(messageDecripte)) messageDecripteStr=StringUtils.intToString(messageDecripte) print("le message dechiffre est: {}".format(messageDecripteStr))
produtos=[] custos=[] codigo = 1 while codigo != 0: codigo,quantidade,preco = input().split() codigo = int(codigo) quantidade = float(quantidade) preco = float(preco) custo = quantidade * preco produtos.append([codigo,quantidade,custo,preco]) custos.append(custo) maior_custo = max(custos) n_posicao = custos.index(maior_custo) if maior_custo == 0: print('nao tem compras') else: print('Item mais caro') print('Codigo: {}'.format(produtos[n_posicao][0])) print('Quantidade: {:.0f}'.format(produtos[n_posicao][1])) print('Custo: {:.2f}'.format(produtos[n_posicao][2]))
def potencias(n): for i in range(n): p=2**(i+1) print(p,end=' ')
def f(b): return a*b a = 0 print('f(3) = {}'.format(f(3))) print('a é {} '.format(a))
def main(): pri = Carro('brasilia', 1968, 'amarela', 80) seg = Carro('fuscao', 1981, 'preto', 95) Carro.acelere(pri, 40) pri.acelere(40) Carro.acelere(seg, 50) Carro.acelere(pri, 80) Carro.pare(pri) seg.pare() Carro.acelere(seg, 100) class Carro: def __init__(self, m, a, c, vm): self.modelo = m self.ano = a self.cor = c self.vel = 0 self.maxV = vm # velocidade maxima def imprima(self): if self.vel == 0: # parado da para ver o ano print( "%s %s %d"%(self.modelo, self.cor, self.ano) ) elif self.vel < self.maxV: print( "%s %s indo a %d Km/h"%(self.modelo, self.cor, self.vel) ) else: print( "%s %s indo muito raaaaaapiiiiiiiidoooooo!"%(self.modelo, self.cor)) def acelere(self, v): self.vel = v if self.vel > self.maxV: self.vel = self.maxV Carro.imprima(self) def pare(self): self.vel = 0 Carro.imprima(self) main()
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # If end of array is greater than or equal to, need equal in case target is there if end >= start: # Get the value in the middle of the array middle = (start + end) // 2 # If target equals the value in the middle of the array if target == arr[middle]: # Return the middle of the array, target is now found return middle # If target is greater than the valie in the middle of the array elif target > arr[middle]: # Return the function with the middle value as the start - 1 to match the index return binary_search(arr, target, (middle -1), end) # If the target is less than the value in the middle of the array elif target < arr[middle]: # Return the function with the middle value as the end -1 to match the index return binary_search(arr, target,start,(middle - 1)) # If the target is not found, return -1 per the tests return -1 # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively def agnostic_binary_search(arr, target): pass
print("program to print the modules odd number") odd number (1 to 100) result=num1++ print (result)
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/10/22 name_list = ['zhangsan', 'lisi', 'wangwu'] print (name_list[2]) print (name_list.index('wangwu')) # 2 修改 name_list[1] = '李四' # 3.增加 name_list.append('大哥') name_list.append('dage') name_list.insert(1,'xiaomeimei') # extend 可以把其他列表追加到当前列表后面 temp_list = ['wukong','bajie','shashidi'] name_list.extend(temp_list) # 4.删除 name_list.remove('wukong') # pop默认可以把列表中最后一个元素删除 name_list.pop() name_list.pop(1) #指定索引位置删除 # name_list.clear() #python3 中的命令,可以清空列表 del name_list[0] #del本质上是用来将一个变量从内存中删除,后续的代码就不能使用这个变量了 print (name_list)
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/10/23 str1 = "hello world" str2 = '我的名字是"大西瓜"' # for char in str1: # # print char print len(str1) print str1.count("l") print str1.index('or')
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2018/1/8 # 之前都是拿 函数 来装饰 函数, 现在是拿 类 来装饰 函数 # class Test(object): # # def __call__(self, *args, **kwargs): # print('-------test-------') # # t = Test() # t() # 因为 __call__ 所以类实例化的对象才能直接()调用 # ############################################################## class Test(object): def __init__(self, func): print('初始化') print('func name is %s' % func.__name__) self.__func = func # 创建一个[属性],指向func def __call__(self, *args, **kwargs): print('装饰器中的功能') self.__func() # 这里回去调用类外面的函数 # 定义一个普通的函数 @Test # 相当于 test = Test(test), 会自动调用 __init__(self), test 指向func def test(): print('test 函数') test() # 这里会去调用 __call__(self)
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/12/28 # xx:公有变量 # _x:单前置下划线,私有化属性或方法,from somemoudule import * 禁止导入,类对象和子类可以访问 # __xx:双前置下划线,避免与子类中的属性命名冲突,无法在外部直接访问(名字重复所以访问不到),想访问,_类名__xx(系统不推荐) # __xx__:双前后下划线,用户名字空间的系统方法或属性 # xx_:单后置下划线,用于避免与python关键词冲突 if_ = 100 class Test(object): def __init__(self): self.num = 100 self.__num = 1000 def setNum(self,newNum): self.__num = newNum def getNum(self): return self.__num t = Test() t.num = 200 # print(t.__num) # 这里带__的属性,不能在类外面使用,报错啊 t.__num = 2000 print(t.num) print(t.__num) # 这里可以使用,是因为前面赋值了,相当于添加了一个同名的__num属性 print('-'*50) print(t.getNum()) t.setNum(50) print(t.getNum())
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/12/3 # 面向对象三大特性: # 1. 封装 ,根据职责将 属性和方法 封装 到一个抽象的 类 中 # 2. 继承 ,实现代码的重用,相同的代码不需要重复编写 # 3. 多态 ,不同的 子类对象 调用相同的父类方法,产生不同的执行结果 class Dog(object): def __init__(self,name): self.name = name def game(self): print "%s 蹦蹦跳跳的玩耍" % self.name class XiaoTianQuan(Dog): def game(self): print "%s 飞到天上去玩耍" % self.name class Person(object): def __init__(self,name): self.name = name def game_with_dog(self,dog): print "%s 和 %s 快乐的玩耍" % (self.name,dog.name) # 让狗玩耍 dog.game() # 1 创建一个狗对象 # wangcai = Dog("旺财") wangcai = XiaoTianQuan("飞天旺财") # 2 创建一个小明对象 xiaoming = Person("小明") # 3 让小明调用和狗玩的方法 xiaoming.game_with_dog(wangcai)
class Dishes: total_price = 0 def __init__(self, type="Cup", colour="Green", price=100, size=250, print1="With cat", material="ceramics"): self.type = type self.colour = colour self.price = price self.size = size self.print1 = print1 self.material = material Dishes.total_price += self.price def to_string(self): print("Type: " + self.type + ", Colour: " + str(self.colour) + ", Price: " + str(self.price) + "Size: " + str(self.size) + ", Print: " + str(self.print1) + "Material:" + str(self.material)) def print_sum(self): print("This " + self.type + " is " + str(self.colour) + " colour") @staticmethod def print_static_sum(): print("Total price of all dishes = " + str(Dishes.total_price)) if __name__ == "__main__": cup = Dishes() plate = Dishes("Plate", "Green", 80, "Flowers", "plastic", 100) kettle = Dishes("Kettle", "Red", 150, "Dots", "metal", 500) cup.to_string() plate.to_string() kettle.to_string() Dishes.print_static_sum() plate.print_sum() kettle.print_sum()
#Ryan #Practice Using expression and conditonal statements #An expression is a problem that must be solved #5 + 5 is "arithmetic" expression x = 5 + 5 #Fumctions/methods must be resolved as expressions as well answer = input("What is your name?") #Comparison expression resolve as Ture/False print(7>7) print(7>=7) print(x==10) print(x>10 or x<10) #A conditional statements run if its condition is Ture / not False if answer == "Bob": print("Hello, Bob! Welcome Bob!") print("This line also prints if your name is Bob") elif answer == "Vadim": print("Hey! You still owe me money!") else: print("Sorry, I only talk to Bobs") print("This line isn't inside of the if statement, and prints regardless") # ^ If checks a condition # ^ Elif checks a condition if the previous condions were not Ture # ^ You can have as meny elif's as you want # ^ Else runs if no prior conditions were true
# Devin Hurley # 03/14/2013 from numpy import matrix import pylab from numpy import polyfit # define def polyfit(x,y,m): # we want this function to output coefficients N=len(x) b = matrix([[0.0]] *(m+1)) # column vector M = matrix([[0.0]*(m+1)]*(m+1)) for k in range(m+1): for i in range(N): b[k] = b[k] + y[i]*x[i]**k for k in range(m+1): for j in range(m+1): # lets begin to make the sum over i, the other part of the succinct equation for i in range(N): M[k,j] = M[k,j] + x[i]**(k+j) a = (M.I)*b return a def f(x): return (x**3) # how do we test this? x = [0,1,2,3] y = [0,1,8,27] newY = [0.0]*len(y) for i in range(4): step = i newY[i] = f(step) pylab.hold(True) pylab.plot(x,y,'o') #pylab.show() print polyfit(x,y,3) # equation is y=x, in y=mx + b form. # a (x,y,2) means a quadratic, works in higher dimension as well, add more points to the x and y. print polyfit(x,y,3) # a straight line, i.e. a best fit line pylab.plot(x,newY) pylab.show()
# Devin Hurley # CSIS310 # 02/17/2013 # part a - derivative of f is # # 12*x^2 - x*e^((x^2)/2) # # part b - at x = 2 # it reaches the root near 1 # # problem number 13 import math def fnc(x): y = 4*(x*x*x) -1 - math.exp((x*x)/2) return y def fncPrime(x): y = 12*x*x - x*math.exp((x*x)/2) return y def newtonian(x, tol): x1 = x x2 = 1+x lineCount = 0 while(math.fabs(x2-x1) > (tol*2) or math.fabs(fnc(x1)) > (tol*2)): x2 = x1 - fnc(x1)/fncPrime(x1) x1 = x2 lineCount = lineCount + 1 return [lineCount, (x1 + x2)/2] print "" z = newtonian(3.0, 0.0001) print z print ""
#!/bin/python import random class FairDice(object): """ These 'dice' implement the probability mechanics described by Sid Meier and Rob Pardo at GDC 2010. see: http://www.shacknews.com/featuredarticle.x?id=1302 They are meant to be more 'fair' than normal probability, following natural language. If '5 times out of 10' you want something to happen, call 'dict = FairDice(5,10)'. If you call 'dice.roll()' 5 times, it will absolutely return True by the 5th time, if not sooner. Set "linear" to False if you want it to work precisely this way. Otherwise, it will become slightly more likely to return True with each roll. """ tries = 0 chances = (1.0,10.0) history = [] linear = True def __init__(self, times, outof): """ "x times out of y", these dice will return true when roll() is called @param times: "x times..." @param outof: "out of y", this must be greater than 0 """ self.chances = (float(times), float(outof)) def roll(self): """ @return: True or False """ if self.linear: base_prob = (self.chances[0] + self.tries) / self.chances[1] else: base_prob = self.chances[0] / self.chances[1] if random.random() < base_prob: # FIXME : no history for now... can't think of a good way to implement it #self.history.append(self.tries) self.reset() return True else: self.tries += 1 return False def reset(self): """ Reset the dice so that the next roll will be treated as the first in a series. """ self.tries = 0
import re from .box import Box class Interface: def __init__(self, table): self.table = table self.goal_tree = self.table.goal_tree self.box_names = Box.boxes_names def parse_question(self, question: str): """This method parses the queston and creates a dictionary that describes the question. Its type, objective and components""" parsed = {} question = question.lower().split(' ') # Determine the type of question if 'how' in question: parsed['type'] = 'how' elif 'why' in question: parsed['type'] = 'why' else: parsed['type'] = None return parsed # Determine the objective of the question if 'put' in question: parsed['obj'] = 'put_on' elif 'clear' in question and 'top' in question: parsed['obj'] = 'clt' elif parsed['type'] == 'why' and 'move' in question: parsed['obj'] = 'move' else: parsed['obj'] = None return parsed # Determine the components of the question components = [] for part in question: if re.search(r'[bB]\d*', part): components.append(part.capitalize()) if parsed['obj'] == 'move': for part in question: if re.search(r'\[\d*,\d*\]', part): components.append(str(list(eval(part)))) parsed['comps'] = components return parsed def question_aire(self): """this is the main method that handles all I/O with the user and uses the other methds to do its job""" while True: q = input("Question: ") if q == 'e' or q == 'exit': break parsed = self.parse_question(q) answer = self.answer_question(parsed) print("Answer:", answer, '\n') def search_tree(self, item, return_index=False): """And auxillary method to aid in answering questions by searching for item in the goal tree. when return_index = True, item's index in the goal tree is also returned""" for i, e in enumerate(self.goal_tree): if e == item: return (item, i) if return_index else item else: raise KeyError("Search term not found!") def answer_question(self, parsed_question: dict): """This is the method that actually answers question by taking as input a parsed question""" final_answer = "I didn't do that" try: obj, components, q_type = parsed_question['obj'], parsed_question['comps'], parsed_question['type'] except KeyError: return "Invalid question" # This if statement is needed bcz the structure of items for clt and others is slightly different and it may be changed. if obj == 'clt': search_term = [obj, components[0]] else: search_term = [obj, components] # If the action said in parsed question is not found in the goal tree then there is no point continuing try: searched_item = self.search_tree(search_term, True) except KeyError: return final_answer # The following block comes up with an answer to all possible scenarios if q_type == 'how': if obj == 'put_on': if search_term in self.goal_tree: final_answer = f"By first clearing the top of {components[1]} and then of {components[0]}" \ f" and then moving {components[0]} to the top of {components[1]}" elif obj == 'clt' and search_term in self.goal_tree: final_answer = "By moving " l = self.goal_tree[searched_item[1] + 1:] # part of the goal tree where our solution exists for o, c in l: if o is not 'move': break final_answer += f"{str(c[0])} to {str(c[1])} and " final_answer = final_answer[:-5] elif q_type == 'why': if obj == 'put_on' and search_term in self.goal_tree: final_answer = "Because you told me to" elif obj == 'clt' and search_term in self.goal_tree: l = self.goal_tree[:searched_item[1]] for o, c in reversed(l): if o is 'put_on': final_answer = f"To put {c[0]} on top of {c[1]}" break else: continue elif obj == 'move': index = searched_item[1] l = self.goal_tree[:index] if index + 1 == len(self.goal_tree): last_move = True elif self.goal_tree[index + 1][0] == 'put_on': last_move = True else: last_move = False for o, c in reversed(l): if o == 'put_on': final_answer = f"To put {c[0]} on top of {c[1]}" break elif o == 'clt' and last_move is False: final_answer = f"To clear the top of {c}" break return final_answer
#!/usr/bin/env Python # Aingty Eung # 9/07/2017 # EE 381 Project 2 # Bernoulli Trials, Bayes' Rule, and General Probability print('\nBernoulli Trial Simulation.') # Cast the number to float for success rate p = float(input('Enter the Probability of Success: ')) k = int(input('Enter the number of trails: ')) # Using the old random number generator code from Project 1 # The norm N is 10,000 N = 10000 # The adder A is 4,857 A = 4857 # The multiplier is 8,601 M = 8601 # Input the Seed #S = input("Enter seed number. ") S = 1; for i in range(k): S = (M*S + A)%N R = S/float(N) # Float division is used to obtain the number on (0,1) print(format(R, '.4f')) # Print number to 4 decimal places # End of Project 1 random number generator if R < p: print('Success!\n') else: print('Failure!\n')
def reverse(n): rev = 0 while (n > 0): digit = n % 10 rev = rev * 10 + digit n = n // 10 print("Reverse of the number:", rev) n=int(input("Enter number: ")) reverse(n)
""" Python tkinter GUI Tutorial # 123 Custom Message Box Popup Simple example of custom message boxes """ from tkinter import * class Application(Frame): def __init__(self, master): super().__init__(master) self.master.title("ProMCS") self.master.geometry("400x100") self.popup = Button(master=self.master, text="Popup", command=self.show_popup) self.popup.pack(pady=10) self.lbl = Label(master=self.master, text="") self.lbl.pack(pady=10) def show_popup(self): """Create custom messagebox with yes and no option""" self.popup_box = Toplevel(root, background="lightblue") self.popup_box.title("Message") self.popup_box.geometry("300x80") message = Label(master=self.popup_box, text="Do you agree with me?", background="lightblue") message.pack(pady=10) btn_frame = Frame(master=self.popup_box) btn_frame.pack() btn_y = Button(master=btn_frame, text="Yes", command=lambda: self.choice("yes")) btn_y.grid(row=0, column=0) btn_n = Button(master=btn_frame, text="No", command=lambda: self.choice("no")) btn_n.grid(row=0, column=1) def choice(self, option): self.popup_box.destroy() if option == "yes": self.lbl.config(text=f"You have picked {option}") else: self.lbl.config(text=f"You have picked {option}") if __name__ == '__main__': root = Tk() app = Application(master=root) app.mainloop()
#!/usr/bin/python3 """ Module used to add two arrays """ def validUTF8(data): """ Method that determines if a data set represents a valid UTF-8 encoding. 1. A character in UTF-8 can be 1 to 4 bytes long 2. The data set can contain multiple characters Args: data (lst): List of integers. Each integer represents 1 byte of data, therefore you only need to handle the 8 least significant bits of each integer Returns: - True if data is a valid UTF-8 encoding, - False if not """ # Number of bytes in the current UTF-8 character n_bytes = 0 # For each integer in the data array. for num in data: # Get the binary representation. We only need the least # significant 8 bits for any given number. bin_rep = format(num, '#010b')[-8:] # If this is the case then start processing a new UTF-8 character. if n_bytes == 0: # Get the number of 1 in the beginning of the string. for bit in bin_rep: if bit == '0': break n_bytes += 1 # 1 byte characters if n_bytes == 0: continue # Invalid scenarios according to the rules of the problem. if n_bytes == 1 or n_bytes > 4: return False else: # Processing integers which represent bytes which are a part of # a UTF-8 character. So, they must adhere to the pattern # `10xxxxxx`. if not (bin_rep[0] == '1' and bin_rep[1] == '0'): return False # We reduce the number of bytes to process by 1 after each integer. n_bytes -= 1 # This is for the case where we might not have the complete data for # a particular UTF-8 character. return n_bytes == 0
#!/usr/bin/python3 """ Module used to """ def rain(arr): """ Given a list of non-negative integers representing walls of width 1, calculate how much water will be retained after it rains. Assume that the ends of the list (before index 0 and after index walls[-1]) are not walls, meaning they will not retain water. If the list is empty return 0. Arguments --------- - walls : list list of non-negative integers. Returns ------- - rain : Int integer indicating total amount of rainwater retained """ if (arr is None): return 0 if not (isinstance(arr, list)): return 0 n = len(arr) if (n < 2): return 0 if not all(isinstance(n, int) for n in arr): # any no integer return 0 if (len([num for num in arr if num < 0]) > 0): # any negative return 0 rain = 0 for i in range(1, n - 1): # Find the maximum element on its left left = arr[i] for j in range(i): left = max(left, arr[j]) # Find the maximum element on its right right = arr[i] for j in range(i + 1, n): right = max(right, arr[j]) # Update the maximum of rain collected rain += (min(left, right) - arr[i]) return rain
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv from enum import unique with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ # Revised with effective solution idea, first time heard # about difference function in Python - thank you. outgoing = set() non_telemarketers = set() # add calls for outgoing to the outgoing set from col[0] # add calls from col[1] in the non_telemarketers set # can't be a telemarketer if number appears in this col for call in calls: outgoing.add(call[0]) # get outgoing caller / texter non_telemarketers.add(call[1]) # can't be a telemarketer if in this row # add cols for texts (outgoing/receiving) to the non_telemarketers # can't be a telemarketer if sent / received a text, so add to # non_telemarketers set for text in texts: non_telemarketers.add(text[0]) non_telemarketers.add(text[1]) # using the difference of sets, get the difference of outgoing and non_telemarketers # to find telemarketers - since these are just for loops, they are # individual O(N) operations or 2 for loops O(2N) - simplified to O(N) operation telemarketers = outgoing.difference(non_telemarketers) print("These numbers could be telemarketers: ") for telemarketer in sorted(telemarketers): print(telemarketer) # Runs O(N log N) Time - searching for telemarketers is just looping through # N records for calls, adding them to a set of outgoing calls or non_telemarketers # then going through another loop with N records for texts, and adding # cols to the non_telemarketers set. # Two for loops is O(2N), which is simply O(N). # Calculating the difference between outgoing and non_telemarketers to get # telemarketers is a O(1) operation. # Sorting takes O(N log N) worst case, so this is the bigger # time operation making this operation O(N log N). # O(N) space - just need space for the dictionary and set that # hold the unique callers and telemarketers
""" You are given the head of a linked list and two integers, i and j. You have to retain the first i nodes and then delete the next j nodes. Continue doing so until the end of the linked list. Example: linked-list = 1 2 3 4 5 6 7 8 9 10 11 12 i = 2 j = 3 Output = 1 2 6 7 11 12 """ class Node: def __init__(self, data): self.data = data self.next = None # helper functions for testing purpose def create_linked_list(arr): if len(arr)==0: return None head = Node(arr[0]) tail = head for data in arr[1:]: tail.next = Node(data) tail = tail.next return head def print_linked_list(head): while head: print(head.data, end=' ') head = head.next print() def skip_i_delete_j(head, i, j): """ :param: head - head of linked list :param: i - first `i` nodes that are to be skipped :param: j - next `j` nodes that are to be deleted return - return the updated head of the linked list """ i_count = 1 curr = head while curr: if i_count % i == 0: j_count = 0 while j_count < j and curr.next: curr.next = curr.next.next j_count += 1 i_count += 1 curr = curr.next return head ll = create_linked_list([1,2,3,4,5,6]) ll = skip_i_delete_j(ll, 2, 3) print_linked_list(ll)
def tax_calculation(): income = int(input()) tax = 0 if 15527 < income < 42708: tax = 15 elif 42707 < income < 132407: tax = 25 elif income >= 132407: tax = 28 calculated_tax = int(round(income * (tax / 100))) print(f"The tax for {income} is {tax}%. That is {calculated_tax} dollars!") tax_calculation()
import math import time #Problem 5: 2520 is the smallest number that can be divided by each # of the numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible # by all of the numbers from 1 to 20? checklist=[11,13,14,16,17,18,19,20] def findSmall_1(): for x in xrange(2520,2000000000,2520): if(x%11==0 and x%13==0 and x%14==0 and x%19==0 and x%16==0 and x%17==0 and x%18==0 and x%20==0): return x def findSmall_2(): for x in xrange(2520,2000000000,2520): if all(x%lis==0 for lis in checklist): return x #Start run time clock for function 1 start = time.time() # Set for loop for multiple interations for x in range(1): a1 = findSmall_1() #Return run time elapsed1 = (time.time() - start) #Start run time clock for function 1 start = time.time() # Set for loop for multiple interations for x in range(1): a2 = findSmall_2() #Return run time elapsed2 = (time.time() - start) #print answer print('Smallest number evenly divisible by range(1:20): %s Found in: %s seconds') % (a1,elapsed1) print('Smallest number evenly divisible by range(1:20): %s Found in: %s seconds') % (a2,elapsed2)
import math import time #Problem 3: The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143? primeFactor = 1 #Determine largets Factor def primeFactors(val): #loop for 2 as a factor while val%2==0: primeFactor = 2 val = val/2 #loop for odd number as factors f = 3 while val!=1: while val % f == 0: primeFactor = f val = val/f f += 2 return primeFactor #Return Value and run time start = time.time() # Set for loop for multiple interations for x in range(1): a = primeFactors(600851475143) elapsed = (time.time() - start) #print answer print('The largest Prime Factor is : ' + str(a) + ' Found in : ' + str(elapsed) + ' Seconds')
class Glass: cnt = 1 def __init__(self, capacity: float = 200, occupied: float = 0): self.capacity_volume: float self.occupied_volume: float self.cnt = Glass.cnt if not isinstance(capacity, (int, float)): raise TypeError("Некоррктный тип capacity") if not isinstance(occupied, (int, float)): raise TypeError("Некоррктный тип occupied") if occupied > capacity or capacity < 0 or occupied < 0: raise ValueError("Некорректный объем") self.capacity_volume = capacity self.occupied_volume = occupied Glass.cnt += 1 def __del__(self): Glass.cnt -= 1 print(f"cnt: {Glass.cnt}") def __str__(self): return (f"Glass str: {self.cnt}") def __repr__(self): return (f"Glass repr: {self.cnt}")
import random #First Prompt print "Well hello hail and harty traveler, welcome to my humble Inn. May I ask your name?" NAME= raw_input(" Full Name?:") print "Ahhh so your name is "+NAME+ " ....I see." #Second Prompt CLASS= raw_input(" What Vocation are you?:_") print "Ohh so you are a mighty, "+CLASS+", Very interesting..." #Third Prompt HOME= raw_input("Where do you hail from?:_") print "I see, so you come from the land of "+HOME+", How nice." ###Luck Stay(Random) LUK= random.randint(0,3) #Fifth Prompt print "Tell me more about yourself!" STR= raw_input("What is your strength value?") DEX= raw_input("What is your dexterity value?") # LUK= raw_input("How much of a wizard are you?(0-3!)") #stats, class, beasts print "I see, I see... So you have "+STR+" points of STR and "+DEX+" points of DEX ." CharacterInfo= {'Name':NAME, 'Class':CLASS, 'Home':HOME} BEASTS= ["Dragon", "Ogre", "Litch", "Hell Hound"] BEAST_HP= random.randint(100, 999) # damage= BEAST_HP # i = random.randint(0,3) #Original random # for i in range(0, int(LUK)): # if LUK > 4: # LUK == 4 # else: # LUK == LUK # # BEAST=BEASTS[i] # SKILL= raw_input ("What Skill do you wish to use?") def playerDPS(a, b): DPS = (a * b) return DPS #Print Beast Encounter # print "Your adventure begins wile you make your way to an old dungeon were you face a mighty "+BEAST+"!" # # def playerDPS(a, b): # DPS = (a * b) # print "You inflict "+str(DPS)+" points of damage!" # if DPS <= BEAST_HP: # print("The "+BEAST+" Has proven more of a challenge than expected, you decide to retreat and return another day.") # else: # print("Congratulations you have slain the "+BEAST+" and you return with a bounty of great spoils!") # DPS= playerDPS(int(STR), int(DEX)) # DPS= playerDPS(1,5) ##Original Loop for monster fight while BEAST_HP > 0: BEAST_HP= BEAST_HP - DPS print "You inflicted "+str(DPS)+". on the foul Beast, it now has "+str(BEAST_HP) if BEAST_HP <= 0: print "You have slain the foul beast, you precede to go thru the dungeon and find a trove of gold and jewls."
import re with open("files/regex-test.txt") as names: for line in names.readlines(): valid = re.match("([A-Z][a-z]+)( [A-Z][a-z]*){1,2}", line) if valid: print(valid.group()) else: print(valid) names.close()
# codinf:utf-8 # 插入即表示将一个新的数据插入到一个有序数组中,并继续保持有序。例如有一个长度为N的无序数组, # 进行N-1次的插入即能完成排序;第一次,数组第1个数认为是有序的数组,将数组第二个元素插入仅有1个有序的数组中; # 第二次,数组前两个元素组成有序的数组,将数组第三个元素插入由两个元素构成的有序数组中...... # 第N-1次,数组前N-1个元素组成有序的数组,将数组的第N个元素插入由N-1个元素构成的有序数组中,则完成了整个插入排序。 def insert_sort(nums): count = len(nums) for i in range(1, count): for j in range(i, 0, -1): # 将第i个元素加入到已排序列最后一位,倒序遍历,如果比前一位小,则调换顺序 if nums[j] < nums[j - 1]: nums[j], nums[j - 1] = nums[j - 1], nums[j] return nums list = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10] print(insert_sort(list))