text
stringlengths
37
1.41M
string,v =input().split() v=int(v) for i in range(v): print(string)
str=input() n=False m=False for i in str: if(i.isdigit()==True): m=True if(i.isalpha()==True): n=True if(n and m): print("Yes") else: print("No")
# Version 1 import psycopg2 import psycopg2.extras try: connection = psycopg2.connect(user = "postgres", password = "password", host = "localhost", port = "5432", dbname = "gtd") except: print("Connection failed") cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # print(connection.get_dsn_parameters()) # cursor.execute("""SELECT datname from pg_database""") # rows = cursor.fetchall() # print("\nShow me the databases:\n") # for row in rows: # print(" ", row[0]) cursor.execute("""Select * from main where country_txt = 'Mexico' """) rows = cursor.fetchall() print("Rows:") counter = 0 for row in rows: print(row['iyear']) # counter += 1 # if(counter>10):break
class Solution: def isValid(self, s: str) -> bool: a=[] for i in s: if '['==i or '('==i or "{"==i: a.append(i) else: if len(a)==0: return False if '}'==i: if a.pop() !="{": return False if ')'==i: if a.pop() !="(": return False if ']'==i: if a.pop() !="[": return False return True and len(a)==0
# Definition for singly-linked list. import json class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: hhead=ListNode(0,head) nextH=hhead.next root=head surplus=False while( nextH): crtH=hhead.next nextH=crtH.next for i in range(k-1): if(nextH==None): surplus==True break nnextH=nextH.next nextH.next = crtH crtH = nextH hhead.next.next = nnextH nextH=nnextH tmp = hhead.next hhead.next = crtH hhead = tmp if(surplus): crtH=hhead.next nextH=crtH.next for i in range(k-1): if(nextH==None): break nnextH=nextH.next nextH.next = crtH crtH = nextH hhead.next.next = nnextH nextH=nnextH tmp = hhead.next hhead.next = crtH hhead = tmp return root.next def stringToIntegerList(input): return json.loads(input) def stringToListNode(input): # Generate list from the input numbers = stringToIntegerList(input) # Now convert that list into linked list dummyRoot = ListNode(0) ptr = dummyRoot for number in numbers: ptr.next = ListNode(number) ptr = ptr.next ptr = dummyRoot.next return ptr def listNodeToString(node): if not node: return "[]" result = "" while node: result += str(node.val) + ", " node = node.next return "[" + result[:-2] + "]" def main(): import sys import io def readlines(): for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'): yield line.strip('\n') lines = readlines() while True: try: line = next(lines) head = stringToListNode(line); line = next(lines) k = int(line); ret = Solution().reverseKGroup(head, k) out = listNodeToString(ret); print(out) except StopIteration: break if __name__ == '__main__': main()
names = ["Arvind", "Bala", "Shiva", "Dinesh"] # Mutable #Indexing [] # print(names[0]) #valid # print(names[4]) #IndexError: Index out of range # Mutable # print("Im printing from line number 8 of list {}".format(names)) # names[0] = "Ganesh" # print(f"Im printing from line number 10 of list {names}") # list methods # 1 upper only for strings # print(names.upper()) # AttributeError: list object has no attribute upper # 1 append() # name = "Ganesh" # names.append(name) # print(names) # 2 Extend method # l = ["Ganesh", "Barath", "Surya"] # names.extend(l) # print(names) # 3 pop # * removes the last element by default # * can pass an index value to remove the particular field # names.pop() # print(names) # print(dir(names))
# new list l1 = [1, 2, 3, 3, 5, 5, 5, 5] # print(l) #append # word = "Animal" # print(dir(l)) # l.append(word) # print(l) # new_list = l.append(word) This will return None #pop # print("line number 14", l) # r = l.pop() # print("line number 16", l) # print(r) # print(l.pop(3)) # returns the removed element of the index. # print(l) # x = l.pop() # to store the popped value of varibale we can store it in a new variable # print("I removed", x) # print(l) # print(l) # copy # l2 = l1.copy() # print("printing l1", l1) # print("printing l2", l2) #clear # l1.clear() # print(l1) #count # print(l1.count(5)) count the number of same(occurences) elements in a list # l2 = ['a', 'b', 'c', 'd', 'e', 'e'] # print(l2.count('e')) #extends and append # l2 = ['a', 'b', 'c', 'd', 'e', 'e'] # l2.append(l1) # print("Append of l2", l2) # l2.extend(l1) # print("Extend of l2", l2) # print(l2) #index # print(l1.index(2)) prints the index of an element.\ #sort # l = [5, 2, 3, 4, 1] # l.sort() # print(l) #reverse # l = [1, 2, 3, 4, 5] # l.reverse() # print(l) #remove # refer difference between pop and remove # l = [1, 2, 3, 4, 5] # x = l.remove(4) # print(l) # print(x) #insert # l = [1, 2, 3, 4, 5] # l.insert(4, 6) #1st parameter index, replace value # print(l)
name = "shiva\n" # to get the length # print(name) #len() # print(len(name)) #INDEX Shiva # 01234 #to get the first element # print(name[2]) # upto but not including # print(name[0:3]) # reverse a string # print(name[::-1]) #Indexing is not possible # name[0] = "R" # print(name) # dir() # print(dir(name)) # # to convert to upper case use upper() function # print(name.upper()) # to convert to upper case use lower() function # print(name.lower()) # use capitalize function # print(name.capitalize()) # strip() method # txt = " my name is " # print(txt.strip()) #check if the word is upper or lower # print(name.isupper()) # replace # print(name) # print(name.replace("\n", "")) # join # print("*".join(name)) # format # name = "shiva" # print("my name is {}".format(name)) # f string # name = "shiav" # print(f"my name is {name}")
name = "Ananya" #len to return the length of a given item # print(len(name)) # #index A N A N Y A # 0 1 2 3 4 5 # print(name[::]) # print(name[:]) # print(name[::-1]) # reverse a string in python # if, elif , else #if # user_input = int(input("Enter your age: ")) # if user_input == 50: # print("Valid") # else: # print("Invalid") # x = 10 # if not x: # print("Something") # else: # print("It's valid") #conditional statements user = input("Enter a or b: ") if user == 'a': print("valid") elif user == 'b': print("b is also valid") else: print("you have entered wrong choice") x = 10 if not x: print("Something") else: print("It's valid")
""" Given a set of start and end tuples find the minimum number of meeting rooms required for hosting all the meetings Time Complexity = O(NlogN) {time to sort the input} Space Complexity O(N) """ """ Solution 1 with stacks . """ def meeting_rooms_1(timings): starts = sorted([t[0] for t in timings]) ends = sorted([t[1] for t in timings ]) meeting_rooms_occupied = 0 max_meeting_rooms_occupied = 0 while starts : if starts[0] > ends[0] : meeting_rooms_occupied -= 1 ends = ends[1:] elif starts[0] == ends[0] : ends = ends[1:] starts = starts[1:] else : meeting_rooms_occupied += 1 max_meeting_rooms_occupied = max(max_meeting_rooms_occupied,meeting_rooms_occupied) starts = starts[1:] return max_meeting_rooms_occupied """ Solution 2 with priority queue """ def add(s, queue): if not queue: queue.append(s) return head = filter(lambda x: x < s, queue) return head + [s] + queue[len(head):] def meeting_rooms_2(timings): sorted_timings = sorted(timings, key=lambda x: x[0]) queue = [] max_size = 0 for i in sorted_timings: if (not queue) or (i[0] > queue[0]): queue = queue[1:] add(i[1], queue) max_size = max(max_size, len(queue)) return max_size
# coding: utf-8 class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def vertex_info(self, vertex): """returns vertex info""" return self.__graph_dict[vertex] def add_vertex(self, vertex): """ add vertex if it is not in "dict" """ if vertex not in self.__graph_dict: self.__graph_dict[vertex] = [] def add_edge(self, edge): """ add edge to graph """ edge = set(edge) (v1, v2) = tuple(edge) if v1 in self.__graph_dict: self.__graph_dict[v1].append(v2) else: self.__graph_dict[v1] = [v2] def __generate_edges(self): """ Generate edges. Edges are represented as "sets" """ edges = set() for vertex in self.__graph_dict: for neighbour in self.__graph_dict[vertex]: edges.add((vertex, neighbour)) return edges def find_all_paths(self, start_vertex, end_vertex, path=[]): """ find all paths from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return [path] if start_vertex not in graph: return [] paths = [] for vertex in graph[start_vertex]: if vertex not in path: found_paths = self.find_all_paths(vertex, end_vertex, path) for p in found_paths: paths.append(p) return paths def diameter(self): """ calculates the diameter of the graph """ v = self.vertices() pairs = [(v[i], v[j]) for i in range(len(v) - 1) for j in range(i + 1, len(v))] smallest_paths = [] for (start, end) in pairs: paths = self.find_all_paths(start, end) if len(paths) > 0: smallest = sorted(paths, key=len)[0] smallest_paths.append(smallest) smallest_paths.sort(key=len) diameter = len(smallest_paths[-1]) - 1 return [diameter, smallest_paths[-1]] def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: " for edge in self.__generate_edges(): res += str(edge) + " " return res
password_to_change = input() command = input() while command != "Done": if command == "TakeOdd": password_to_change = password_to_change[1:len(password_to_change):2] print(password_to_change) elif command.split()[0] == "Cut": index = int(command.split()[1]) length = int(command.split()[2]) remove = password_to_change[index:index + length] password_to_change = password_to_change.replace(remove, "", 1) print(password_to_change) elif command.split()[0] == "Substitute": move_out = command.split()[1] move_in = command.split()[2] if move_out not in password_to_change: print("Nothing to replace!") else: password_to_change = password_to_change.replace(move_out, move_in) print(password_to_change) command = input() print(f"Your password is: {password_to_change}")
phrase = tuple(input()) unique_characters = set(phrase) for char in sorted(unique_characters): print(f"{char}: {phrase.count(char)} time/s")
import sys first_list = input() num = int(input()) new_list = first_list.split() min_size = sys.maxsize removal = "" last_list = "" for j in range(num): smallest = min_size for i in new_list: if int(i) < smallest: smallest = int(i) removal = str(smallest) new_list.remove(removal) last_list = ", ".join(new_list) print(f"[{last_list}]")
#empty list empty=[] print("This is an empty list: "+ str(empty)) #list of strings acronyms = ["LOL","IDK","TBH"] word="tada" print("This is a list of acronyms: "+ str(acronyms)) print("This is the last item in list: "+acronyms[len(acronyms)-1]) ## adding to list print("\n\n") acronyms.append("TGIF") acronyms.append("BFN") print("After adding to list: "+str(acronyms)) ## removing from list print("\n\n") acronyms.remove("BFN") print(acronyms) print("Now removing the from list: "+acronyms[2]) del acronyms[2] print("After removing from list: "+str(acronyms)) ##if statement print("\n\n") if word in acronyms: print(word + " is in list\n") ##elif word not in acronyms: else: print(word + " is not in list\n") #for loopys for acronym_in_acronyms in acronyms: print(acronym_in_acronyms) #list of numbers print("\n\n") numbers=[5,10,15,20] print("This is a list of numbers: "+ str(numbers)+"\n")
def spin_words(sentence): res = "" words = sentence.split() for word in words: if len(word) >= 5: res += word[::-1] else: res += word res += " " return res[:-1]
N = input() number_set = input() total = 0 for i in range(int(N)): total += int(number_set[i]) print(total)
''' Repeating Characters ''' T = input() for i in range(int(T)): S = input() # Split the string S = S.split() # Setting the repeat variables R = S[0] # Setting the paragraph variables P = "" for j in range(len(S[1])): P += S[1][j] * int(R) print(P)
def lone_tally_check(p): """ standard evaluation method, checks each boxes tally set to see if there is only one possible value left for that box. :param p: the puzzle """ # map = p.box_map progress = False # cycle through every box in the puzzle for key, box in p.box_map.items(): # Only check boxes with unknown value if box.value == 0: # if only one item in tally set, it's the value for the box if len(box.tally) == 1: # get the only value in the tally set value = max(box.tally) # and update the puzzle p.update_new_known(key, value) progress = True # if no values left in tally, the puzzle has an error if len(box.tally) == 0: p.no_solution = True p.error_description = f'No valid value to put in row {p.box_map[key].row + 1}, ' \ f'column {p.box_map[key].col + 1}' p.set_final_string() break p.method_log.append(["lone tally", progress]) if p.num_unknown_boxes() == 0: p.solved = True p.set_solution_string() def only_place_check(p): """ standard evaluation method, checks each axis to see if any values are possible in only one box of the axis :param p: the puzzle """ progress = False # Loop through all 27 axes for key, axis in p.axis_map.items(): # If all values in axis are known, skip if len(axis.unknown) == 0: continue box_set = axis.box_set # need to copy because Unknown set can change unknowns = axis.unknown.copy() # loop through the values not yet known in the axis for value in unknowns: # how many tallies have the value as a possibility count = 0 # box ID for last box where this value was a possibility latest = 0 # loop through every box in axis for j in box_set: # if the value of the box is unknown and the tally set contains it if value in p.box_map[j].tally: # increment the count count += 1 # record the box ID latest = j # if find more than one instance, go on to the next value if count == 2: break # if there's only one place for the value if count == 1: p.update_new_known(latest, value) progress = True # the value is found in no tally sets, there's an error in the puzzle if count == 0: p.no_solution = True p.set_final_string() dims = ['row', 'column', 'big square'] p.error_description = f'No place for {value} in {dims[p.axis_map[key].dimension]} ' \ f'{p.axis_map[key].index + 1}' break p.method_log.append(["only place", progress]) if p.num_unknown_boxes() == 0: p.solved = True p.set_solution_string() def basic_solve_attempt(p): """ run through the two basic solving methods until there's no more progress :param p: the puzzle """ while p.num_unknown_boxes() != 0: # track how many unknowns there are at the beginning of the loop blanks = p.num_unknown_boxes() # first basic method lone_tally_check(p) if p.solved or p.no_solution: break # second basic method only_place_check(p) if p.solved or p.no_solution: break # If there's no progress, end attempt if p.num_unknown_boxes() == blanks: break
""" Sort file based on a column. """ import sys def parser(): return { 'help': 'Sort file based on a column.' } def add_arguments(parser): """ Parse arguments Args: parser (argparse.ArgumentParser) """ parser.add_argument('-dt', "--datatype", action="store", type=str, dest="datatype", help="Datatype of the input file, e.g., tsv or csv.", default="tsv") parser.add_argument( "-c", "--column", action="store", type=str, dest="column", help="Property/column to sort on.") parser.add_argument(metavar="input", dest="input", action="store", default=sys.stdin) def run(datatype, column, input): # import modules locally import socket import sh sh.mlr('--%s' % datatype, 'sort', '-f', column, input, _out=sys.stdout, _err=sys.stderr)
import MapReduce import sys mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: order_id # value: whole record key = record[1] value = record mr.emit_intermediate(key, value) def reducer(key, value): # key: order_id # value: a list of lists (the records of 'order' and all matching 'line_items') # find the list in value that has element 0 == 'order' for orders in value: if orders[0] != "order": # if the first element of the list is 'order', continue # move to the next list for line_items in value: # iterate over the list of lists again join_list = [] if not line_items[0] == "line_item": # if the first element of the list is not 'line_item' continue # go to the next list else: # otherwise join_list.append(orders) join_list.append(line_items) # add the list to join_list mr.emit(([val for subl in join_list for val in subl])) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
import sys sum_int = 0 while True: line_str = sys.stdin.readline() if not line_str: break sum_int += int(line_str) print(sum_int)
#!/usr/bin/env python "在windows 7下每次运行打印不同的结果" import threading import time COUNT_INT = 0 def adder(): "间隔地给COUNT_INT加1" global COUNT_INT COUNT_INT += 1 time.sleep(0.5) COUNT_INT += 1 def main(): global COUNT_INT listThread = [] for i_int in range(100): Thread = threading.Thread(target=adder) listThread.append(Thread) Thread.start() for i_Thread in listThread: i_Thread.join() print(COUNT_INT) if __name__ == "__main__": main()
#!/usr/bin/env python """ 分隔字符串或文本文件并交互的进行分页 """ def more(text_str, num_lines=15): lines = text_str.splitlines() while lines: chunk = lines[: num_lines] lines = lines[num_lines: ] for line in chunk: print(line) if lines and input('More?') != '': break if __name__ == '__main__': import sys if len(sys.argv) == 1: more(sys.stdin.read()) else: more(open(sys.argv[1]).read())
#!/usr/bin/env python "每次都打印200,因为共享资源的访问已经同步化" import threading import time COUNT_INT = 0 def adder(count_int_mutex): "间隔地给COUNT_INT加1" global COUNT_INT with count_int_mutex: COUNT_INT += 1 time.sleep(0.5) with count_int_mutex: COUNT_INT += 1 def main(): global COUNT_INT count_int_mutex = threading.Lock() listThread = [] for i_int in range(100): Thread = threading.Thread(target=adder, args=(count_int_mutex,)) listThread.append(Thread) Thread.start() for i_Thread in listThread: i_Thread.join() print(COUNT_INT) if __name__ == "__main__": main()
#!/usr/bin/env python "利用bool列表在父线程中探知子线程何时结束" import _thread as thread MUTEX = thread.allocate_lock() NUMS_THREAD_INT = 10 LISTBOOL = [False for i_int in range(NUMS_THREAD_INT)] def counter(id_int, count_int): "数数" for i_int in range(count_int + 1): MUTEX.acquire() print('[{}] -> {}'.format(id_int, i_int)) MUTEX.release() LISTBOOL[id_int] = True # 向主线程发送信号 def main(): for i_id_int in range(NUMS_THREAD_INT): thread.start_new_thread(counter, (i_id_int, 100)) while False in LISTBOOL: pass print('Main thread exiting...') if __name__ == '__main__': main()
# Python program to print # red text with green background from colorama import Fore, Back, Style print(Fore.BLUE + 'some red text') print(Back.CYAN + 'and with a green background') print(Style.BRIGHT + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')
import requests # # build URL # path_url = 'http://api.postcodes.io/postcodes/' # argument = 'CR03SW' # post_codes = requests.get(path_url + argument) # # print(post_codes) # #turn this into a dictionary # dict_response = post_codes.json() # # #getting out data # print(dict_response.keys()) # # #getting the response # print(dict_response['status']) # print(dict_response['result'].keys()) # print(dict_response['result']['admin_district']) # for key in dict_response['result']: # print(key, '-->', dict_response['result'][key]) # Task ## 1- Play around with API and getting data # This prints out the keys in the get request # print(dict_response.keys()) # This prints out the status of the website (which inlcudes the URL and argument passed through) # print(dict_response['status']) # This prints out the results as a dictionary # print(dict_response['result']) # 2 - from a postcode retrieve: lonitude, latitude, nuts, admin ward # This prints out the longitude, latitude, nuts and admin_ward # print(dict_response['result']['longitude']) # print(dict_response['result']['latitude']) # print(dict_response['result']['nuts']) # print(dict_response['result']['admin_ward']) # 3 - build a function that returns a lat of a postcode def postcode_lat(): ask_postcode = input('What is the postcode you want to find the latitude of?') path_url = 'http://api.postcodes.io/postcodes/' result = requests.get(path_url + ask_postcode.strip()) post_code_dictionary = result.json() return post_code_dictionary['result']['latitude'] # 4 - build another function that returns the log of a post code def postcode_long(): ask_postcode = input('What is the postcode you want to find the longitude of?') path_url = 'http://api.postcodes.io/postcodes/' result = requests.get(path_url + ask_postcode.strip()) post_code_dictionary = result.json() return post_code_dictionary['result']['longitude'] # 5 - Allows me to search a postcode, and get the following data exported to a TXT file: # - postcode # -lonitude, latitude, nuts, admin ward def search_postcode(): ask_postcode = input('What is the postcode you would like to search for?') path_url = 'http://api.postcodes.io/postcodes/' result = requests.get(path_url + ask_postcode.strip()) post_code_dictionary = result.json() # ask for file creation name ask_file = input('Please name the file you would like to insert your postcode data into') file_name = ask_file + '.txt' #create the file try: with open(file_name, 'w+') as file_created: file_created.write(f"Postcode: {post_code_dictionary['result']['postcode']}." f" Longitude: {post_code_dictionary['result']['longitude']}." f" Latitude: {post_code_dictionary['result']['latitude']}." f" Nuts: {post_code_dictionary['result']['nuts']}." f" Admin Ward: {post_code_dictionary['result']['admin_ward']}.") except TypeError as error: print('Please ensure you have all the correct information') finally: print('Completed')
def length_of_longest_substring(s: str): length: int = 0 last_index = {} n: int = len(s) l: int = 0 r: int = 0 while l < n and r < n: c = s[r] if c in last_index: l = max(l, last_index[c] + 1) last_index[c] = r length = max(length, r - l + 1) r += 1 # i: int = 0 # for j, value in enumerate(s): # if value in last_index: # i = max(last_index[value], i) # length = max(length, j - i + 1) # last_index[value] = j + 1 return length
class Calculator: def __init__(self,lis): self.tot=0 self.lis=lis def sum(self): self.tot=sum(self.lis) print(self.tot) def avg(self): if self.tot!=0: self.av=self.tot/len(self.lis) else: self.av=sum(self.lis)/len(self.lis) print(self.av) if __name__=='__main__': li=[] #li=[1,2,3,4,5] while True: num=int(input('enter num (0->end):')) if num==0: break li.append(num) cal1=Calculator(li) cal1.sum() cal1.avg()
class Ksztalty: def __init__(self, x, y): self.x=x self.y=y self.opis = "To będzie klasa dla ogólnych kształtów" def pole(self): return self.x * self.y def obwod(self): return 2 * self.x + 2 * self.y def dodaj_opis(self, text): self.opis = text def skalowanie(self, czynnik): self.x = self.x * czynnik self.x = self.y * czynnik class Kwadrat(Ksztalty): def __init__(self, x): self.x =x self.y=x def __add__(self, other): return Kwadrat(self.x+other.x) kwad1=Kwadrat(5) kwad2=Kwadrat(3) kwad3=kwad1+kwad2 print(str(kwad3.x))
import time N = int(1e6) start = time.time() # Inefficient: creaend a list of length N in memory, # then iterate over it for k in range(N): pass end = time.time() print 'Iterating through a list of', N, 'elements took', \ round(1000*(end - start),2), 'milliseconds.' start = time.time() for l in xrange(N): pass end = time.time() print 'Iterating through an xrange generator of', N, 'elements took', \ round(1000*(end - start),2), 'milliseconds.'
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 17:14:48 2021 @author: chung """ semi_annual_raise = 0.07 r = 0.04 total_cost = 10**6 down_payment = 0.25 * total_cost months = 36 annual_salary = float(input("Annual Salary: ")) def total_save(portion_saved): total_saved = 0 monthly_salary = annual_salary/12 for i in range(1, months + 1): if i % 6 == 0: monthly_salary = monthly_salary * (1 + semi_annual_raise) total_saved += portion_saved * monthly_salary total_saved = total_saved * (1+r/12) return total_saved high = 10000 low = 0 steps = 0 portion_saved = (high+low)/20000 while abs(total_save(portion_saved) - down_payment) > 100: if total_save(portion_saved) < down_payment: low = round(portion_saved * 10000) else: high = round(portion_saved * 10000) if steps > 100: print("Not possible") break portion_saved = (round(high+low))/20000 steps += 1 print(f"Best savings rate: {portion_saved}") print(f"Steps in bisection search: {steps}")
#1 x = int(input("sum_of_elements: ")) num = 0 full_list = [] even_list = [] while True: full_list.append(num) if num%2 == 0: even_list.append(num) elif len(even_list) == x: print(full_list) print(even_list) print(sum(even_list)) break if num == 0: num = 1 else: num = full_list[-1] + full_list[-2]
class BinarySearch: def __init__(self,input_array): #Конструктор класса self.array=input_array self.array_len=len(self.array) self.Right=self.array_len-1 self.Left=0 self.Stop_Search=False self.Success=False def Step(self,N): #выполняет один шаг поиска: делит текущий диапазон на два, продолжает сокращение рабочего диапазона, #корректируя Left и Right, при необходимости фиксирует завершение поиска last_right=self.Right last_left=self.Left for i in range(0,self.array_len): if type(self.array[i])!= int: return -1 if self.array_len==0: return None middle_index=(self.Left+self.Right+1)//2 middle_value=self.array[middle_index] if N>middle_value: self.Left=middle_index elif N<middle_value: self.Right=middle_index else: self.Success=True if self.Left==self.Right or (last_left==self.Left and last_right==self.Right): self.Stop_Search=True else: pass def GetResult(self): for i in range(0,self.array_len): if type(self.array[i])!= int: return -1 if self.array_len==0: return -1 if self.Success==True: return 1 else: if self.Stop_Search==False: return 0 elif self.Stop_Search==True: return -1 #12 Занятие def GallopingSearch(array,N): #Блок 1 : Поиск диапазона нахождения искомого элемента i=1 max_index=len(array)-1 right=len(array)-1 left=0 index=2**i-2 while True: if array[index]==N: return True elif array[index]<N: i+=1 index=2**i-2 if index>max_index: index=max_index right=max_index if array[index]==N: return True else: return False else: pass else: right=index left=2**(i-1)-1 break #Блок 2 : Создание массива и поиск позиции с помошью метода Step класса BinarySearch res_arr=[] for j in range(left,right+1): res_arr.append(array[j]) Output=BinarySearch(res_arr) while Output.Success!=True: Output.Step(N) if Output.Stop_Search==True and Output.Success!=True: return False else: pass return True """ arr=[1,23,90,97,101,104,567] print(GallopingSearch(arr,7)) """
# data = [ # ['ram', 'sita', 'gita', 'hari'], # ['laxmi', 'binita', 'anish', 'rahul'], # ['sophia', 'kamal', 'sunita', 'test'], # # ] # # for names in data: # for name in names: # print(name) # for name in data: # print(name) # # for a in range(10): # print(a) # # x = 1 # # while x < 10: # print(x) # x += 1 # x = 10 # # while x > 1: # print(x) # x -= 1 num = int(input("Enter any number: ")) increment = 1 while increment <=num: print(increment) increment += 1
import requests import csv from bs4 import BeautifulSoup as Soup url = "https://university.graduateshotline.com/ubystate.html#NC" fieldnames = ['Name', 'State', 'Website'] # CSV file Open def csv_file(): with open('US Universities by State.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() # CSV file write row def save_to_csv(data): with open('US Universities by State.csv', 'a') as csvfile: writer = csv.writer(csvfile) writer.writerow(data) def getData(div): try: raw = div.a name = raw.text.strip() url = raw["href"] except AttributeError: name = div.text.strip() url = None return name, url def main(): res = requests.get(url) if int(res.status_code) == 200: html_soup = Soup(res.content, "lxml") cont = html_soup.find('ol') # List body university, State, website = None, "Alabama", None name = cont.findChild() while name: if name.find('big'): nState = name.find('big').text else: nState = State if name.find('ul'): try: par = name.a.text.strip() except: par = "" for li in name.findAll('li'): university, website = getData(li) university = par + ", " + university print(university, website) save_to_csv([university, State, website]) else: university, website = getData(name) print(university, website) save_to_csv([university, State, website]) if State!=nState: State= nState name = name.findNextSibling() return True else: return False if __name__ == "__main__": csv_file() print ("Done " if main() else "Error ")
''' This outline will help solidify concepts from the Mathematical Operators lesson. Fill in this outline as the instructor goes through the lesson. ''' #1) Make two string variables and use the + operator to combine them into #one new variable. var = " Hello" + " there" #2) Make two int variables and use the + operator to combine them into #one new variable. x = 4 + 6 #3) Make two int variables and use the - operator to combine them into #one new variable. y = 9 - 1 #4) Make two float variables and use the - operator to combine them into #one new variable. g = 8.45 - 0.45 #5) Make two int variables and use the * operator to combine them into #one new variable. h = 6 * 7 #6) Make one string variable and one int variable and use the * operator #to combine them into one new variable. d = "Araceli" * 3 #7) Make two int variables and use the / operator to combine them into #one new variable. v = 8 / 8 #8) Make two float variables and use the / operator to combine them into #one new variable. t = 2.4 / 2.2 #9) Make two int variables and use the % operator to combine them into #one new variable. o = 5 % 4 #10) Make two int variables and use the // operator to combine them into #one new variable. f = 4 // 4 #11) Make two int variables and use the ** operator to combine them into #one new variable. a = 2 ** 2 #12) Make any type of operation with a common SYNTAX error b = 5 5
import requests import io from os import path import pandas as pd import plotly.graph_objs as go def fetch_data(path_to_data, file_name='../data/latest_crime_data.csv'): """ Request the dataset from https://www.ethnicity-facts-figures.service.gov.uk/crime-justice-and-the-law/policing/number-of-arrests/. Args: path_to_data (string) representing the url of the data (csv). file_name (string) representing the location to store the downloaded data. Returns: ../data/latest_crime_data.csv containing the raw data from the url. The size of the new file and whether or not it has been overwritten or newly created. """ no_content_error_message = 'No content has been downloaded! Please check url.' try: # request the data from the given url r = requests.get(path_to_data) # converts byte-code to string content = r.content.decode('utf-8') if content == None: return no_content_error_message else: df = pd.read_csv(io.StringIO(content)) return df except Exception as e: print("Unable to fetch dataset from url.") print(e) def clean_data(): """ Clean the data of redundant columns, missing values, data quality etc. Args: None Returns: df (pandas.DataFrame) containing cleaned version of data. """ # url where data source is located csv_url = "https://www.ethnicity-facts-figures.service.gov.uk/crime-justice-and-the-law/policing/number-of-arrests/latest/downloads/number-of-arrests.csv" # call read_data() df = fetch_data(csv_url) # strip any whitespace in column names df.columns = [i.strip() for i in df.columns] # remove columns with low cardinality low_card_cols = df.columns[df.nunique() == 1].tolist() if low_card_cols != []: df.drop(low_card_cols, axis=1, inplace=True) else: del low_card_cols # remove notes column due to number of missing values. This may change in future. df.drop(['Notes'], axis=1, inplace=True) # drop ethnicity type as it is completely correlated with ethnicity df.drop(['Ethnicity_type'], axis=1, inplace=True) # sort data by time df.sort_values(by='Time', ascending=True, inplace=True) df.reset_index(drop=True, inplace=True) # clean the number of arrests by removing commas from numbers and removing non-numeric chars df['Number of arrests'] = df['Number of arrests'].str.replace("[^0-9]", "").str.strip() # create a flag column to show rows with missing values in number of arrests df['Missing_Number_of_Arrests'] = df['Number of arrests'].apply(lambda x: 1 if x == '' else 0) # convert arrests column to int df['Number of arrests'] = df['Number of arrests'].replace('', -1) df['Number of arrests'] = df['Number of arrests'].astype(int) # make new ethnic groups like those on data source website description df.Ethnicity = df.Ethnicity.apply(lambda x: 'Asian' if x in ['Asian', 'Indian', 'Pakistani', 'Bangladeshi', 'Any other asian'] else 'Black' if x in ['Black Caribbean', 'Black African', 'Any other black background', 'Black'] else 'White' if x in ['White Irish', 'White British', 'White', 'Any other white background'] else 'Other' if x in ['Chinese', 'Other', 'Any other ethnic group'] else 'Mixed' if 'mixed' in x.lower() else x) return df def filter_df(how='all'): """ Filters the data to include only stats about population as a whole. Args: how (string) ['all', 'not all'] representing how to filter the data: 'all' selects all rows where column values = all 'not all' selects all rows where column values != all Returns: filtered_df (pandas.DataFrame) containing filtered data """ # call clean_data() df = clean_data() if how == 'all': filtered_df = df.loc[(df.Geography=='All') & (df.Gender=='All') & (df.Ethnicity=='All') & (df.Age_Group=='All') & (df.Missing_Number_of_Arrests == 0)].copy() elif how == 'not all': filtered_df = df.loc[(df.Ethnicity != 'All') & (df.Gender != 'All') & (df.Age_Group != 'All') & (df.Geography != 'All') & (df.Missing_Number_of_Arrests == 0)].copy() else: raise Exception("Parameter value not recognised. Value must be 'all' or 'not all'.") return filtered_df def plot_data(): """ Plots the data to be displayed on the frontend of the web application. Args: None Returns: figures (list) containing the plotly visualisations (dict) """ # call clean_data() and filter_data() df_all = filter_df() df_not_all = filter_df(how='not all') df = clean_data() # plot the rate of arrests by gender plot_one = [] df_gender_pivot = df.loc[(df.Missing_Number_of_Arrests == 0) & (df.Ethnicity=='All') & (df.Geography=='All') & (df.Age_Group=='All') & (df.Gender != 'All')].copy() df_gender_pivot = df_gender_pivot.pivot_table(index='Time', columns=['Gender'], values='Rate per 1,000 population by ethnicity, gender, and PFA', aggfunc='sum') plot_one.append( go.Scatter( x=df_gender_pivot.index.tolist(), y=df_gender_pivot.Female.tolist(), mode='lines+markers', marker=dict( symbol=200 ), name='Female', line=dict( color="aquamarine" ) ) ) plot_one.append( go.Scatter( x=df_gender_pivot.index.tolist(), y=df_gender_pivot.Male.tolist(), mode='lines+markers', marker=dict( symbol=200 ), name='Male', line=dict( color="yellow" ) ) ) layout_one = dict( title="Rate of Arrests Arrests by Gender per Year", font = dict( color="white" ), plot_bgcolor='transparent', paper_bgcolor="transparent", xaxis=dict( title='Year', color='white', showgrid=False, tickangle=60 ), yaxis=dict( title="Rate of arrests (per 1000 people)", color='white' ), ) # plot arrests by ethnicity - use grouping that are specified on data source website df_ethnic_pivot = df.loc[(df.Missing_Number_of_Arrests == 0) & (df.Ethnicity != 'All') & (df.Age_Group == 'All') & (df.Geography == 'All') & (df.Gender == 'All')].copy() df_ethnic_pivot = df_ethnic_pivot.loc[df_ethnic_pivot.Ethnicity != 'Unreported'] df_ethnic_pivot['Rate per 1,000 population by ethnicity, gender, and PFA'] = df_ethnic_pivot['Rate per 1,000 population by ethnicity, gender, and PFA'].astype(int) df_ethnic_pivot = df_ethnic_pivot.pivot_table(index='Time', columns=['Ethnicity'], values='Rate per 1,000 population by ethnicity, gender, and PFA', aggfunc='sum') plot_two = [] colors = ['aquamarine', 'yellow', 'skyblue', 'tomato', 'magenta'] for eth, col in zip(df_ethnic_pivot.columns, colors): plot_two.append( go.Scatter(name=eth, x=df_ethnic_pivot.index.tolist(), y=df_ethnic_pivot[eth].tolist(), line=dict( color=col ), mode='lines+markers', marker=dict( symbol=102 ) ) ) layout_two = dict( title="Rate of Arrests by Ethnicity per Year", font = dict( color='white' ), xaxis=dict( title="Year", color='white', showgrid=False, tickangle=60 ), yaxis=dict( title="Rate of arrests (per 1000 people)", color="white" ), paper_bgcolor='transparent', plot_bgcolor='transparent' ) # plot the top 10 forces per year df_forces = df.loc[(df.Missing_Number_of_Arrests == 0) & (df.Ethnicity == 'All') & (df.Age_Group == 'All') & (df.Gender == 'All') & (df.Geography != 'All')].copy() df_forces = df_forces.loc[~df['Rate per 1,000 population by ethnicity, gender, and PFA'].str.contains('N/A')] df_forces['Rate per 1,000 population by ethnicity, gender, and PFA'] = df_forces['Rate per 1,000 population by ethnicity, gender, and PFA'].astype(int) df_forces_arrest_rates = df_forces.groupby(['Geography'])['Rate per 1,000 population by ethnicity, gender, and PFA'].mean().sort_values(ascending=False) top10_forces = df_forces_arrest_rates.index.tolist()[:10] bottom10_forces = df_forces_arrest_rates.index.tolist()[-10:] df_top10_forces = df.loc[(df.Missing_Number_of_Arrests == 0) & (df.Ethnicity == 'All') & (df.Age_Group == 'All') & (df.Gender == 'All') & (df.Geography.isin(top10_forces))].copy() df_top10_forces_pivot = df_top10_forces.pivot_table(index='Time', columns=['Geography'], values='Rate per 1,000 population by ethnicity, gender, and PFA', aggfunc='sum') df_top10_forces_pivot.at['2017/18', 'Lancashire'] = 14 # lancashire didnt record 17/18 data so fill value with year before plot_three = [] colors = ['aquamarine', 'yellow', 'skyblue', 'tomato', 'magenta', 'blue', 'chartreuse', 'cyan', 'navajowhite', 'hotpink'] for force,col in zip(df_top10_forces_pivot.columns, colors): plot_three.append( go.Scatter( x=df_top10_forces_pivot.index.tolist(), y=df_top10_forces_pivot[force].tolist(), name=force, mode='lines+markers', line=dict( color=col ), marker=dict( symbol=200 ) ) ) layout_three = dict( title="Police Forces with Highest Rates of Arrest", font = dict( color='white' ), xaxis=dict( title="Year", color='white', showgrid=False ), yaxis=dict( title="Rate of arrests (per 1000 people)", color="white" ), paper_bgcolor='transparent', plot_bgcolor='transparent' ) # plot rate of arrest for ethnicity for top 5 and bottom 5 forces top5_forces = df_forces_arrest_rates.index.tolist()[:6] bottom5_forces = df_forces_arrest_rates.index.tolist()[-6:] df_ethnic_pivot = df.loc[(df.Missing_Number_of_Arrests == 0) & (df.Ethnicity != 'All') & (df.Age_Group == 'All') & (df.Geography.isin(top5_forces + bottom5_forces)) & (df.Gender == 'All')].copy() df_ethnic_pivot = df_ethnic_pivot.loc[df_ethnic_pivot.Ethnicity != 'Unreported'] df_ethnic_pivot['Rate per 1,000 population by ethnicity, gender, and PFA'] = df_ethnic_pivot['Rate per 1,000 population by ethnicity, gender, and PFA'].astype(int) df_force_ethnic_groups = df_ethnic_pivot.groupby('Geography') forces_dict = dict() forces_layout_dict = dict() for name, group, in df_force_ethnic_groups: colors = ['aquamarine', 'yellow', 'skyblue', 'tomato', 'magenta'] plot_tmp = [] tmp = group.pivot_table(index='Time', columns=['Ethnicity'], values='Rate per 1,000 population by ethnicity, gender, and PFA', aggfunc='sum') for eth, col in zip(tmp.columns, colors): plot_tmp.append(go.Scatter( name=eth, mode="lines+markers", x=tmp.index.tolist(), y=tmp[eth].tolist(), line=dict( color=col ), marker=dict( symbol=200 ) )) forces_dict[name] = plot_tmp forces_layout_dict[name] = dict( title=name, font = dict( color='white' ), xaxis=dict( title="Year", color='white', showgrid=False, tickangle=60 ), yaxis=dict( title="Rate of arrests (per 1000 people)", color="white" ), paper_bgcolor='transparent', plot_bgcolor='transparent' ) # append all plotly graphs to a list figures = [] figures.append(dict(data=plot_one, layout=layout_one)) figures.append(dict(data=plot_two, layout=layout_two)) figures.append(dict(data=plot_three, layout=layout_three)) for i, j in zip(forces_dict.items(), forces_layout_dict.items()): if i[0] in top5_forces: figures.append(dict(data=i[1], layout=j[1])) for i, j in zip(forces_dict.items(), forces_layout_dict.items()): if i[0] in bottom5_forces: figures.append(dict(data=i[1], layout=j[1])) return figures
# Import necessary libraries import numpy as np import mnist import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical #Load the dataset train_images = mnist.train_images() train_labels = mnist.train_labels() test_images = mnist.test_images() test_labels = mnist.test_labels() img_share = mnist.test_images() #Normalize the images, changing pixel values from [0,255] to [0,1] train_images = (train_images/255) test_images = (test_images/255) #Flatten images to pass into neural network train_images = train_images.reshape((-1,784)) test_images = test_images.reshape((-1,784)) print(train_images.shape) print(test_images.shape) #Build the model model = Sequential() model.add( Dense(128, activation='relu', input_dim=784)) model.add( Dense(64, activation='relu')) model.add(Dense(10, activation='softmax')) #Compile model #Loss: how well the model did on training, tries to improve using optimizer model.compile( optimizer='adam', loss='categorical_crossentropy', metrics = ['accuracy'] ) #Train the model model.fit( train_images, to_categorical(train_labels), epochs = 10 ) # Create predictions using the model predictions = model.predict(test_images) # Create a plot for each prediction and display it to the user for i in range(len(test_images)): plt.grid(False) plt.imshow(img_share[i], cmap=plt.cm.binary) # Display the actual value on the bottom plt.xlabel("Actual: " + str(test_labels[i])) # Display the prediction as well as the confidence on the top plt.title("Prediction: " + str(np.argmax(predictions[i])) + "\nConfidence: " + str(predictions[i][np.argmax(predictions[i])])) plt.show()
# -*- coding: utf-8 -*- import sys from Tkinter import * app = Tk() app.title("Aplicacion grafica en python") etiqueta = Label(app, text="Hola mundo!!!") boton = Button(app, text="OK!!") etiqueta2 = Label(app, text="otra etiqueta") etiqueta.pack()#si no se agrega la etiqueta.pack() el controlo no se agrega a la ventana de tkinter boton.pack() etiqueta2.pack() app.mainloop()#si no se coloca el mainloop no se muestra la ventana
#domino con cadenas print 'dominocadenas.py' def jugardomino(ficha1,ficha2): fichaa=ficha1.split('-',1) fichab=ficha2.split('-',1) #print fichaa[1] posible='Si es posible' noposible='No es posible' print fichaa[0] if (fichaa[0]==fichab[0]): print posible elif (fichaa[0]==fichab[1]): print posible elif (fichaa[1]==fichab[0]): print posible else: print noposible #print ficha1,ficha2 ficha1='3-1' ficha2='36-2' jugardomino(ficha1,ficha2)
from typing import Optional class State: """ This class represents a State of an automaton """ def __init__(self, name: Optional[str] = None): self.name: str = name def __eq__(self, other) -> bool: if not isinstance(other, type(self)): return NotImplemented return str(self) == str(other) def __hash__(self) -> int: return hash(self.name) def __str__(self) -> str: return str(self.name)
# 1 Intro to List print("\n# 1") a = [1, 2, 3,] print(a) b = ['a', 'b', 'c',] print(b) c = [1, 'x', 10, 'abc', 10.0,] print(c) # 2 Indexing and Slicing print("\n# 2") a = ['a', 'b', 'c', 'd', 'e', 'feg',] print("a:", a) print() print("a[3]:", a[3]) print("a[2:5]:", a[2:5]) print("a[-3:]:", a[-3:]) print("a[-1][:-2]:", a[-1][:-1]) # 3 List Methods print("\n# 3") team = ["Ceos", 2018, "8th",] nums = [2, 4, 4, 1,] words = ["alssong", "dalssong", "pythong",] print("team:", team) print("nums:", nums) print("words:", words) print() print("len(words):", len(words)) print("max(nums):", max(nums)) print("min(nums):", min(nums)) print("sum(nums):", sum(nums)) print("nums.count(0):", nums.count(0)) print("nums.index(1):", nums.index(1)) team.reverse() print("After team.reverse():", team) team.clear() print("After team.clear():", team) nums.append(38) print("After nums.append(38):", nums) nums.extend([9,1]) print("After nums.extend([9,1]):", nums) nums.remove(4) print("After nums.remove(4):", nums) words.insert(1, 'hago') print("After words.insert(1, 'hago'):", ' '.join(words)) words.insert(-1, 'han') print("After words.insert(-1, 'han'):", ' '.join(words)) print("nums + words:", nums + words) print("nums * 2:", nums * 2)
# 1 Odd, Even print("\n# 1") a = int(input("Enter a number: ")) if a%2 == 0: print("It's even number!") else: print("It's odd number!") # 2 +, - / Odd, Even print("\n# 2") a = int(input("Enter a number: ")) if a > 0 and a %2 == 0: print(f"{a} is positive even number!") elif a < 0 and a%2 == 0: print(f"{a} is negative even number!") elif a > 0 and a%2 == 1: print(f"{a} is positive odd number!") elif a < 0 and a%2 == 1: print(f"{a} is negative odd number!") else: print(f"{a} is zero!") # 3 A Multiple of Three but Not Even print("\n# 3") a = int(input("Enter a number: ")) if a >= 0: print(f"{a} is 1-digit number!") elif a >= 10: print(f"{a} is 2-digit number!") elif a >= 100: print(f"{a} is 3-digit number!") elif a >= 1000: print(f"{a} is 4-digit number!") # 4 A Multiple of Three but Not Even print("\n# 4") a = int(input("Enter a number: ")) if a%2 == 0: if a%3 == 0: print(f"{a} is a multiple of both 2 and 3.") else: print(f"{a} is a multiple of 2 but not 3.") else: if a%3 == 0: print(f"{a} is a multiple of 3 but not 2.") else: print(f"{a} is not a multiple of 2 or 3.")
numbers = [2,4,5,6,4,4,2,34,31,32,14,6] def merge_sort(arr): if len(arr)<2: return arr mid = len(arr)//2 left_arr = merge_sort(arr[:mid]) right_arr = merge_sort(arr[mid:]) l = r = 0 merged_arr = [] while l<len(left_arr) and r<len(right_arr): if left_arr[l] < right_arr[r]: merged_arr.append(left_arr[l]) l+=1 else: merged_arr.append((right_arr[r])) r+=1 merged_arr += left_arr[l:] merged_arr += right_arr[r:] return merged_arr print(merge_sort(numbers))
# def my_function(x): # return 5 * x # print(my_function(3)) # print(my_function(5)) # print(my_function(9)) def rectangle(p,l): luas=p*l keliling=2*p + 2*l return luas, keliling p = int(input("panjang = ")) l = int(input("lebar = ")) print(rectangle(p,l))
# passing arguments to decorator def decorator_with_args(decorator_args1, decorator_args2, decorator_args3): def decorator(func): def wrapper(function_args1, function_args2, function_args3): print("The wrapper can access all the variables\n" "\t from the decorator maker:{0} {1} {2} \n" "\t from the function call:{3} {4} {5}\n" "and pass them into the decorator function".format(decorator_args1, decorator_args2, decorator_args3, function_args1, function_args2, function_args3)) return func(function_args1, function_args2, function_args3) return wrapper return decorator pandas = "Pandas" @decorator_with_args(pandas, 'Numpy', 'Sciki-learn') def actual_function(function_args1, function_args2, function_args3): print("This is decorator function and it only known about its args:{0} {1} {2}".format(function_args1, function_args2, function_args3)) actual_function("John", "Science", "Tools")
""" generating random graphs ER and in the in-degree distribution """ import math import matplotlib.pyplot as plt import sys sys.path.append("../../_degree_distributions_for_graphs") import ddg p = 0.2 #probability directed edge from i to j n = 5000 # count nodes er_graph = ddg.make_complete_graph_p(n, p) in_degre_distrib = ddg.in_degree_distribution(er_graph) norm_in_degre_distr = ddg.norm_degree_distribution(in_degre_distrib) graph = norm_in_degre_distr mx = sum(x*graph[x] for x in graph) sigma = sum(((x - mx)**2)*graph[x] for x in graph)**0.5 print mx, sigma plt.plot([math.log10(x) for x in norm_in_degre_distr], [math.log10(norm_in_degre_distr[x]) for x in norm_in_degre_distr], 'o') plt.title('loglog plot of ER normalized in-degree distribution, n = {}, p = {}'.format(n , p)) plt.xlabel('in-degree') plt.ylabel('normalized distribution') plt.show()
class Solution: def isUgly(self, num): reducedNum = num while reducedNum >= 2: if reducedNum % 2 == 0: reducedNum /= 2 else: break while reducedNum >= 3: if reducedNum % 3 == 0: reducedNum /= 3 else: break while reducedNum >= 5: if reducedNum % 5 == 0: reducedNum /= 5 else: break if reducedNum == 1: return True return False if __name__ == "__main__": sol = Solution() num = 11 print(sol.isUgly(num))
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def getInOrder(root): if root is None: return [] left = getInOrder(root.left) this = [root.val] right = getInOrder(root.right) return left + this + right class Solution: def lowestCommonAncestor(self, root, p, q): if root is None or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root elif left: return left elif right: return right if __name__ == "__main__": """ Testing on the tree given in the leetcode example: _______3(A)______ / \ ___5(B)__ ___1(C)__ / \ / \ 6(D) _2(E)_ 0(F) 8(G) / \ 7(H) 4(I) """ A = TreeNode(3) B = TreeNode(5) C = TreeNode(1) D = TreeNode(6) E = TreeNode(2) F = TreeNode(0) G = TreeNode(8) H = TreeNode(7) I = TreeNode(4) A.left = B A.right = C B.left = D B.right = E C.left = F C.right = G E.left = H E.right = I sol = Solution() print(sol.lowestCommonAncestor(A, D, I).val)
#Start with a number n > 1. Find the number of steps it takes to reach one #using the following process: If n is even, divide it by 2. If n is odd, #multiply it by 3 and add 1. import sys import argparse import time def timeit(method): def timed(*args, **kw): ts = time.clock() result = method(*args, **kw) te = time.clock() print '%f sec' % \ (te-ts) return result return timed # iterative implementation def collatzNaive(n): if n<1: return -1 if n == 1: return 0 count = 0 while (n != 1): #python has a weird ternary operator if n % 2 == 0: n /= 2 else: n = n * 3 + 1 count += 1 return count # recursive implementation def collatzRecursive(n): if n < 1: return -1 if n == 1: return 0 if n % 2 == 0: return 1 + collatzRecursive(n/2) else: return 1 + collatzRecursive(n * 3 + 1) #calculates stopping times with memoization def stoppingTimes(n): store = stoppingTimes.store if n < 1: return -1 if n == 1: return 0 if n not in store: if n % 2: store[n] = 1 + stoppingTimes(n * 3 + 1) else: store[n] = 1 + stoppingTimes(n/2) return store[n] stoppingTimes.store = {} #uses the benefits of memoization def calcAll(n): for i in range(n+1): stoppingTimes(i) return stoppingTimes.store[n] def parse(): parser = argparse.ArgumentParser(description='Calculates collatz stopping times') parser.add_argument("num", type=int, help="number to calculate stopping time for") parser.add_argument("-t", "--time", action="store_true", help="set this option to time the results") parser.add_argument("-r", "--recursive", action="store_true", help="set this option to use the recursive function") parser.add_argument("-i", "--iterative", action="store_true", help="set this option to use the iterative function") parser.add_argument("-m", "--memoization", action="store_true", help="set this option to use memoization") args = parser.parse_args() return [args.time, args.recursive, args.iterative, args.memoization, args.num] if __name__ == "__main__": args = parse() if not (args[0]): if not (args[1] or args[2] or args[3]): print collatzNaive(args[-1]) if (args[1]): print "Recursive Result: ", collatzRecursive(args[-1]) if (args[2]): print "Iterative Result: ", collatzNaive(args[-1]) if (args[3]): print "Calculate All", calcAll(args[-1]) else: if not (args[1] or args[2] or args[3]): tb = time.clock() tmp = collatzNaive(args[-1]) te = time.clock() print "Iterative result :", tmp, " took ", (te-tb), " seconds." if (args[1]): tb = time.clock() tmp = collatzNaive(args[-1]) te = time.clock() print "Iterative result :", tmp, " took ", (te-tb), " seconds." if (args[2]): tb = time.clock() tmp = collatzRecursive(args[-1]) te = time.clock() print "Recursive result :", tmp, " took ", (te-tb), " seconds." if (args[3]): tb = time.clock() tmp = calcAll(args[-1]) te = time.clock() print "Memoization result :", tmp, " took ", (te-tb), " seconds."
import unittest class Snap(object): def __init__(self, val): self.next = [] self.val = val def dectCircle(self): # dfs with pruning visited = set() if dfs(self, visited, []): return True else: return False def dfs(snap, visited, path): for friend in snap.next: if friend in visited: continue if friend in path: return True else: path.append(friend) if dfs(friend, visited, path): return True visited.add(snap) return False class myTest(unittest.TestCase): def test(self): snap1, snap2, snap3, snap4, snap5 = Snap(1), Snap(2), Snap(3), Snap(4), Snap(5) snap1.next = [snap2, snap3, snap4] snap2.next = [snap3, snap4] snap3.next = [snap4] snap4.next = [snap3] self.assertTrue(snap1.dectCircle()) unittest.main()
# -*- coding: utf-8 -*- """ Created on Tue Jul 16 14:16:09 2019 @author: IST """ def list_ends(a_list): return [a_list[0], a_list[len(a_list)-1]] a = [1,2,3,4,5] print (list_ends(a))
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 10:23:38 2019 @author: IST """ def fibonacci (eleNum): i= 1 if eleNum == 0 : fib = [] elif eleNum ==1 : fib =[1] elif eleNum ==2: fib = [1,1] elif eleNum > 2: fib = [1,1] while i < eleNum - 1: fib.append(fib[i] +fib [i-1]) i+=1 return fib ele = int (input("Enter a number to generate a fiboncci with it ....")) print(fibonacci(ele))
#1. prediction: 5 def a(): return 5 print(a()) #2. prediction: 10 def a(): return 5 print(a()+a()) #3. prediction: 5 def a(): return 5 return 10 print(a()) #4. prediction: 5 def a(): return 5 print(10) print(a()) #5. prediction: 5 nothing def a(): print(5) x=a() print(x) #6. prediction:3 5 def a(b,c): print(b+c) print(a(1,2)+a(2,3)) #7. prediction: 25 def a(b,c): return str(b)+str(c) print(a(2,5)) #8. prediction: 100, 10 def a(): b=100 print(b) if b<10: return 5 else: return 10 return 7 print(a()) #9. prediction: 7 14 21 def a(b,c): if b<c: return 7 else: return 14 return 3 print(a(2,3)) print(a(5,3)) print(a(2,3)+a(5,3)) #10.prediction:8 def a(b,c): return b+c return 10 print(a(3,5)) #11. prediction: 500 500 300 500 b=500 print(b) def a(): b=300 print(b) print(b) a() print(b) #12. prediction: 500 500 300 500 b=500 print(b) def a(): b=300 print(b) return b print(b) a() print(b) #13. prediction: 500 500 300 300 b=500 print(b) def a(): b=300 print(b) return b print(b) b=a() print(b) #14. prediction:1 3 2 def a(): print(1) b() print(2) def b(): print(3) a() #15. prediction: 1 3 5 10 def a(): print(1) x=b() print(x) return 10 def b(): print(3) return 5 y=a() print(y)
singer = input("選擇歌手:") song = input("選擇歌曲:") class Data: def __init__(self,singer,song): self.singer = singer self.song = song def printSinger(self): if singer == "周杰倫" : print("你選周杰倫") elif singer == "陳奕迅" : print("你選陳奕迅") else : print("還沒儲存這個歌手") def printSong(self): if song == "安靜" : print("只剩下鋼琴陪我") elif song == "淘汰" : print("只能說我輸了") else : print("歌詞庫沒有") a = Data(singer,song) a.printSinger() a.printSong()
name =input("打名字啦,哪次沒名字:") gender =input("性別:") email =input("電子信箱:") dinner =input("晚餐吃:") if name.count("*") != 0 : print("不要亂打啦") else : print(f"名字:{name}") print(f"性別:{gender}") print(f"電子信箱:{email}") print(f"晚餐吃:{dinner}")
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ s = str(x) y = s[: : -1] if y == s: return True else: return False # ========================================= solution = Solution() x1 = 121 x2 = -121 x3 = 11111111111111 print solution.isPalindrome(x1) print solution.isPalindrome(x2) print solution.isPalindrome(x3)
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ times = 1 if n <= 1: return times if n >= 2: times1 = self.climbStairs(n - 1) times2 = self.climbStairs(n - 2) times = times1 + times2 return times # ========================================= solution = Solution() n1 = 6 n2 = 5 print solution.climbStairs(n1) print solution.climbStairs(n2)
# import copy # nums = [1,2,3] # list = copy.copy(nums) # list.append(4) # print nums # print list nums = [1,2,3] list = nums list.append(4) print nums
class Animal(object): def eat(self): print 'I am eating' def drink(self): print 'I am drinking' def sleep(self): print 'I am sleeping' class Bird(Animal): def fly(self): print 'bird can fly!!!' class Person(Animal): def __init__(self): self.head = Head() def speak(self): print 'person can speak!!!' def kantou(self): print '我的头被砍了' class Head(object): def head(self): print 'has a head' # =================================== sparrow = Person() sparrow.speak() head = Head()
#What do the following functions do? #random - generates ramdom float between 0-1 #uniform - generates random float between two numbers #randint - generates ramdom integer between two numbers #Import random here: from random import uniform, randint #Print a random Float between 0.0 & 1.0 print(uniform(0,1)) #Print a random interger between 1 & 10 print(randint(1,10)) #Print a random Float between 10 & 71 print(uniform(10,71)) #Print a random interger between 24 & 98 print(randint(24,98))
#The user enters a yes or no question #The computers returns a random Magic 8 Ball Statement to the awnser. #Here are the statments it should select randomly from to awnser the question. ''' Yes, Definatly It is very likely Maybe That's pretty unlikely Thats impossible Why do you ask me a question you already know the awnser to? 50/50 ''' from random import choice awn = ["yes, Definatly", "It is very likey", "Maybe", "that's pretty unlikely", "thats impossible", "Why do you ask me a question you already know the awnser to?", "50/50"] input("enter a yes or no question:\n") print(choice(awn))
from visdom import Visdom class Plot: def __init__(self, name_x: str, name_y: str, viz: Visdom): """ this class represents a visdom plot. It contains the name of the x axis and the y axis which define the type of the plot :param name_x: the name of the x axis :param name_y: the name of the y axis :param viz: the visdom server object """ self.x_title = name_x self.y_title = name_y self.viz = viz self.window = None def draw_plot(self, dict_vals: dict, name: str, up='insert'): """ this function sends the data of the plot to the visdom server. It takes a dictionary with the required values and extracts the :param dict_vals: :param name: the name of the line :param up: the type of update to perform to the graph :return: display the graph on the visdom server """ # if there is no graph displayed than create a new graph if self.viz is None: return False if self.window is None: window = self.viz.line( X=dict_vals[self.x_title], Y=dict_vals[self.y_title], name=name, opts=dict(xlabel=self.x_title, ylabel=self.y_title)) self.window = window # if there is already a graph than append the line to the existing # graph else: self.viz.line(X=dict_vals[self.x_title], Y=dict_vals[self.y_title], name=name, win=self.window, update=up, opts=dict( xlabel=self.x_title, ylabel=self.y_title)) return True
import numpy as np # Read Values from csv into 2 Lists: X & Y def ols(file): X = [] Y = [] csv = np.genfromtxt(file, delimiter=",") X = csv[:,1] Y = csv[:,2] X[np.isnan(X)]=0 Y[np.isnan(Y)]=0 # Mean x & y x_mean = np.mean(X) y_mean = np.mean(Y) # Calculate Intercept & Slope sum1 = 0 sum2 = 0 for x,y in zip(X,Y): sum1 += ((x - x_mean)*(y - y_mean)) sum2 += ((x - x_mean)**2) slope = (sum1/sum2) intercept = y_mean - (slope*x_mean) # Calculate variance # sum3 = 0 # for x,y in zip(X,Y): # sum3 += (y - ((intercept + slope*x)**2)) # variance = (sum1 / (len(X)-2)) print ("Slope: ", slope) print ("Intercept: ", intercept) #print ("Variance:", variance) ols('question_2.csv')
beatles = ["paul", "john", "ringo"] print(beatles[0]) print(beatles[0:2]) print(len(beatles)) beatles.append("George") print(beatles) beatles[0] = "PAUL" print(beatles) del(beatles[2]) print(beatles) #CRUD # most have it when creating elements # Create -> list.append(element) # Read -> list[index] # Update -> list[index]= new_value # Delete -> delete list[index] for beatle in beatles: print(beatle.capitalize()) # if you also want to have access to index as well use enumerate # adding the 1 to remove the 0 at the beginning for index, beatle in enumerate(beatles): print(f"{index + 1}. {beatle.capitalize()}")
phones = {"john": 4019, "paul": "4121", "dave": "9081", "bob": "4322"} type(phones) print(phones) # do a crud on a dictionary # keys most be unique # What is the phone number of paul #read print(phones["paul"]) #create update is the same phones["paul"]= "1212" print(phones["paul"]) #removing an element del(phones["paul"]) print(phones) for name, num in phones.items(): print(name, num)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1 , l2 ) : res = ListNode(0) next = res add = 0 while True : if l1 == None and l2 == None : if add == 1 : next.next = ListNode(1) break x = l1.val if l1 else 0 y = l2.val if l2 else 0 count = x + y + add add = 1 if count >= 10 else 0 next.next = ListNode(count%10) next = next.next l1 = l1.next if l1 != None else None l2 = l2.next if l2 != None else None return res.next
import math def function(x, y): return (-2*x-y) def euler_explicit_1(x_0, y_0, x, h): n = int((x - x_0)//h + 1) y = y_0 for i in range(1, n+1): del_y = h*function(x_0, y) y = y + del_y x_0 = x_0 + h print(f"y' = {function(x_0,y)}\nh*y' = {h*function(x_0,y)}") print(f"y for {i}th iteration with {round(x_0,3)} is {y}\n") print("=========================================") print("*** Euler Explicit Method ***") print("#############################################") def euler_modified(x_0, y_0, x, h): n = int((x - x_0)//h + 1) y = y_0 for i in range(1, n+1): y_p = y + h*function(x_0, y) initial_slope = function(x_0, y) final_slope = function(x_0+h, y_p) del_y = 0.5*h*(initial_slope + final_slope) y = y + del_y x_0 = x_0 + h print( f"Initial Slope= {initial_slope}\ny_predicted = {y_p}\nFinal Slope = {final_slope}") print(f"h*y'_avg = {del_y}") print(f"y for {i}th iteration with {round(x_0,3)} is {y}\n") print("=========================================") print("*** Euler Modified (Heun) Method ***") print("#############################################") # Generic 2nd order Runge Kutta method with a=0.5, b=0.5, alpha=1, beta=1 denotes Euler Modified Method or Heun Method # Another variation of Runge Kutta Method is explicit midpoint method def rungeKutta_2(x_0, y_0, x, h, a=0.5, b=0.5, alpha=1, beta=1): n = int((x - x_0)//h + 1) y = y_0 for i in range(1, n+1): k1 = h * function(x_0, y) # Generic method below is commented for now. # k2 = h * function(x_0 + alpha*h, y + beta*k1) # k_avg = a*k1 + b*k2 # The below method is used by online solvers and is midpoint method k2 = h * function(x_0 + 0.5*h, y + 0.5*k1) k_avg = k2 y = y + k_avg x_0 = x_0 + h print(f"h*k1 = {k1}\nh*k2 = {k2}") print(f"h*k_avg ={k_avg}") print(f"y for {i}th iteration with {round(x_0,3)} is {y}\n") print("=========================================") print("*** Runge Kutta 2nd order (midpoint method) ***") print("#############################################") def rungeKutta_4(x_0, y_0, x, h): n = int((x - x_0)//h + 1) y = y_0 for i in range(1, n+1): k1 = h * function(x_0, y) k2 = h * function(x_0 + 0.5*h, y + 0.5*k1) k3 = h * function(x_0 + 0.5*h, y + 0.5*k2) k4 = h * function(x_0 + h, y + k3) k_avg = (1/6)*(k1 + 2*k2 + 2*k3 + k4) y = y + k_avg x_0 = x_0 + h print(f"h*k1 = {k1}\nh*k2 = {k2}\nh*k3 = {k3}\nh*k4 = {k4}") print(f"h*k_avg ={k_avg}") print(f"y for {i}th iteration with {round(x_0,3)} is {y}\n") print("=========================================") print("*** Runge Kutta 4th order ***") print("#############################################") def main(): x_0 = 0 y_0 = -1 x = 0.6 h = 0.1 euler_explicit_1(x_0, y_0, x, h) #euler_modified(x_0, y_0, x, h) #rungeKutta_4(x_0, y_0, x, h) #rungeKutta_2(x_0, y_0, x, h) if __name__ == "__main__": main()
""" This file computes the file for the trajectory of the person """ import os import re from jsonfilereader import JsonReader, split_json, pixel_fall, height_person from helper import * def compute_cm(body_parts): """ Given: body_parts – list of body parts position with the order nose, shoulder,elbow, wrist,hip,knee,ankle going from left to right Return: CM – the center of mass computed Abstract: COMPUTE takes a list of body parts position with the order nose, shoulder,elbow, wrist,hip,knee,ankle going from left to right and computes the center of mass of the person. """ ratio = [0.073,0.026,0.016,0.507,0.103,0.043]#Head, upperarm, forarm, trunk, thigh,calf list_centers = [] # compute_cm all the centers! chead = {'x' : body_parts[0]['x'],'y' : body_parts[0]['y']} cluparm = {'x' : (body_parts[1]['x'] + body_parts[3]['x'])/2,'y' : (body_parts[1]['y'] + body_parts[3]['y'])/2} cruparm = {'x' : (body_parts[2]['x'] + body_parts[4]['x'])/2,'y' : (body_parts[2]['y'] + body_parts[4]['y'])/2} clforarm = {'x' : (body_parts[3]['x'] + body_parts[5]['x'])/2,'y' : (body_parts[3]['y'] + body_parts[5]['y'])/2} crforarm = {'x' : (body_parts[4]['x'] + body_parts[6]['x'])/2,'y' : (body_parts[4]['y'] + body_parts[6]['y'])/2} cshoulder = {'x' : (body_parts[1]['x'] + body_parts[2]['x'])/2,'y' : (body_parts[1]['y'] + body_parts[2]['y'])/2} chip = {'x' : (body_parts[7]['x'] + body_parts[8]['x'])/2,'y' : (body_parts[7]['y'] + body_parts[8]['y'])/2} ctrunk = {'x' : (cshoulder['x'] + chip['x'])/2,'y' : (cshoulder['y'] + chip['y'])/2} clthigh = {'x' : (body_parts[7]['x'] + body_parts[9]['x'])/2,'y' : (body_parts[7]['y'] + body_parts[9]['y'])/2} crthigh = {'x' : (body_parts[8]['x'] + body_parts[10]['x'])/2,'y' : (body_parts[8]['y'] + body_parts[10]['y'])/2} clcalf = {'x' : (body_parts[9]['x'] + body_parts[11]['x'])/2,'y' : (body_parts[9]['y'] + body_parts[11]['y'])/2} crcalf = {'x' : (body_parts[10]['x'] + body_parts[12]['x'])/2,'y' : (body_parts[10]['y'] + body_parts[12]['y'])/2} list_centers.append(chead) list_centers.append(cluparm) list_centers.append(cruparm) list_centers.append(clforarm) list_centers.append(crforarm) list_centers.append(cshoulder) list_centers.append(chip) list_centers.append(ctrunk) list_centers.append(clthigh) list_centers.append(crthigh) list_centers.append(clcalf) list_centers.append(crcalf) # compute_cm the center of mass with the ratio xCM = (chead['x']*ratio[0] + (cluparm['x']+cruparm['x'])*ratio[1] + \ (clforarm['x']+crforarm['x'])*ratio[2] + ctrunk['x']*ratio[3] + \ (clforarm['x']+crforarm['x'])*ratio[2] + (clthigh['x']+crthigh['x'])*ratio[4] + \ (clcalf['x']+crcalf['x'])*ratio[5]) #xCM = chead['x'] * ratio[0] yCM = (chead['y']*ratio[0] + (cluparm['y']+cruparm['y'])*ratio[1] + \ (clforarm['y']+crforarm['y'])*ratio[2] + ctrunk['y']*ratio[3] + \ (clforarm['y']+crforarm['y'])*ratio[2] + (clthigh['y']+crthigh['y'])*ratio[4] + \ (clcalf['y']+crcalf['y'])*ratio[5]) #yCM = chead['y'] * ratio[0] CM = {'x':xCM,'y':yCM} list_centers.append(CM) return CM def trajectory(PATHJSON="./JsonFiles/"): """ """ """ Given: PATHJSON – Path for all the json files Return: Nothing, everything is saved in two files "Trajectory" for the trajectory of the center of mass, the nose, the left foot, the right foot and "Confidences" that will contain the confidence of the prediction of the position of the person with Alphapose Abstract: TRAJECTORY saves the trajectory of the center of mass, the nose and the feet in the y-axis The order is 1) Center of mass 2) Nose 3) Left foot 4) Right foot. It also saves the confidence of the prediction of the position of the person with Alphapose """ DIR = "Trajectory" os.system('rm -r '+ DIR) # Remove the directory to be sure that everything is new os.system("mkdir " + DIR) center_x = [] center_y = [] nose_y = [] foot_l = [] foot_r = [] confidences = [] previous_number = 0 total_values = 0 for root, dirs,files in os.walk(PATHJSON): # Find all the files in the directory photos files.sort(key=natural_keys) for filename in files: total_values +=1 """ Take the corresponding photo and json file and apply ratio computation """ image = PATHJSON+filename number = natural_keys(filename.split('.')[0])[1] while (previous_number+1 != number): center_x.append(0) center_y.append(500) nose_y.append(500) foot_l.append(500) foot_r.append(500) confidences.append(0) previous_number +=1 js = PATHJSON+"Photo"+str(format(number,"04"))+".json" js1 = JsonReader(js) body = js1.body_parts() # Add a line here for the confidence of the prediction conf = js1.confidence_value() CM = compute_cm(body) center_y.append(CM['y']) nose_y.append(js1.nose()['y']) foot_l.append(js1.ltankle()['y']) foot_r.append(js1.rtankle()['y']) center_x.append(CM['x']) confidences.append(conf) previous_number = number # Save in a file for later plot name_file = ".".join(("/".join((DIR,PATHJSON.split("/")[-2])),"txt")) f = open(name_file,"w") for i in range(len(center_x)): f.write(str(center_x[i])+" ") f.write("\n") for i in range(len(center_y)): f.write(str(center_y[i])+" ") f.write("\n") for i in range(len(nose_y)): f.write(str(nose_y[i])+" ") f.write("\n") for i in range(len(foot_l)): f.write(str(foot_l[i])+" ") f.write("\n") for i in range(len(foot_r)): f.write(str(foot_r[i])+" ") f.close() f2 = open(DIR+"/Confidences.txt","w") for i in range(len(confidences)): f2.write(str(confidences[i])+"\n") f2.close()
sentence="Zeven Zottegemse zotten zullen zes zomerse zondagen zwemmen zonder zwembroek." myList=sentence.split() print(myList) length=len(myList) print(length) def reverse(s): return s[::-1] print(reverse('help')) l1=[[1,2],[2,5],[3,6]] print(l1 [1]) l1 [1] print("1".isdigit()) print(False) def do(n): global counter #counter = 0 for i in (1,2,'bla'): counter += n return counter counter = 1 print(do(2)) def foo1(x=1): return x*2; foo = (1,2,3,4) print(foo1()) a=[(),[],'hello world'.split()] print(len(a)) l = [1,2,3,4,5,6,7] print(l[:-6]) count = 0 for i in range(len(l)): count=0 for item in l[:-i]: #print('bla') count+=1 #print(count) l = [8,12,3] x=l.sort() y=l[:] l.extend([1]) print(x) print(y==l) print(y) print(l) x=2 r=1 print((x,r)) s='ja' print(s)
# Given a, b, c for a quadratric expression ax2 + bx + c = 0. # Write a function getX that returns the larger of the values for X, # i.e. given x1 = -2 and x2 = 5, getX should return 5. # Formulas # x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a) # x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a) # Solution. import math # set 3 params def getX(a,b,c): try: x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a) ; x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a) if (x1 > x2): print('x1:', x1) else: print('x2:', x2) except ValueError: print("Impossible, No square root of a negative number") getX(2, 101, 14)
import random def shuffleDeck(): suits = {'\u2660','\u2661','\u2662','\u2663'} ranks = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'} deck = [] for suit in suits: for rank in ranks: deck.append(rank + ' ' + suit) random.shuffle(deck) # Now shuffle the deck return deck def dealCard(deck): return deck.pop() def total(hand): values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '1':10, 'J':10, 'Q':10, 'K':10,'A':11} result = 0 numAces = 0 for card in hand: result += values[card[0]] # 0th char is the rank if card[0] == 'A': numAces += 1 while result > 21 and numAces >0: # convert ace from 11 to 1 result -= 10 numAces -= 1 return result def compareHands(house,player): houseTotal = total(house) playerTotal = total(player) if houseTotal > playerTotal: print('You lose.') elif houseTotal < playerTotal: print('You win.') elif houseTotal == 21 and 2 == len(house) < len(player): print('You lose.') # house wins with a blackjack elif playerTotal == 21 and 2 == len(player) < len(house): print('You win.') # players wins with a blackjack else: print('A tie.') def blackjack(): deck = shuffleDeck() house = [] player = [] for i in range(2): player.append(dealCard(deck)) house.append(dealCard(deck)) print('House: {} {}'.format(house[0], house[1])) print(' You: {} {}'.format(player[0], player[1])) answer = input("Hit or stand? (default: hit): ") while answer in {'', 'h', 'hit'}: card = dealCard(deck) player.append(card) print('You got {}'.format(card)) print(player) if total(player) > 21: print('You went over... You lose.') return answer = input('Hit or stand? (default: hit): ') while total(house) < 17: card = dealCard(deck) house.append(card) print('House got {}'.format(card)) print(house) if total(house) > 21: print('House went over... You win.') return compareHands(house,player) blackjack()
import math import numpy as np import itertools from collections import deque from operator import itemgetter def accumulate(edge_array, img_size, threshold=300): """ Main hough transform function. This is an optimized hough transform which doesn't blindly bruteforce every possible radius throughout the image. Instead it finds shapes (a shape is a collection of connected points) and creates a bounding box around this shape. the radius is calculated on the assumption that the shape is a circle by getting the difference between the highest and lowest point in the shape. If it is a circle then this radius is correct, otherwise it will simply fail in accumulation and thresholding. regional accumulation is then performed on the bounding box with the specific radius and if a local maxima is above the threshold then it's assumed to be a circle. """ accumulater_array = np.zeros((img_size[1], img_size[0]), dtype=np.uint32) global_point_set = set() maxima = [] for y in range(img_size[1]): for x in range(img_size[0]): if edge_array[y][x] and (x,y) not in global_point_set: # create a graph of all the points connected to the current point local_point_set = connect_points(edge_array, img_size, (x,y)) global_point_set = global_point_set.union(local_point_set) if len(local_point_set) > 10: xmin = min(local_point_set, key=itemgetter(0))[0] ymin = min(local_point_set, key=itemgetter(1))[1] xmax = max(local_point_set, key=itemgetter(0))[0] ymax = max(local_point_set, key=itemgetter(1))[1] radius = (ymax - ymin) // 2 # make bounding box slightly bigger on all sides for better fit for i in range(1,3): if point_in_array(edge_array, img_size, (xmin-i,0)): xmin = xmin-i if point_in_array(edge_array, img_size, (0,ymin-i)): ymin = ymin-i if point_in_array(edge_array, img_size, (xmax+i,0)): xmax = xmax+i if point_in_array(edge_array, img_size, (0,ymax+i)): ymax = ymax+i bounding_box_top = (xmin, ymin) bounding_box_bot = (xmax, ymax) accumulate_region(edge_array, accumulater_array, img_size, radius, bounding_box_top, bounding_box_bot) local_maxima = find_local_maxima(accumulater_array, img_size, radius, threshold,bounding_box_top, bounding_box_bot) maxima.extend(local_maxima) #normalize array so that it can be converted back to an image max_accumulate = accumulater_array.max() if max_accumulate > 255: ratio = max_accumulate / float(255) accumulater_array = accumulater_array / ratio return (maxima, accumulater_array) def connect_points(edge_array, img_size, p0): """Performs a depth first search to find all connected points to a given point. This should connect all points for a circle""" local_point_set = set() stack = deque() stack.append(p0) while stack: point = stack.pop() if point not in local_point_set: local_point_set.add(point) for y in range(point[1]-1, point[1] + 2): for x in range(point[0]-1, point[0] + 2): if validate_point(edge_array, img_size, (x,y), local_point_set): stack.append((x,y)) return local_point_set def point_in_array(edge_array, img_size, p): if p[0] >= 0 and p[0] < img_size[0] and p[1] >= 0 and p[1] < img_size[1]: return True def validate_point(edge_array, img_size, p, visited): """Check if point is inside the array and check if it has been visited. Helper function for connect_points""" if p[0] >= 0 and p[0] < img_size[0] and p[1] >= 0 and p[1] < img_size[1] and p not in visited: return edge_array[p[1]][p[0]] else: return False def accumulate_region(edge_array, accumulater_array, img_size, radius, region_top, region_bot): """Performs accumulation in a local specified region instead of the whole array""" for y in xrange(region_top[1], region_bot[1]): for x in range(region_top[0], region_bot[0]): if edge_array[y][x]: for theta_d in range(360): theta_r = np.radians(theta_d) x_acc = int(round(x + radius * np.cos(theta_r))) y_acc = int(round(y + radius * np.sin(theta_r))) if x_acc < img_size[0] and x_acc >= 0 and y_acc < img_size[1] and y_acc >= 0: accumulater_array[y_acc][x_acc] += 1 def find_local_maxima(arr, img_size, radius, threshold, region_top, region_bot): """Finds the points in the region above the specified threshold. These points should be circles""" maxima = [] for y in range(region_top[1], region_bot[1]): for x in range(region_top[0], region_bot[0]): if arr[y][x] > threshold: maxima.append((x, y, radius,arr[y][x])) return maxima
# Write a program that detects the ID number hidden in a text. # We know that the format of the ID number is: # 2 letters, 1 digit, 2 letters, 2 digits, 1 letter, 1 digit (For example: AA4ZA11B1). # import re text = "AABZA1111AEGTV5YH678MK4FM53B6" pattern = r"\w\w\d\w\w\d\d\w\d" re.search(pattern, text) for match in re.findall(pattern, text): print(match)
name = "Jose Antonio Amieva" country = "Mexico" age = 25 hourly_wage = 1000000 satisfied = True daily_wage = 100000000000 print("My name is " + name + ", I have " + str(age) + " years old. I am actually living in " + country + " and my wage is " + str(hourly_wage) + " per hour.") print(f"my daily wage is ${daily_wage} and I am satisfied? {satisfied}")
import itertools # The list of candies to print to the screen candyList = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Swedish Fish", "Skittles", "Hershey Bar", "Starbursts", "M&Ms"] # The amount of candy the user will be allowed to choose allowance = 5 # The list used to store all of the candies selected inside of candyCart = [] # Print out options for x in range(len(candyList)): print("["+str(x)+"]" + candyList[x]) for i in range(allowance): uInput = int(input("Number? ")) if uInput == 0: candyCart.append(candyList[0]) elif uInput == 1: candyCart.append(candyList[1]) elif uInput == 2: candyCart.append(candyList[2]) elif uInput == 3: candyCart.append(candyList[3]) elif uInput == 4: candyCart.append(candyList[4]) elif uInput == 5: candyCart.append(candyList[5]) elif uInput == 6: candyCart.append(candyList[6]) elif uInput == 7: candyCart.append(candyList[7]) elif uInput == 8: candyCart.append(candyList[8]) print(candyCart) for candies in candyCart: print(candies)
import csv file = './netflix_ratings.csv' f = open(file) csv_f = csv.reader(f) inputName = input("What tv show or movie do you want to search for? ") rating = "" user_rating = "" a = False for row in csv_f: if row[0] == inputName: rating = row[1] user_rating = row[5] a = True if a == True: print(f"\n{inputName} is rated {rating} with a rating of {user_rating}") else: print(f"\n{inputName} is not on our database! Ponte Buzo, Caperuso!") print(f.read())
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print("Answer is")print(num1 + num2) print("This calculator is made by Vinayak Handa") print(" 20 april 2021")
class Customer: def __init__(self, email): self.email = email self.age = 0 self.last_name = "" self.first_name = "" self.password = "" self.card_number = "" self.security_code = "" def input_age(self): while True: try: age = int(input("Enter age :")) if age < 0: raise ValueError self.age = age break except ValueError: print("Age must be an non negative integer ") def input_password(self): while True: print("\nYour password must be 8-12 characters long containing at least one upper-case letter, " "one lower-case letter, and one number.") password = input("Enter password : ") if not any(c.isupper() for c in password): print("does not contain upper-case") elif not any(c.islower() for c in password): print("does not contain lower-case") elif not any(c.isdigit() for c in password): print("does not contain number") elif len(password) < 8 or len(password) > 12: print("Password should be 8-12 characters long") else: print("\nValid password") self.password = password break def input_card_number(self): while True: card_number = input("Enter 16-digit credit card number : ") if all(c.isdigit() for c in card_number) and len(card_number) == 16: self.card_number = card_number break print("\nCard number must be 16 digits.") def input_security_code(self): while True: security_code = input("Enter 3-digit security code : ") if all(c.isdigit() for c in security_code) and len(security_code) == 3: self.security_code = security_code break print("\nPIN must be three digits.") def input_info(self): self.first_name = input("Enter first name : ") self.last_name = input("Enter last name : ") self.input_age() self.input_password() self.input_card_number() self.input_security_code() def verify_info(self): while True: print("\n------------------------------------------") print("\n 1. First name : {}".format(self.first_name)) print("\n 2. Last name : {}".format(self.last_name)) print("\n 3. Email address : {}".format(self.email)) print("\n 4. Password : {}".format(self.password)) print("\n 5. Age : {}".format(self.age)) print("\n 6. Card number : {}".format(self.card_number)) print("\n 7. Security code : {}".format(self.security_code)) choice = int(input("\nTo correct any entry, enter the entry's number and press RETURN. If everything is " "correct, press 0 :")) if choice == 1: self.first_name = input("Enter first name : ") elif choice == 2: self.last_name = input("Enter last name : ") elif choice == 3: self.email = input("Enter email address : ") elif choice == 4: self.input_password() elif choice == 5: self.input_age() elif choice == 6: self.input_card_number() elif choice == 7: self.input_security_code() elif choice == 0: print("Registration and verification completed for this customer.") break # break from loop after successful verification else: print("Invalid choice. Please choose (1-7).") def output_info(self): return "{} {} {} {} {} {} {}\n".format(self.first_name, self.last_name, self.age, self.email, self.password, self.card_number, self.security_code) if __name__ == '__main__': print("\n Customer 1") email = input("Enter email address : ") customer1 = Customer(email) customer1.input_info() customer1.verify_info() print("\n Customer 2") email = input("Enter email address : ") customer2 = Customer(email) customer2.input_info() customer2.verify_info() f = open("customers.txt", "w") f.write(customer1.output_info()) f.write(customer2.output_info()) f.close() print("\n Data of two customers written to the file 'customers.txt'")
#!/usr/bin/env python import itertools import num2words import re import sys EPS = '<epsilon>' # [start, end] def foo(start, end): s = 1 for i in range(start, end + 1): words = re.split('\W+', num2words.num2words(i)) # removes delimiters isym = str(i) prev = 0 for isym, osym in itertools.izip_longest(str(i), words, fillvalue=EPS): print prev, s, isym, osym prev = s s += 1 print s - 1 # finish state if __name__ == '__main__': start = 0 end = 999999 if len(sys.argv) > 1: end = int(sys.argv[1]) if len(sys.argv) > 2: start = end end = int(sys.argv[2]) foo(start, end)
'''year=int(input('enter your year:')) if(year%4==0): print(year,'is leap year') else: print(year,'is not leap year')''' year=int(input('enter your year:')) if(year%100==0): if(year%400==0): print(year,'is leap') else: print(year,'is not leap') else: if(year%4==0): print(year,'is leap year') else: print(year,'is not leap')
# -*- coding: utf-8 -*- import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import statsmodels.formula.api as smf #Simple Linear Regression Boston = pd.read_csv('../data/Boston.csv', index_col=0) Boston.columns #medv (median house value), lstat(percent of households with low socioeconomic status) lm = smf.ols(formula ='medv ~ lstat', data=Boston).fit() print(lm.summary()) #Obtains confidence intervals for the coefficient estimates print(lm.conf_int()) #Plots with the least squares regression line #Looks like a non-linear association Boston.plot(kind="scatter", x="lstat", y="medv") preds = lm.predict(Boston.lstat) plt.plot(Boston.lstat, preds, c='red') #The plot_regress_exog function is a convenience function that gives a 2x2 plot fig = plt.figure(figsize=(12,8)) fig = sm.graphics.plot_regress_exog(lm, "lstat", fig=fig) #Multiple Linear Regression lm = smf.ols(formula ='medv ~ lstat+age', data=Boston).fit() print(lm.summary()) #Include all predictors all_columns = "+".join(Boston.columns) all_columns.replace("+medv", "") lm = smf.ols(formula ='medv ~' + all_columns, data=Boston).fit() print(lm.summary()) #Interaction Terms lm = smf.ols(formula ='medv ~ lstat+age+lstat*age', data=Boston).fit() print(lm.summary()) #Non-linear Transformations of the Predictors lm2 = smf.ols(formula ='medv ~ lstat+I(lstat**2.0)', data=Boston).fit() print(lm2.summary()) #We can use anova_lm() here to compare the quadratic fit to the linear fit lm = smf.ols(formula ='medv ~ lstat', data=Boston).fit() sm.stats.anova_lm(lm, lm2)
"""Display Manager: Handles all things relating to Pig's core display features.""" import time def print_main_menu(): """Prints Main Menu""" print("Hello! Welcome to Pig.") print("Rules: \n\tRoll a die to see who goes first, ascending-order-wise.") print("\tRoll until you like the score you currently have.") print("""\tHold to keep the score and add it to your total score; \tthen pass the die to the next player.""") print("""\tIf you roll a 1, you lose all your current turn's accumulated score, \tand must pass the die.""") print("\tThe first to 100 wins. \nHave fun!\n") print("\t1.SinglePlayer") print("\t2.Multiplayer") print("\t3.Quit") def print_turn_menu(player_name, player_total_score, game_manager_current_score, player_times_rolled): """Prints Turn Menu""" print("") print(player_name, "\'s Turn") print("Total Score:", player_total_score) print("Score for the turn:", game_manager_current_score) print("Times Rolled:", player_times_rolled) print("1. Roll") print("2. Hold") print("") def print_player_selection(): """Prints Player Selection Menu""" print("How many players in total are there? (Including Yourself)") print("Maximum amount is 4 Players.") print("") def print_transition(dots, time_between): """Prints Transition Menu""" for _i in range(dots): print(".") time.sleep(time_between) def print_match_end_menu(): """Prints Match End Menu""" print("1. Main Menu.") print("2. Exit.")
# QUESTION """ Longest Word Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may also contain numbers, for example "Hello world123 567" Use the Parameter Testing feature in the box below to test your code with different arguments. """ # ANSWER import re pattern = re.compile(r'\W+') def LongestWord(sen): x = pattern.split(sen) return max(x, key=len) print(LongestWord(input())) """ Purpose of Regular Expressions: -> Extracting the needed information from the dense data stack, -> Controlling the input entered by the user, -> Putting the data into a format suitable for its intended use. """ # Thanks to special characters, events such as 'search' or 'replacement' occur quickly and effectively.
import copy import random import numpy as np array = np.zeros((10,2)) def add(value, index): low = 0 high = index mid = int((low + high) >> 1) while (low - high) > 1: #print low, high if value > array[mid]: low = mid mid = int((low + high) >> 1) else: high = mid mid = int((low + high) >> 1) return mid def add_value(value, index): global array array[index][0] = value array[index][1] = index print value for i in range(index, -1, -1): for j in range(index, -1, -1): if array[j][0] < array[i][0]: temp = copy.copy(array[j]) array[j] = array[i] array[i] = temp for k in range(10): add_value(random.randint(0, 100), k) print array
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve from sklearn.model_selection import ShuffleSplit #---------------------------------------------------------------------- def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues plotted. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is not a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validators that can be used here. n_jobs : integer, optional Number of jobs to run in parallel (default 1). """ plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve(estimator, X, y, cv=cv, scoring='roc_auc', n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") return plt #---------------------------------------------------------------------- def plot_learning_curves2(estimator, X_train, y_train, X_val, y_val, suptitle='', title='', xlabel='', ylabel=''): """ Plots learning curves for a given estimator. Parameters ---------- estimator : sklearn estimator X_train : pd.DataFrame training set (features) y_train : pd.Series training set (response) X_val : pd.DataFrame validation set (features) y_val : pd.Series validation set (response) suptitle : str Chart suptitle title: str Chart title xlabel: str Label for the X axis ylabel: str Label for the y axis Returns ------- Plot of learning curves """ # create lists to store train and validation scores train_score = [] val_score = [] # create ten incremental training set sizes training_set_sizes = np.linspace(5, len(X_train), 10, dtype='int') # for each one of those training set sizes for i in training_set_sizes: # fit the model only using that many training examples estimator.fit(X_train.iloc[0:i, :], y_train.iloc[0:i]) # calculate the training accuracy only using those training examples train_accuracy = metrics.accuracy_score( y_train.iloc[0:i], estimator.predict(X_train.iloc[0:i, :]) ) # calculate the validation accuracy using the whole validation set val_accuracy = metrics.accuracy_score( y_val, estimator.predict(X_val) ) # store the scores in their respective lists train_score.append(train_accuracy) val_score.append(val_accuracy) # plot learning curves fig, ax = plt.subplots(figsize=(14, 9)) ax.plot(training_set_sizes, train_score, c='gold') ax.plot(training_set_sizes, val_score, c='steelblue') # format the chart to make it look nice fig.suptitle(suptitle, fontweight='bold', fontsize='20') ax.set_title(title, size=20) ax.set_xlabel(xlabel, size=16) ax.set_ylabel(ylabel, size=16) ax.legend(['training set', 'validation set'], fontsize=16) ax.tick_params(axis='both', labelsize=12) ax.set_ylim(0, 1) def percentages(x, pos): """The two args are the value and tick position""" if x < 1: return '{:1.0f}'.format(x*100) return '{:1.0f}%'.format(x*100) def numbers(x, pos): """The two args are the value and tick position""" if x >= 1000: return '{:1,.0f}'.format(x) return '{:1.0f}'.format(x) y_formatter = FuncFormatter(percentages) ax.yaxis.set_major_formatter(y_formatter) x_formatter = FuncFormatter(numbers) ax.xaxis.set_major_formatter(x_formatter)
import time from datetime import date import win32com.client as wc import os from colorama import init, Back, Fore, Style import calendar init() def ns(c): while c!=("s") and c!=("n"): print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ").lower() return(c) def OKI(n): try: n=int(n) except: n=OKI(input("Caracter no valido: ")) return n def pregunta(timer): #ESTA FUNCION PREGUNTA SI SE QUIERE INCLUIR AMBAS FECHAS EN EL COMPUTO (VALE PARA "A","B" Y "C"). AD=ns(input("¿Incluir ambos dias en el computo?(n/s): ").lower()) if AD==("s"): timer=timer+1 return(timer) def nums(a): while a<1 or a>9999: a=OKI(input("Año no valido: ")) return a def mes(m):#HAN DE SER ENTEROS while m>12 or m<1: m=OKI(input("Hay 12 meses,(introduce un valor entre 1 y 12 ambos incluidos): ")) return(m) def mess(a,m,d):#PARA APLICAR LA FUNCION ESTAS VARIABLES HAN DE SER ENTEROS!!! M1=date(a,m,1) if a<9999 or m<12: #PARA ESTABLECER EL ÚLTIMO DIA DEL MES EN CUESTIÓN if m==12: M2=date(a+1,1,1)#ESTO SOLO SI a<9999. else: M2=date(a,m+1,1)#ESTO PARA m<12. MD=abs(M1-M2) while d>MD.days or d<1: d=OKI(input("La cifra del día está fuera del rango para el mes escogido: ")) else: while d>31: d=OKI(input("La cifra del día está fuera del rango para el mes escogido: ")) return d def meses(Fm): A=("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre") n=0 for i in A: n+=1 if int(Fm[1])==n: return i break def semana(n): N=-1 for i in("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo"): N+=1 if N==n: return(i) break conti = "s" speak=wc.Dispatch("Sapi.SpVoice") while(conti == "s"): print(Back.BLUE+" __________________________________________ ") print(Back.BLUE+" /__ ____________________________________/ ") print(Back.BLUE+" / / __ _________ ______ ________ ") print(Back.BLUE+" / / | | | _ _ | | =====| | ----_/ ") print(Back.BLUE+" /__/ |__| |_| |_| |_| |______| |_| \_\ ") print(Back.BLUE+"*******************************************************************") print(Back.RESET+"") print(Fore.GREEN+"-------------------------ESCOJA UNA OPCIÓN-------------------------") print("A) Calcular número de días entre una fecha y la actual.") print("B) Calcular número de días entre dos fechas.") print("C) Conocer fecha a partir del número de días.") print("-------------------------------------------------------------------"+Fore.RESET) op=input("Introduzca aquí su opción: ").upper() while op!=("A") and op!=("B") and op!=("C"): op=input("Escriba solo \'A\',\'B\' o \'C\' segun su opción: ").upper() today=date.today() cal=ns(input("¿Desea ver calendarios?(n/s): ").lower()) if op==("A"): a=nums(OKI(input("\nAño del suceso: ")))#;a=nums(OKI(a)) m=mes(OKI(input("Mes del suceso: ")))#;m=mes(OKI(m)) d=OKI(input("Dia del suceso: "));#d=OKI(d) Di=mess(a,m,d) D1=date(a,m,Di) if D1==(today): print(Fore.YELLOW+"Hoy es",D1) timer=abs(D1-today).days timer=pregunta(timer) if D1>today: message = "Quedan {} dias para la fecha escogida.".format(timer) print(Fore.YELLOW+"\n"+message) else: message = "Han transcurrido {} dias desde la fecha escogida.".format(timer) print(Fore.YELLOW+"\n"+message) print("({} semanas y {} dias).".format(str(int(timer/7)),timer%7)) speak.Speak(message) if cal==("s"): print(Fore.GREEN+"") CAL=calendar.c.prmonth(a,m) if op==("B"): a=nums(OKI(input("\nAño del primer suceso: ")))#;a=nums(OKI(a)) m=mes(OKI(input("Mes del primer suceso: ")))#;m=mes(OKI(m)) d=OKI(input("Día del primer suceso: "))#;d=OKI(d) Di=mess(a,m,d) D1=date(a,m,Di) Dist1=abs(D1-today).days a2=nums(OKI(input("\nAño del segundo suceso: ")))#;a2=nums(OKI(a2)) m2=mes(OKI(input("Mes del segundo suceso: ")))#;m2=mes(OKI(m2)) d2=OKI(input("Día del segundo suceso: "))#;d2=OKI(d2) Dii=mess(a2,m2,d2) D2=date(a2,m2,Dii) Dist2=abs(D2-today).days if (D1<=today and D2<=today) or (D1>=today and D2>=today): timer=abs(Dist1-Dist2) timer=pregunta(timer) if D1<=today and D2<=today: #print("") message = "Transcurrieron {} dias entre las dos fechas indicadas.".format(timer) print(Fore.YELLOW+"\n"+message) else: message = "Transcurriran {} dias entre las dos fechas indicadas.".format(timer) print(Fore.YELLOW+"\n"+message) print("({} semanas y {} dias).\n".format(str(int(timer/7)),timer%7)) speak.Speak(message) else: timer=(Dist1+Dist2) timer=pregunta(timer) message = "Transcurrirán {} dias entre las dos fechas indicadas.".format(timer) print(Fore.YELLOW+"\n"+message) print("({} semanas y {} dias).\n".format(str(int(timer/7)),timer%7)) speak.Speak(message) if cal==("s"): print(Fore.GREEN+"") CAL=calendar.c.prmonth(a,m) print("") CAL2=calendar.c.prmonth(a2,m2) if op==("C"): num=OKI(input("\nEscriba el número de días: ")) pas_fut=input("¿Al pasado (\'p\') o al futuro (\'f\'): ").lower() while pas_fut!=("p") and pas_fut!=("f"): pas_fut=input("Esciba solo \'p\'o\'f\'según su opción: ").lower() Dia1=date(1,1,1);HOY=int((today-Dia1).days)+1#SE ESTABLECE EL ORDINAL DE LA FECHA ACTUAL Dia_ult=date(9999,12,31);fut_hoy=int((Dia_ult-today).days)#SE ESTABLECE LO QUE FALTA PARA EL ULTIMO DIA if pas_fut==("p"): while num>HOY: print(Fore.YELLOW+"La cantidad introducida es superior al numero de dias transcurridos, el máximo es de",HOY-1,"dias.") num=OKI(input("Prueba con otro número: ")) dist=HOY-num dateo=date.fromordinal(dist)#RESUMIR date_spl=str(dateo).split("-") mes_nom=meses(date_spl) week_day=(dateo).weekday() dia_semana=semana(week_day) print(Fore.YELLOW+"\nHace {} días era {} {} de {} de {}.".format(num,dia_semana,date_spl[2],mes_nom,date_spl[0])) if pas_fut==("f"): while num>fut_hoy: print(Fore.YELLOW+"La cantidad introducida es superior al numero de dias restantes, el máximo es de",fut_hoy,"dias") num=OKI(input("Prueba con otro número: ")) dist=HOY+num dateo=date.fromordinal(dist)#RESUMIR date_spl=str(dateo).split("-") mes_nom=meses(date_spl) week_day=(dateo).weekday() dia_semana=semana(week_day) print(Fore.YELLOW+"\nDentro de {} días será {} {} de {} de {}.".format(num,dia_semana,date_spl[2],mes_nom,date_spl[0])) if cal==("s"): print(Fore.GREEN+"") CAL=calendar.c.prmonth(int(date_spl[0]),int(date_spl[1])) print(Fore.RESET+"") conti=ns(input("\n¿Desea continuar?(n/s): ").lower()) if os.name == "posix": os.system("clear") elif os.name == "ce" or os.name == "nt" or os.name == "dos": os.system("cls")
import functools import sys def tokenize(s): lst = [] i = 0 while i < len(s): if s[i] == '(' or s[i] == ')': lst.append(s[i]) i += 1 elif s[i] == ';': j = i while j < len(s) and s[j] != '\n': j += 1 i = j elif s[i] == ' ' or s[i] == '\n': i += 1 else: temp = '' j = i while j < len(s) and s[j] != ' ' and s[j] != ')' and s[j] != '(' and s[j] != '\n': temp += s[j] j += 1 if temp != '': lst.append(temp) i = j return lst def is_int(s): try: int(s) return True except: return False def is_float(s): try: float(s) return True except: return False def parse_helper(lst, i = 0): if i == len(lst): return None, None if is_int(lst[i]): return int(lst[i]), i + 1 if is_float(lst[i]): return float(lst[i]), i + 1 if lst[i] != '(' and lst[i] != ')': return lst[i], i + 1 ret = [] if lst[i] == '(': next_idx = i + 1 while next_idx < len(lst) and lst[next_idx] != ')': ex, next_idx = parse_helper(lst, next_idx) ret.append(ex) if next_idx >= len(lst) or lst[next_idx] != ')': raise SyntaxError() return ret, next_idx + 1 raise SyntaxError() def parse(lst): ret, next_idx = parse_helper(lst) if len(lst) != next_idx: raise SyntaxError() return ret def all_equal(lst): first = lst[0] for i in lst: if i != first: return False return True def decreasing(lst): if (len(lst) <= 1): return True first = lst[0] for i in range(1, len(lst)): if lst[i] >= first: return False first = lst[i] return True def nonincreasing(lst): if (len(lst) <= 1): return True first = lst[0] for i in range(1, len(lst)): if lst[i] > first: return False first = lst[i] return True def increasing(lst): if (len(lst) <= 1): return True first = lst[0] for i in range(1, len(lst)): if lst[i] <= first: return False first = lst[i] return True def nondecreasing(lst): if (len(lst) <= 1): return True first = lst[0] for i in range(1, len(lst)): if lst[i] < first: return False first = lst[i] return True def not_func(lst): return not lst[0] def list_func(args): if len(args) == 0: return LinkedList(None) elts = [LinkedList(i) for i in args] for i, j in zip(elts[:-1], elts[1:]): i.set_next_elt(j) return elts[0] def empty_list_dec(func): def ret_func(arg): if arg.elt is None: raise EvaluationError() return func(arg) return ret_func def car_func(arg): if arg.elt is None: raise EvaluationError() return arg.elt def cdr_func(arg): if arg.elt is None: raise EvaluationError() return arg.next def length_func(arg): if arg.elt == None: return 0 count = 0 for i in arg.list_iter(): count+=1 return count def elt_at_index_func(arg, ind): if length_func(arg) <= ind: raise EvaluationError() count = 0 for i in arg.list_iter(): if count == ind: return i.elt count+=1 def concat_func(arg): cop = None if len(arg) == 0: return LinkedList(None) for i in reversed(arg): for j in range(length_func(i)-1, -1, -1): k = cop cop = LinkedList(elt_at_index_func(i, j)) cop.set_next_elt(k) return cop def map_func(func, lst): # if func not in carlae_builtins: # func = result_and_env(func, func.env)[0] first = LinkedList(func([lst.elt])) ex = first while lst.next != None: lst = lst.next ex.next = LinkedList(func([lst.elt])) ex = ex.next return first def filter_func(func, lst): if func([lst.elt]): first = LinkedList(lst.elt) else: first = None ex = first while lst.next != None: lst = lst.next if func([lst.elt]): ex.next = LinkedList(lst.elt) ex = ex.next return first def reduce_func(func, lst, val): first = func([val, lst.elt]) ex = func([val, lst.elt]) while lst.next != None: lst = lst.next ex = func([ex, lst.elt]) return ex def evaluate_file(arg, eval_env=None): in_file = open(arg).read() return result_and_env(parse(tokenize(in_file)), eval_env)[0] class EvaluationError(Exception): pass class Environment(object): def __init__(self, parent = None, init_dict = {}): self.env_dict = {} self.parent = parent for i in init_dict: self.env_dict[i] = init_dict[i] #self.env_dict = {i: init_dict[i] for i in init_dict} def set(self, var_name, val): self.env_dict[var_name] = val def set_bang(self, var_name, val): cur_env = self while cur_env is not None and var_name not in cur_env.env_dict: cur_env = cur_env.parent if cur_env is None: raise EvaluationError() cur_env.set(var_name, val) def get(self, var_name): if isinstance(var_name, list): return None if var_name in self.env_dict: return self.env_dict[var_name] return self.parent.get(var_name) if self.parent is not None else None def copy(self): new = Environment(self.parent) for i in self.env_dict: new.env_dict[i] = self.env_dict[i] return new def __repr__(self): ret = 'Environment(\n' for i in self.env_dict: ret += str(i) + ' = ' + str(self.env_dict[i]) + '\n' ret += '\n)' return ret class Function(object): def __init__(self, params, code, env): self.params = params self.code = code self.env = env for i in self.params: self.env.set(i, None) def set_values(self, args): if len(args) != len(self.params): raise EvaluationError() new_func = Function(self.params, self.code, self.env.copy()) for j, i in enumerate(self.params): new_func.env.set(i, args[j]) return new_func def __repr__(self): return 'function object' def __call__(self, args): new_func = self.set_values(args) return result_and_env(new_func.code, new_func.env)[0] class LinkedList(object): def __init__(self, elt=None): self.elt = elt self.next = None def set_next_elt(self, next_elt): self.next = next_elt def list_iter(self): i = self while i is not None: yield i i = i.next carlae_builtins = Environment(init_dict = { '+': sum, '-': lambda args: -args[0] if len(args) == 1 else args[0] - sum(args[1:]), '*': lambda args: functools.reduce(lambda x, y: x * y, args), '/': lambda args: args[0] / functools.reduce(lambda x, y: x * y, args[1:]), '=?': all_equal, '>': decreasing, '>=': nonincreasing, '<': increasing, '<=': nondecreasing, 'not': not_func, '#t': True, '#f': False, 'list': list_func, 'car': lambda arg: car_func(arg[0]), #empty_list_dec(lambda arg: arg.elt), 'cdr': lambda arg: cdr_func(arg[0]), #empty_list_dec(lambda arg: arg.next), 'length': lambda arg: length_func(arg[0]), 'elt-at-index': lambda arg: elt_at_index_func(arg[0], arg[1]), 'concat': concat_func, 'map': lambda arg: map_func(arg[0], arg[1]), 'filter': lambda arg: filter_func(arg[0], arg[1]), 'reduce': lambda arg: reduce_func(arg[0], arg[1], arg[2]), 'begin': lambda arg: arg[-1] }) def result_and_env(inp, env = None): if env is None: env = Environment(carlae_builtins) if isinstance(inp, list) and len(inp) == 0: raise EvaluationError() if is_int(inp) or is_float(inp): return inp, env if isinstance(inp, str): sym = env.get(inp) if sym is not None: return sym, env raise EvaluationError() # if isinstance(inp, list): # if len(inp) == 0: # raise EvaluationError() # what if it is define if inp[0] == 'define': # if (len(inp) != 3): # raise EvaluationError() if ((not isinstance(inp[1], str)) and (not isinstance(inp[1], list))): raise EvaluationError() new_env = Environment(env) if isinstance(inp[1], list): env.set(inp[1][0], Function(inp[1][1:], inp[2], new_env)) return env.get(inp[1][0]), env else: env.set(inp[1], result_and_env(inp[2], env)[0]) return env.get(inp[1]), env if inp[0] == 'lambda': if len(inp) != 3: raise EvaluationError() new_env = Environment(env) func = Function(inp[1], inp[2], new_env) return func, env if inp[0] == 'if': new_env = Environment(env) if result_and_env(inp[1], env)[0] is True or result_and_env(inp[1], env)[0] == '#t': return result_and_env(inp[2], env) else: return result_and_env(inp[3], env) if inp[0] == 'and': new_env = Environment(env) for i in inp[1:]: if result_and_env(i, env)[0] is False: return False, env return True, env if inp[0] == 'or': new_env = Environment(env) for i in inp[1:]: if result_and_env(i, env)[0] is True: return True, env return False, env if inp[0] == 'let': inp_vars = inp[1] new_env = Environment(env) for i in inp_vars: new_env.set(i[0], result_and_env(i[1], env)[0]) return result_and_env(inp[2], new_env)[0], env if inp[0] == 'set!': #new_env = env.get(inp[1]) # if not env[inp[1]]: # raise EvaluationError() val = result_and_env(inp[2], env)[0] env.set_bang(inp[1], val) return val, env # what if it isn't define if (not isinstance(inp[0], list)) and (not isinstance(inp[0], str)): raise EvaluationError() ex = [] for i in inp[1:]: new_env = Environment(env) ex.append(result_and_env(i, env)[0]) new_env = Environment(env) func = result_and_env(inp[0], env)[0] return func(ex), env def evaluate(inp, env = None): return result_and_env(inp, env)[0] def repl(): inp = None env = Environment(carlae_builtins) if len(sys.argv[1:]) > 0: for i in sys.argv[1:]: evaluate_file(i, env) while inp != 'QUIT': inp = input('in> ') if inp == 'QUIT': break try: ret, new_env = result_and_env(parse(tokenize(inp)), env) env = new_env print('out>', ret) except Exception as e: print('out>', str(e)) if __name__ == '__main__': repl()
# # Σχ. Έτος 2020-21 # Θεόδωρος Ελευθέριος Βασιλικός # Νίκος Καλλίτσης # Παιχνίδι γνώσεων για απόφοιτους του Γυμνασίου © # #Variable για τις λάθος απαντήσεις: pl = 0 # όλα τα functions για τις ερωτήσεις: def Πληροφορική_προσπάθειες(): category1 = input('Πληροφορική ') if category1 == "Ναι" or category1 == "ναι" or category1 == 'ΝΑΙ': print('\n') print("Ερώτηση 1:") print('-'*10) πληρ1προ = 2 while πληρ1προ > 0: print("CPU, GPU, SSD, HDD ή USB;") qu1 = input("Πως λέγεται σε συντομογραφία η κάρτα γραφικών;") if qu1 == 'GPU'or qu1 == 'gpu'or qu1 == 'G.P.U.' or qu1 == 'Gpu': print('Μπράβο το G.P.U. είναι το Graphics processing unit, δηλαδή εκεί που επεξεργάζονται τα γραφικά, αυτό που βλέπεις στην οθόνη!') πληρ1προ -= 5 else: print('Μια μικρή βοήθεια: όπου βλέπεις D στο τέλος μιας λέξης από τις παραπάνω είναι Disk (δίσκος)...') πληρ1προ -= 1 print(f'Σου απομένουν {πληρ1προ} προσπάθειες') if πληρ1προ <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 2:") print('-'*10) πληρ2προ = 2 while πληρ2προ > 0: print("Word, Notepad, Pages, OpenOffice, Libre Writer") qu2 = input("Ποιά από τις παραπάνω είναι εφαρμογή της Microsoft;") if qu2 == 'Word' or qu2 == 'word'or qu2 == 'WORD': print('Καλός καλός! Έτσι πληροφοριακά όλα τα παραπάνω προγράμματα είναι για επεξεργασία κειμένου, αλλά μόνο το Word είναι της Microsoft.') πληρ2προ -= 5 else: print('Δε νομίζω πως είναι δύσκολο... μια μικρή βοήθεια το Pages δεν είναι πρόγραμμα των windows, είναι εφαρμογή της Apple.') πληρ2προ -= 1 print(f'Σου απομένουν {πληρ2προ} προσπάθειες') if πληρ2προ <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-'*5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 3:") print('-'*10) πληρ3προ = 3 while πληρ3προ > 0: print("Intel, AMD, Apple, NVidia") qu3 = input("Ποιά από τις παραπάνω ΔΕΝ είναι μάρκα επεξεργαστών;") if qu3 == "NVidia" or qu3 == "nvidia" or qu3 == "NVIDIA": print("Πολύ σωστά, η NVidia είναι η πιο γνωστή εταιρεία που παράγει κάρτες γραφικών(GPU).") πληρ3προ -= 5 else: print('Λίγο ανεβάσαμε τον πήχη; Δεν μιλάω συγκεκριμένα για επεξεργαστές υπολογιστών... και τα κινητά τηλέφωνα (π.χ.) έχουν επεξεργαστή!') πληρ3προ -= 1 print(f'Σου απομένουν {πληρ3προ} προσπάθειες') if πληρ3προ <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def Γλώσσα_Λογοτεχνία_προσπάθειες(): category2 = input('Γλώσσα - Λογοτεχνία ') if category2 == "Ναι"or category2 == "ναι" or category2 == "ΝΑΙ": print('\n') print("Ερώτηση 1:") print('-'*10) λογ1 = 2 while λογ1 > 0: print("Φεραίος, Κορνάρος, Ελύτης") que1 = input("Ποιός έγραψε τον Θούριο;") if que1 == "Φεραίος" or que1 == "Φερέος" or que1 == "φεραίος" or que1 == "ΦΕΡΑΙΟΣ": print("Δεν έχω λόγια!!!") λογ1 -= 5 else: print('Προσπάθησε ξανά... απλά να ξέρεις ο Οδ. Ελύτης ήταν ένας από τους πιο σπουδαίους ποιητές της Ελλάδας!') λογ1 -= 1 print(f'Σου απομένουν {λογ1} προσπάθειες') if λογ1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 2") print('-'*10) λογ2 = 2 while λογ2 > 0: print("Αντίθεση, Eιρωνεία, Έλλειψη") que2 = input("Ποιό σχήμα λόγου παρατηρείτε στο παράδειγμα: Ωραία τα κατάφερες!") if que2 == 'Ειρωνεία' or que2 == 'ειρωνεία' or que2 == 'ΕΙΡΩΝΕΙΑ' or que2 == 'Ειρονεία': print('Πολύ καλός παίχτης! Αν το βρήκες με τη πρώτη Μπράβο, αλλιώς δε πειράζει έμαθες...') λογ2 -= 5 else: print('Μήπως εσύ έχεις έλλειψη; Για δες ξανά φίλε μου! (ΑΝΤΙΘΕΣΗ)') λογ2 -= 1 print(f'Σου απομένουν {λογ2} προσπάθειες') if λογ2 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 3") print('-'*10) λογ3 = 2 while λογ3 > 0: print("Παραγράφους, Ομοιοκαταληξίες ή Στροφές") ques1 = input("Το ποίημα έχει πάντα...") if ques1 == 'Στροφές'or ques1 == 'στροφές' or ques1 == 'Στροφες': print('Το βρήκες! Ομοιοκαταληξίες δεν έχουν όλα τα ποιήματα, ειδικότερα αν ανήκουν στη μοντέρνα ποίηση! Στροφές όμως έχουν όλα!') λογ3 -= 5 else: print('Σε ρώτησα συγκεκριμένα τι έχει ένα ποίημα ΠΑΝΤΑ... εκ φύσεως πώς το λένε; Ξανά!') λογ3 -= 1 print(f'Σου απομένουν {λογ3} προσπάθειες') if λογ3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def English_προσπάθειες(): category3 = input('Αγγλικά ') if category3 == "Ναι" or category3 == "ναι" or category3 == "Yes" or category3 == "Nai" or category3 == "ΝΑΙ": print('\n') print("Για να σε δούμε...") print("Ερώτηση 1:") print('-'*10) engl1 = 2 while engl1 > 0: print("Συμβιβάζομαι, Ανέχομαι, Φοράω κάτι") q1 = input("Τι σημαίνει η φράση put up with;") if q1 == 'Ανέχομαι' or q1 == 'ανέχομαι' or q1 == 'ΑΝΕΧΟΜΑΙ': print('Καλός και στα Αγγλικά!') engl1 -= 5 else: print('Πάμε πάλι...') engl1 -= 1 print(f'Σου απομένουν {engl1} προσπάθειες') if engl1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 2:") print('-'*10) engl2 = 2 while engl2 > 0: print("Come, Comed, Commes") q2 = input("Ποιό από τα παραπάνω είναι past participle του ρήματος come;") if q2 == "Come" or q2 == "come" or q2 == "COME" or q2 == "Ψομε": print("Μπράβοοο!") engl2 -= 5 else: print('Κάποιος δεν ξέρει να ανώματα ρήματα στα αγγλικά... Πάμε πάλι') engl2 -= 1 print(f'Σου απομένουν {engl2} προσπάθειες') if engl2 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 3:") print('-'*10) engl3 = 2 while engl3 > 0: print("Homemade, Handmade, Inmade") q3 = input("Ποιό από τα παραπάνω σημαίνει σπιτικός;") if q3 == "Homemade" or q3 == "homemade" or q3 == "HOMEMADE" or q3 == "Ηομεμαδε": print("Amazing!") engl3 -= 5 else: print('No of course not! Try again please!') engl3 -= 1 print(f'Σου απομένουν {engl3} προσπάθειες') if engl3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def Μαθηματικά_προσπάθειες(): category4 = input('Μαθηματικά ') if category4 == "Ναι" or category4 == "ναι" or category4 == 'ΝΑΙ': print('\n') print("Στις ερωτήσεις να απαντάς με 1, 2 και 3 αντίστοιχα.") print("Ερώτηση 1:") print('-'*10) math1 = 2 while math1 > 0: print("α^2-2αβ-β^2, β^2-2αβ+α^2, α-2αβ^2+β^2") e = input("Ποιό είναι το ανάπτυγμα της ταυτότητας (α-β)^2 ") if e == "2" or e == "δύο": print("Πολύ σωστά!") math1 -= 5 else: print('Μην σε μπερδεύει η λέξη ανάπτυγμα... απλά κάνε τη ταυτότητα όπως την ξέρεις!') math1 -= 1 print(f'Σου απομένουν {math1} προσπάθειες') if math1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 2:") print('-'*10) math2 = 2 while math2 > 0: print("α^2+β^3+γ^3+2αβγ, α^2+β^2+γ^2+2αβ+2αγ+2βγ, α^3+2αγ+γ^3+β^2") e1 = input("Ποιό είναι το ανάπτυγμα της ταυτότητας (α+β+γ)^2 ") if e1 == "2" or e1 == "δύο": print("Πολύ σωστά!") math2 -= 5 else: print('Αν δε θυμάσαι πώς αναλύουμε τη ταυτότητα, κάνε πολλαπλασιασμό: (α+β+γ)*(α+β+γ)') math2 -= 1 print(f'Σου απομένουν {math2} προσπάθειες') if math1 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print("Ερώτηση 3:") print('-'*10) math3 = 2 while math3 > 0: print("α^2, β^2+2αβ, 2αβ") e2 = input("Ποιό είναι το αποτέλεσμα: (α+β)^2-(α^2+β^2) ") if e2 == "3" or e2 == "τρία": print("Πολύ σωστά!") math3 -= 5 else: print('Δε πειράζει πάμε ξανά!') math3 -= 1 print(f'Σου απομένουν {math3} προσπάθειες') if math3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def Φυσική_προσπάθειες(): category5 = input('Φυσική ') if category5 == "Ναι" or category5 == "ναι" or category5 == 'ΝΑΙ': print('\n') print('Ερώτηση 1:') print('-'*10) phy1 = 2 while phy1 > 0: print('1A, 1V, 1Ω, 1J, 1W') ph1 = input('Ποια μονάδα από τις παραπάνω θα χρησιμοποιούσες για να μετρήσεις την ισχύ ενός διπόλου;') if ph1 == '1W' or ph1 == '1w' or ph1 == 'W' or ph1 == '1w' or ph1 == '1Βατ': print('Μπράβο! Το 1W (ή ένα Βατ) είναι η μονάδα μέτρησης της Ισχύος στο Διεθνές Σύστημα Μονάδων (S.I.) και 1W = 1A * 1V') phy1 -= 5 else: print('Για προσπάθησε άλλη μία φορά... μην σε μπερδέυει το ότι έχω βάλει πολλές μονάδες! Το 1J είναι ενέργεια!') phy1 -= 1 print(f'Σου απομένουν {phy1} προσπάθειες') if ph1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 2:') print('-'*10) phy2 = 2 while phy2 > 0: print('Αμπερόμετρο, Βολτόμετρο, Ωμόμετρο, Πολύμετρο, Παλμογράφος') ph2 = input('Τα παραπάνω είναι όργανα μέτρησης. Ποιο από τα παραπάνω όργανα θα χρησιμοποιούσες για να μετρήσεις την Ισχύ ενός διπόλου;') if ph2 == 'Πολύμετρο' or ph2 == 'πολύμετρο' or ph2 == 'ΠΟΛΥΜΕΤΡΟ': print('Εύγε! Θα χρησμοποιούσες το πολύμετρο, το οποίο παρόλο που δε μετράει την ισχύ, αυτή καθ αυτή, μετράει και την ένταση του ηλ. ρεύματος και την τάση στα άκρα της συσκευής σου! Έτσι με τον παραπάνω τύπο (1W = 1A * 1V) Θα μπορέσεις να βρεις την ισχύ του διπόλου!') phy2 -= 5 else: print('Σου φάνησε δύσκολη η ερώτηση(;) ... σε ρώτησα την ΙΣΧΥ!') phy2 -= 1 print(f'Σου απομένουν {phy2} προσπάθειες') if ph2 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 3:') print('-'*10) phy3 = 2 while phy3 > 0: print('αντίστροφα, σε σειρά, παράλληλα, ανάστροφα') ph3 = input('Στο σπίτι σου έχεις λάμπες· σωστά; Ε λοιπόν, πώς πρέπει να συνδέσουμε τις λάμπες έτσι ώστε: όχι μόνο όταν καεί η μία να συνεχίσζουν να δουλεύουν οι υπόλοιπες, αλλά και να μην επηρεαστεί καθόλου το πόσο έντονα θα φωτοβολούν οι λάμπες στη περίπτωση που καεί η μία;') if ph3 == 'παράλληλα' or ph3 == 'Παράλληλα' or ph3 == 'ΠΑΡΑΛΛΗΛΑ': print('Μπράβοο! Εμείς ξέρουμε ότι όταν συνδέεις αντιστάτες παράλληλα, έχουν την ίδια τάση και όταν κλείσουμε έναν αντιστάτη οι υπόλοιποι που είναι συνδεδεμένοι παράλληλα θα έχουν ακριβώς την ίδια ένταση με προηγουμένως! Άρα, οι λάμπες θα φωτοβολούν το ίδιο.') phy3 -= 5 else: print('Για προσπάθησε ξανά! Μην σε μπερδεύουν οι λάμπες, σκέψου τα Χριστουγεννιάτικα λαμπάκια που βάζουμε στο δέντρο!') phy3 -= 1 print(f'Σου απομένουν {phy3} προσπάθειες') if ph3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def Χημεία_προσπάθειες(): category6 = input('Χημεία ') if category6 == "Ναι" or category6 == "ναι" or category6 == 'ΝΑΙ': print('\n') print('Ερώτηση 1:') print('-'*10) chem1 = 2 while chem1 > 0: print('Νερό, Αλάτι, Διοξείδιο του άνθρακα, Τίποτα') che1 = input('Τι θα σχηματιστεί αν ανακατέψουμε σόδα με ξίδι;') if che1 == 'Αλάτι' or che1 == 'αλάτι' or che1 == 'ΑΛΑΤΙ': print('Εύγε! Θα σχηματιστούν κρύσταλοι άλατος!') chem1 -= 5 else: print('Πολύ απλή ερώτηση νομίζω! Το Τίποτα το αποκλύουμε γιατί και τα δύο είναι χημικά συστατικά... θα σχηματιστεί προφανώς μια χημική ένωση! Πάμε πάλι!') chem1 -= 1 print(f'Σου απομένουν {chem1} προσπάθειες') if chem1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 2:') print('-'*10) chem2 = 2 while chem2 > 0: print('2, 8, 4, 6, 16') che2 = input('Ο ατομικός αριθμός του οξυγόνου είναι 8, πόσα ηλεκτρόνια έχει ένα μόριο οξυγόνου;') if che2 == '8': print('Πολύ σωστά! Έχει 8 ηλεκτρόνια και 8 πρωτόνια!') chem2 -= 5 else: print('Για προσπάθησε ξανά... ο ατομικός αριθμός είναι Z και ο αριθμός των νετρονίων είναι Ν... για θυμίσου!') chem2 -= 1 print(f'Σου απομένουν {chem2} προσπάθειες') if chem2 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 3:') print('-'*10) chem3 = 2 while chem3 > 0: print('ανιόν υδρογόνου, κατιόν υδρογόνου, πανιόν υδρογόνου') che3 = input('Ένα ιόν υδρογόνου έχει -3 ηλεκτόνια. Πώς ονομάζεται;') if che3 == "κατιόν υδρογόνου" or che3 == "Κατιόν Υδρογόνου" or che3 == "ΚΑΤΙΟΝ ΥΔΡΟΓΟΝΟΥ": print('Μπραβίσιμο!') chem3 -= 5 else: print('Δεν υπάρχει το πανιόν... για ξαναδες το τώρα') chem3 -= 1 print(f'Σου απομένουν {chem3} προσπάθειες') if chem3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) def Ιστορία_προσπάθειες(): category7 = input('Ιστορία ') if category7 == "Ναι" or category7 == "ναι" or category7 == 'ΝΑΙ': print('\n') print('Ερώτηση 1:') print('-'*10) hist1 = 3 while hist1 > 0: print('1435, 1453, 1776, 1467, 1978, 1987') his1 = input('Η πρώτη άλωση της Κωνσταντινούπολης έγινε το... ') if his1 == '1453' or his1 == 'το 1453': print('Εύγε! Το 1453 έγινε!') hist1 -= 5 else: print('Να θυμάσαι ότι έγινε τον 15ο αιώνα μ.Χ. Προσπάθησε πάλι!') hist1 -= 1 print(f'Σου απομένουν {hist1} προσπάθειες') if hist1 <= 0: print('Χάσατε... προσπαθήστε ξανά') global pl pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 2:') print('-'*10) hist2 = 2 while hist2 > 0: print('Ναι, Όχι, Ονομάζεται αλλιώς') his2 = input('Ο 1ος Παγκόσμιος Πόλεμος ονομάζεται και πόλεμος των Χαρακωμάτων;') if his2 == 'Ναι'or his2 == 'ναι' or his2 == 'ΝΑΙ': print('Μπράβο διαβασμένος σε βλέπω!') hist2 -= 5 else: print('Κάποιος είναι λίγο αδιάβαστος βλέπω... Προσπάθησε ξανά!') hist2 -= 1 print(f'Σου απομένουν {hist2} προσπάθειες') if hist2 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) print('\n') print('Ερώτηση 3:') print('-'*10) hist3 = 2 while hist3 > 0: print('με την εισοβολή του Μουσολίνι στην Αθήνα, με την εισοβολή του Χίτρελ στη Ρωσία, με την εισβολή του Μουσολίνι στα Ιεροσόλυμα, με την εισβολή του Χίτρελ στη Πολωνία') his3 = input('Ο 2ος παγκόσμιος πόλεμος άρχισε με... (απάντα με 1 ή 2 ή 3 ή 4)') if his3 == '4': print('Ωραίος ο νέος!') hist3 -= 5 else: print('Πληροφοριακά άρχισε στην Ευρώπη και εξαπλώθηκε σε όλη την οικουμένη αργότερα! Προσπάθησε άλλη μία φορά!') hist3 -= 1 print(f'Σου απομένουν {hist3} προσπάθειες') if hist3 <= 0: print('Χάσατε... προσπαθήστε ξανά') pl += 1 break print('-' * 5) print(f'Έχεις {pl} λάθος απαντήσεις') print('-' * 5) else: print('Πάμε παρακάτω...') def Ολα_χωρίς_προσπάθειες(): ξανά = input('Θέλεις να ξανακάνεις κάποια ερωτηση; (Ναι ή Όχι)') if ξανά == 'Ναι' or ξανά == 'ναι' or ξανά == 'NAI'or ξανά == 'ΝΑι': print('ok...') category = input("Διάλεξε μια κατηγορία στην οποία θες να τεστάρεις τις γνώσεις σου: (Πληροφορική, Αγγλικά,Γλώσσα - Λογοτεχνία, Ιστορία, Μαθηματικά, Φυσική ή Χημέια: ") if category == "Πληροφορική" or category == "πληροφορική" or category == "ΠΛΗΡΟΦΟΡΙΚΗ": print('\n') print("Ερώτηση 1:") print('-'*10) πληρ1 = True while πληρ1: print("CPU, GPU, SSD, HDD ή USB;") qu1 = input("Πως λέγεται σε συντομογραφία η κάρτα γραφικών; ") if qu1 == 'GPU'or qu1 == 'gpu'or qu1 == 'G.P.U.': print('Μπράβο το G.P.U. είναι το Graphics processing unit, δηλαδή εκεί που επεξεργάζονται τα γραφικά, αυτό που βλέπεις στην οθόνη!') πληρ1 = False else: print('Μια μικρή βοήθεια: όπου βλέπεις D στο τέλος μιας λέξης από τις παραπάνω είναι Disk (δίσκος)...') print("Ερώτηση 2:") print('-'*10) πληρ2 = True while πληρ2: print("Word, Notepad, Pages, OpenOffice, Libre Writer") qu2 = input("Ποιά από τις παραπάνω είναι εφαρμογή της Microsoft; ") if qu2 == 'Word' or qu2 == 'word'or qu2 == 'WORD': print('Καλός καλός! Έτσι πληροφοριακά όλα τα παραπάνω προγράμματα είναι για επεξεργασία κειμένου, αλλά μόνο το Word είναι της Microsoft.') πληρ2 = False else: print('Δε νομίζω πως είναι δύσκολο... μια μικρή βοήθεια το Pages δεν είναι πρόγραμμα των windows, είναι εφαρμογή της Apple.') print("Ερώτηση 3:") print('-'*10) πληρ3 = True while πληρ3: print("Intel, AMD, Apple, NVidia") qu3 = input("Ποιά από τις παραπάνω ΔΕΝ είναι μάρκα επεξεργαστών;") if qu3 == "NVidia" or qu3 == "nvidia" or qu3 == "NVIDIA": print("Πολύ σωστά, η NVidia είναι η πιο γνωστή εταιρεία που παράγει κάρτες γραφικών(GPU).") πληρ3 = False else: print('Λίγο ανεβάσαμε τον πήχη; Δεν μιλάω συγκεκριμένα για επεξεργαστές υπολογιστών... και τα κινητά τηλέφωνα (π.χ.) έχουν επεξεργαστή!') elif category == "Γλώσσα - Λογοτεχνία" or category == "Γλώσσα-Λογοτεχνία" or category == "γλώσσα - λογοτεχνία" or category == "γλώσσα-λογοτεχνία" or category == "Γλώσσα Λογοτεχνία" or category == "γλώσσα λογοτεχνία": print("Ερώτηση 1:") print('-'*10) λογ1 = True while λογ1: print("Φεραίος, Κορνάρος, Ελύτης") que1 = input("Ποιός έγραψε τον Θούριο;") if que1 == "Φεραίος" or que1 == "Φερέος" or que1 == "φεραίος" or que1 == "ΦΕΡΑΙΟΣ": print("Δεν έχω λόγια!!!") λογ1 = False else: print('Προσπάθησε ξανά... απλά να ξέρεις ο Οδ. Ελύτης ήταν ένας από τους πιο σπουδαίους ποιητές της Ελλάδας!') print("Ερώτηση 2") print('-'*10) λογ2 = True while λογ2: print("Αντίθεση, Eιρωνεία, Έλλειψη") que2 = input("Ποιό σχήμα λόγου παρατηρείτε στο παράδειγμα: Ωραία τα κατάφερες!") if que2 == 'Ειρωνεία' or que2 == 'ειρωνεία' or que2 == 'ΕΙΡΩΝΕΙΑ' or que2 == 'Ειρονεία': print('Πολύ καλός παίχτης! Αν το βρήκες με τη πρώτη Μπράβο, αλλιώς δε πειράζει έμαθες...') λογ2 = False else: print('Μήπως εσύ έχεις έλλειψη; Για δες ξανά φίλε μου! (ΑΝΤΙΘΕΣΗ)') print("Ερώτηση 3") print('-'*10) λογ3 = True while λογ3: print("Παραγράφους, Ομοιοκαταληξίες ή Στροφές") ques1 = input("Το ποίημα έχει πάντα...") if ques1 == 'Στροφές'or ques1 == 'στροφές' or ques1 == 'Στροφες': print('Το βρήκες! Ομοιοκαταληξίες δεν έχουν όλα τα ποιήματα, ειδικότερα αν ανήκουν στη μοντέρνα ποίηση!') λογ3 = False else: print('Σε ρώτησα συγκεκριμένα τι έχει ένα ποίημα ΠΑΝΤΑ... εκ φύσεως πώς το λένε; Ξανά!') elif category == "Αγγλικά" or category == "αγγλικά" or category == "ΑΓΓΛΙΚΑ" or category == "English": print("Για να σε δούμε...") print("Ερώτηση 1:") print('-'*10) engl1 = True while engl1: print("Συμβιβάζομαι, Ανέχομαι, Φοράω κάτι") q1 = input("Τι σημαίνει η φράση put up with;") if q1 == 'Ανέχομαι' or q1 == 'ανέχομαι' or q1 == 'ΑΝΕΧΟΜΑΙ': print('Καλός και στα Αγγλικά!') engl1 = False else: print('Πάμε πάλι...') print("Ερώτηση 2:") print('-'*10) engl2 = True while engl2: print("Come, Comed, Commes") q2 = input("Ποιό από τα παραπάνω είναι past participle του ρήματος come;") if q2 == "Come" or q2 == "come" or q2 == "COME" or q2 == "Ψομε": print("Μπράβοοο!") engl2 = False else: print('Κάποιος δεν ξέρει να ανώματα ρήματα στα αγγλικά... Πάμε πάλι') print("Ερώτηση 3:") print('-'*10) engl3 = True while engl3: print("Homemade, Handmade, Inmade") q3 = input("Ποιό από τα παραπάνω σημαίνει σπιτικός;") if q3 == "Homemade" or q3 == "homemade" or q3 == "HOMEMADE" or q3 == "Ηομεμαδε": print("Amazing!") engl3 = False else: print('No of course not! Try again please!') elif category == "Μαθηματικά" or category == "μαθηματικά" or category == "ΜΑΘΗΜΑΤΙΚΑ": print("Στις ερωτήσεις να απαντάς με 1, 2 και 3 αντίστοιχα.") print("Ερώτηση 1:") print('-'*10) math1 = True while math1: print("α^2-2αβ-β^2, β^2-2αβ+α^2, α-2αβ^2+β^2") e = input("Ποιό είναι το ανάπτυγμα της ταυτότητας (α-β)^2") if e == "2" or e == "δύο": print("Πολύ σωστά!") math1 = False else: print('Μην σε μπερδεύει η λέξη ανάπτυγμα... απλά κάνε τη ταυτότητα όπως την ξέρεις!') print("Ερώτηση 2:") print('-'*10) math2 = True while math2: print("α^2+β^3+γ^3+2αβγ, α^2+β^2+γ^2+2αβ+2αγ+2βγ, α^3+2αγ+γ^3+β^2") e1 = input("Ποιό είναι το ανάπτυγμα της ταυτότητας (α+β+γ)^2") if e1 == "2" or e1 == "δύο": print("Πολύ σωστά!") math2 = False else: print('Αν δε θυμάσαι πώς αναλύουμε τη ταυτότητα, κάνε πολλαπλασιασμό: (α+β+γ)*(α+β+γ)') print("Ερώτηση 3:") print('-'*10) math3 = True while math3: print("α^2, β^2+2αβ, 2αβ") e2 = input("Ποιό είναι το αποτέλεσμα: (α+β)^2-(α^2+β^2)") if e2 == "3" or e2 == "τρία": print("Πολύ σωστά!") math3 = False else: print('Δε πειράζει πάμε ξανά!') elif category == 'Φυσική' or category == 'φυσική' or category == 'ΦΥΣΙΚΗ': print('Ερώτηση 1:') print('-'*10) phy1 = True while phy1: print('1A, 1V, 1Ω, 1J, 1W') ph1 = input('Ποια μονάδα από τις παραπάνω θα χρησιμοποιούσες για να μετρήσεις την ισχύ ενός διπόλου;') if ph1 == '1W' or ph1 == '1w' or ph1 == 'W' or ph1 == '1w' or ph1 == '1Βατ': print('Μπράβο! Το 1W (ή ένα Βατ) είναι η μονάδα μέτρησης της Ισχύος στο Διεθνές Σύστημα Μονάδων (S.I.) και 1W = 1A * 1V') phy1 = False else: print('Για προσπάθησε άλλη μία φορά... μην σε μπερδέυει το ότι έχω βάλει πολλές μονάδες! Το 1J είναι ενέργεια!') print('Ερώτηση 2:') print('-'*10) phy2 = True while phy2: print('Αμπερόμετρο, Βολτόμετρο, Ωμόμετρο, Πολύμετρο, Παλμογράφος') ph2 = input('Τα παραπάνω είναι όργανα μέτρησης. Ποιο από τα παραπάνω όργανα θα χρησιμοποιούσες για να μετρήσεις την Ισχύ ενός διπόλου;') if ph2 == 'Πολύμετρο' or ph2 == 'πολύμετρο' or ph2 == 'ΠΟΛΥΜΕΤΡΟ': print('Εύγε! Θα χρησμοποιούσες το πολύμετρο, το οποίο παρόλο που δε μετράει την ισχύ, αυτή καθ αυτή, μετράει και την ένταση του ηλ. ρεύματος και την τάση στα άκρα της συσκευής σου! Έτσι με τον παραπάνω τύπο (1W = 1A * 1V) Θα μπορέσεις να βρεις την ισχύ του διπόλου!') phy2 = False else: print('Σου φάνησε δύσκολη η ερώτηση(;) ... σε ρώτησα την ΙΣΧΥ!') print('Ερώτηση 3:') print('-'*10) phy3 = True while phy3: print('αντίστροφα, σε σειρά, παράλληλα, ανάστροφα') ph3 = input('Στο σπίτι σου έχεις λάμπες· σωστά; Ε λοιπόν, πώς πρέπει να συνδέσουμε τις λάμπες έτσι ώστε: όχι μόνο όταν καεί η μία να συνεχίσζουν να δουλεύουν οι υπόλοιπες, αλλά και να μην επηρεαστεί καθόλου το πόσο έντονα θα φωτοβολούν οι λάμπες στη περίπτωση που καεί η μία;') if ph3 == 'παράλληλα' or ph3 == 'Παράλληλα' or ph3 == 'ΠΑΡΑΛΛΗΛΑ': print('Μπράβοο! Εμείς ξέρουμε ότι όταν συνδέεις αντιστάτες παράλληλα, έχουν την ίδια τάση και όταν κλείσουμε έναν αντιστάτη οι υπόλοιποι που είναι συνδεδεμένοι παράλληλα θα έχουν ακριβώς την ίδια ένταση με προηγουμένως! Άρα, οι λάμπες θα φωτοβολούν το ίδιο.') phy3 = False else: print('Για προσπάθησε ξανά! Μην σε μπερδεύουν οι λάμπες, σκέψου τα Χριστουγεννιάτικα λαμπάκια που βάζουμε στο δέντρο!') elif category == 'Χημεία' or category == 'χημεία' or category == 'ΧΗΜΕΙΑ': print('Ερώτηση 1:') print('-'*10) chem1 = True while chem1: print('Νερό, Αλάτι, Διοξείδιο του άνθρακα, Τίποτα') che1 = input('Τι θα σχηματιστεί αν ανακατέψουμε σόδα με ξίδι;') if che1 == 'Αλάτι' or che1 == 'αλάτι' or che1 == 'ΑΛΑΤΙ': print('Εύγε! Θα σχηματιστούν κρύσταλοι άλατος!') chem1 = False else: print('Πολύ απλή ερώτηση νομίζω! Το Τίποτα το αποκλύουμε γιατί και τα δύο είναι χημικά συστατικά... θα σχηματιστεί προφανώς μια χημική ένωση! Πάμε πάλι!') print('Ερώτηση 2:') print('-'*10) chem2 = True while chem2: print('2, 8, 4, 6, 16') che2 = input('Ο ατομικός αριθμός του οξυγόνου είναι 8, πόσα ηλεκτρόνια έχει ένα μόριο οξυγόνου;') if che2 == '8': print('Πολύ σωστά! Έχει 8 ηλεκτρόνια και 8 πρωτόνια!') chem2 = False else: print('Για προσπάθησε ξανά... ο ατομικός αριθμός είναι Z και ο αριθμός των νετρονίων είναι Ν... για θυμίσου!') print('Ερώτηση 3:') print('-'*10) chem3 = True while chem3: print('ανιόν υδρογόνου, κατιόν υδρογόνου, πανιόν υδρογόνου') che3 = input('Ένα ιόν υδρογόνου έχει -3 ηλεκτόνια. Πώς ονομάζεται;') if che3 == "κατιόν υδρογόνου" or che3 == "Κατιόν Υδρογόνου" or che3 == "ΚΑΤΙΟΝ ΥΔΡΟΓΟΝΟΥ": print('Μπραβίσιμο!') chem3 = False else: print('Δεν υπάρχει το πανιόν... για ξαναδες το τώρα') elif category == 'Ιστορία' or category == 'ιστορία' or category == 'ΙΣΤΟΡΙΑ': print('Ερώτηση 1:') print('-'*10) hist1 = True while hist1: print('1435, 1453, 1776, 1467, 1978, 1987') his1 = input('Η πρώτη άλωση της Κωνσταντινούπολης έγινε το... ') if his1 == '1453': print('Εύγε! Το 1453 έγινε!') else: print('Να θυμάσαι ότι έγινε τον 15ο αιώνα μ.Χ. Προσπάθησε πάλι!') hist1 = False print(f'Σου απομένουν {hist1} προσπάθειες') print('Ερώτηση 2:') print('-'*10) hist2 = True while hist2: print('Ναι, Όχι, Ονομάζεται αλλιώς') his2 = input('Ο 1ος Παγκόσμιος Πόλεμος ονομάζεται και πόλεμος των Χαρακωμάτων;') if his2 == 'Ναι'or his2 == 'ναι' or his2 == 'ΝΑΙ': print('Μπράβο διαβασμένος σε βλέπω!') else: print('Κάποιος είναι λίγο αδιάβαστος βλέπω... Προσπάθησε ξανά!') hist2 = False print(f'Σου απομένουν {hist2} προσπάθειες') print('Ερώτηση 3:') print('-'*10) hist3 = True while hist3: print('με την εισοβολή του Μουσολίνι στην Αθήνα, με την εισοβολή του Χίτρελ στη Ρωσία, με την εισβολή του Μουσολίνι στα Ιεροσόλυμα, με την εισβολή του Χίτρελ στη Πολωνία') his3 = input('Ο 2ος παγκόσμιος πόλεμος άρχισε με... (απάντα με 1 ή 2 ή 3 ή 4)') if his3 == '4': print('Ωραίος ο νέος!') hist3 = False else: print('Πληροφοριακά άρχισε στην Ευρώπη και εξαπλώθηκε σε όλη την οικουμένη αργότερα! Προσπάθησε άλλη μία φορά!') else: τέλος() def τέλος(): global pl if pl >= 9: print('=' * 12) print('Έχασες! Προσπάθησε ξανά!') print('\n') else: print('=' * 12) print('Νίκησες! Μπράβο!') print('\n') print("Ευχαριστώ πολύ που αφιέρωσες λίγο χρόνο στο προγραμματάκι μας Θοδωρής Βασιλικός και Νίκος Καλλίτσης") print("Καλή συνέχεια!") exit1 = input('Πατα οποιοδήποτε κουμπί για να κλείσεις το πρόγραμμα') if exit1 == 'όχι δε θέλω': print('Ε τότε κάτσε εδώ') for i in range(15): print('...') print('Τι ακόμα δεν έφυγες') else: exit() def τέλος_1(): print("Ευχαριστώ πολύ που αφιέρωσες λίγο χρόνο στο προγραμματάκι μας Θοδωρής Βασιλικός και Νίκος Καλλίτσης") print("Καλή συνέχεια!") exit2 = input('Πατα οποιοδήποτε κουμπί για να κλείσεις το πρόγραμμα') if exit2 == 'όχι δε θέλω': print('Ε τότε κάτσε εδώ') for i in range(15): print('...') print('Τι ακόμα δεν έφυγες') else: exit() # το κύριο πρόγραμμα: print( "Γεια σου, αυτό είναι ένα παιχνίδι για να τεστάρεις τις γνώσεις σου σε διάφορα πραγματα που είναι χρήσιμα για " "το μέλλον σου" ) question = input("Θα ήθελες να συνεχίσεις (Ναι ή Όχι) -> ") if question == "Ναι" or question == 'ναι' or question == 'ΝΑΙ': print("τέλεια!") print("Διαλέγεις τις παρακάτω κατηγορίες απαντώντας Ναι ή Όχι:") Πληροφορική_προσπάθειες() English_προσπάθειες() Γλώσσα_Λογοτεχνία_προσπάθειες() Ιστορία_προσπάθειες() Μαθηματικά_προσπάθειες() Φυσική_προσπάθειες() Χημεία_προσπάθειες() Ολα_χωρίς_προσπάθειες() else: τέλος_1()
# Read thru chapter 5, skipping the section on GASP. # http://openbookproject.net/thinkcs/python/english2e/ch05.html # Do chapter 5 exercises 1-8 in this file. # You'll need this... import math # Exercise 1 def compare(a, b): """ >>> compare(5, 4) 1 >>> compare(7, 7) 0 >>> compare(2, 3) -1 >>> compare(42, 1) 1 """ # Your function body should begin here. pass # Exercise 2-8 should go here. if __name__ == '__main__': import doctest doctest.testmod()
class Student: name="name" conf={'exam_max': 30 ,'lab_max':7,'lab_num':10, 'k':0.61} def __init__(self,name,conf): self.name=name self.conf=conf res=[0 for res in range(conf['lab_num'])] res_exam=0 def make_lab(self,m,n): if(m>self.conf['lab_max']): m=self.conf['lab_max'] if not n.exist(): for i in self.res: if(i==0): self.res=m break else: if(n<self.conf['lab_num']): self.res.insert(n,m) return self def make_exam(self,m): if(m>self.conf['exam_max']): m=self.conf['exam_max'] self.res_exam=m return self def if_certified(self): return (sum(self.res)+self.res_exam,(sum(self.res)+self.res_exam)>(self.k*(self.conf['exam_max']+self.conf['lab_max']+self.conf['lab_num']))) pass
def check_stack(list): temp = [] for i in list: if i == '(': temp.append(i) else: if temp: temp.pop() else: return 'NO' if temp: return 'NO' else: return 'YES' answer = [] for _ in range(int(input())): list2 = list(input()) answer.append(check_stack(list2)) print(*answer,sep='\n')
caseCount = int(input()) #입력받기 def zero_one_count(value): zero_count = [1,0] one_count = [0,1] if value == 0 : print("%d %d"%(zero_count[0],one_count[0])) elif value == 1: print("%d %d"%(zero_count[1],one_count[1])) else: for j in range(2,value+1): zero_count.append(zero_count[j-2]+zero_count[j-1]) one_count.append(one_count[j-2]+one_count[j-1]) print("%d %d" %(zero_count[value],one_count[value])) for i in range(0,caseCount): value = int(input()) #입력받기 zero_one_count(value)
# 2021 Copyright Dinu Ion-Irinel from docx import Document from docx.shared import Inches from docx.shared import RGBColor # initialize of the document document = Document() # intro informations name = input("Hello, what is your name? : ") phone_number = input("What's your phone_number: ") email = input("Enter your email: ") image_tag = input("Enter the name of image: ") document.add_picture('./' + image_tag, width=Inches(2.0)) document.add_heading(name + '\n') document.add_paragraph(phone_number + ' | ' + email) # about informations document.add_heading("About Me") informations = input("Tell us something about you...") document.add_paragraph(informations) # experience area document.add_heading("Experience:") while True: first_user_response = input("Do you have more experience? ") if first_user_response.lower() == "no": break else: company = input("Enter a company: ") perioad = input("Enter the period: ") describe_experience = input("Describe your experience: ") experiences_paragraph = document.add_paragraph() experiences_paragraph.add_run(company + " ").bold = True experiences_paragraph.add_run(perioad + "\n").italic = True experiences_paragraph.add_run(describe_experience) # skills area document.add_heading("Skills") while True: second_user_response = input("Do you have more skills? ") if second_user_response.lower() == "no": break else: skill = input("Enter your skill: ") skills_paragraph = document.add_paragraph() skills_paragraph.style = 'List Bullet' skills_paragraph.add_run(skill) # languages area document.add_heading("Language") while True: third_user_response = input("Do you know more language? ") if third_user_response.lower() == 'no': break else: language = input("Enter a new language: ") languages_paragraph = document.add_paragraph() languages_paragraph.style = 'List Bullet' languages_paragraph.add_run(language) # save the document document.save("resume.docx")
# [2018-08-20] Challenge #366 [Easy] Word funnel 1 # https://www.reddit.com/r/dailyprogrammer/comments/98ufvz/20180820_challenge_366_easy_word_funnel_1/ CHALLENGE_INPUT = { 'leave' : 'eave' , 'reset' : 'rest' , 'dragoon' : 'dragon' , 'eave' : 'leave' , 'sleet' : 'lets' , 'skiff' : 'ski' } BONUS1_INPUT = [ 'dragoon', 'boats', 'affidavit' ] BONUS2_INPUT = 5 # Funnel algorithm for challenge def funnel(a: str, b: str) -> bool: if len(a) != len(b) + 1: return False return b in get_slices(a) # Return all strings that are missing one letter def get_slices(word: str) -> list: return [ word[:i] + word[i+1:] for i, c in enumerate(word) ] # Return all unique slices def get_unique_slices(word: str) -> list: return list(set(get_slices(word))) # Strip newlines from each line in a file (for bonuses) def read_words(file: object) -> list: return [ word.rstrip('\n') for word in file.readlines() ] # Filter the words from enable1.txt to only candidates that make sense def get_candidates(length: int, words: list) -> list: return [ x for x in words if len(x) == length ] # Open our file for bonuses enable1 = open('../../resources/enable1.txt') wordlist = read_words(enable1) # Start execution of the challenge print('Challenge:') for key in CHALLENGE_INPUT: print('funnel("' + key + '", "' + CHALLENGE_INPUT[key] + '") => ' + ('true' if funnel(key, CHALLENGE_INPUT[key]) else 'false')) # # Bonus 1 algorithm def bonus(word: str) -> list: matches = [ x for x in get_unique_slices(word) if x in get_candidates(len(word) - 1, wordlist) ] return matches # Bonus 2 algorithm def bonus2(word: str) -> bool: if len(word) < BONUS2_INPUT: return False slices = get_slices(word) if len(slices) < 5: return False matches = 0 candidates = get_candidates(len(word) - 1, wordlist) for c in candidates: if c in slices: matches = matches + 1 return matches == BONUS2_INPUT # Start execution of bonus 1 print('Bonus 1:') for word in BONUS1_INPUT: output = 'bonus("' + word + '") => [' result = bonus(word) for r in result: output = output + '"' + r + '", ' output = output.rstrip(', ') + ']' print(output) # Start execution of bonus 2 print('Bonus 2:') results = [ word for word in wordlist if bonus2(word)] for k in results: print(k) # End execution enable1.close() input()
# -*- coding: utf-8 -*- """ Created on Thu Dec 07 18:30:03 2017 @author: Otávio Felipe Ferreira de Souza """ import numpy as np import pandas as pd class Usuario(object): def criar_tabela(self): tabela = [] z = raw_input("Digite a funcao Z (Separado por virgulas): " ) #eqz = raw_input("Digite para funcao z: \n <= \n >= \n =") valorbz = 0 #int(raw_input("Digite valor da inequacao: ")) z = z.split(",") z = [int(numero) for numero in z] # converte str para int tamanhoz = len(z) listaz= [] # ira receber as variaveis listaeq = [] #listaeq.append(eqz) for u in range(0, tamanhoz): a11 = z[u] #print a11 locals()['zx{0}'.format(u)] = a11 #cria variaveis x1,x2...''' letra = locals()['zx{0}'.format(u)] listaz.append(letra) listaz.append(valorbz) #adiciona valor de b tabela.append(listaz) print tabela self.nrestricao = int(raw_input("Digite o numero de restricoes:" )) for j in range(0,self.nrestricao): r = raw_input("Digite a funcao da "+str(j+1)+"o restricao (Separado por virgulas): " ) r = r.split(",") r = [int(numero) for numero in r] # converte str para int tamanhoz = len(r) locals()['listar{0}'.format(j)] = [] # cria lista para receber lista com os nomes da restricoes eq = raw_input("Digite para as restricoes (separar por virgula) :\n <= \n >= \n = \n") valorbr = int(raw_input("Digite valor da inequacao de R: ")) #valorbr = valorbr.split(",") #valorbr = [int(numero) for numero in valorbr] #valorbr.append(valorbz) #print valorbr locals()['valorbr{0}'.format(j)]= valorbr #cria e varia a varialel valorbr responsavel por guarda valor da inequação valorbr = locals()['valorbr{0}'.format(j)] #pego valor da variavel valorb{0} e guarda na variavel valorbr para ser adicionado a lista no final #locals()['eqr{0}'.format(j)] = eq #eq = locals()['eqr{0}'.format(j)] listaeq.append(eq) for i in range(0, tamanhoz): #---------------------------------------------------------- a22 = r[i] locals()['r{0}'.format(j)+'_{0}'.format(i)] = a22 letra = locals()['r{0}'.format(j)+'_{0}'.format(i)] locals()['listar{0}'.format(j)].append(letra) locals()['listar{0}'.format(j)].append(valorbr) # adiciona lista da restricao o valorb tabela.append(locals()['listar{0}'.format(j)]) # adiciona a lista na tabela print tabela print listaeq print "tabela : \n", tabela self.igualdade(listaeq,tabela) self.tabela = np.array(self.tabela, dtype = float ) return self.tabela def numero (self): numero11 = artii return numero11 def igualdade(self, listaeq, tabela) : self.listaeq = listaeq self.tabela = tabela self.numartifi = 0 #lista = ['<=','>='] for p in range(1,2+1): locals()['folga{0}'.format(p)] = [[0]] # locals()['artifi{0}'.format(p)] =[0] for ww in range (0,2): locals()['folga{0}'.format(p)].append([0]) listaeq = self.listaeq[p-1] if listaeq == '>=': locals() ['folga{0}'.format(p)] [p] = [-1] locals()['artifi{0}'.format(p)] =[[0]] for ww in range (0,2): locals()['artifi{0}'.format(p)].append([0]) locals()['artifi{0}'.format(p)][p] = [1] self.numartifi += 1 if listaeq == '<=': locals() ['folga{0}'.format(p)][p] = [1] if listaeq == '=': locals()['artifi{0}'.format(p)] =[[0]] for ww in range (1,2+1): locals()['artifi{0}'.format(p)].append([0]) locals()['artifi{0}'.format(p)][p] = [1] self.numartifi += 1 a = np.array(locals()['folga{0}'.format(p)]) self.tabela = np.hstack((self.tabela, a )) print self.tabela for qq in range(1,2+1): try: add_arti = np.array(locals()['artifi{0}'.format(qq)]) self.tabela = np.hstack((self.tabela, add_arti)) except KeyError : pass print (self.tabela) #print (locals()['folga{0}'.format(p)]) #colocando coluna b no final tamanho_tabela = len (self.tabela[0,:]) print 'tamanho tabela', tamanho_tabela ordem = [] for nn in range(0, tamanho_tabela-1 ): indiceb = (tamanho_tabela-1)- (self.numartifi + self.nrestricao) print 'indiceb', indiceb if indiceb == nn: ordem.append(tamanho_tabela-1) ordem.append(nn) print ordem i = np.argsort(ordem) self.tabela = self.tabela[:,i] self.tabela = np.array(self.tabela, dtype = float ) print pd.DataFrame(self.tabela) global artii artii = self.numartifi #Usuario().criar_tabela() #tabela = [listaz, listar1 ]
#217 # Time: O(n) # Space: O(n) # Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, # and it should return false if every element is distinct. class hashTableSol(): def containDuplicate1(self,nums): return len(nums)>len(set(nums)) #217 def containDuplicate2(self,nums): num_appear_by_far={} for num in nums: if num in num_appear_by_far: return True else: num_appear_by_far[num]=True return False
#141 # Time: O(n) # Space: O(1) # Given a linked list, determine if it has a cycle in it. # # Follow up: # Can you solve it without using extra space? class ListNode(): def __init__(self,val): self.val=val self.next=None def __repr__(self): return '{}->{}'.format(self.val,repr(self.next)) class listSol(): def hasCycleListI(self,head): fast,slow=head,head while fast and fast.next: fast,slow=fast.next.next,slow.next if fast == slow: return True return False