text
stringlengths
37
1.41M
print("In Python 3, print is a function so it is invoked with parenthesis") print("The print function also automatically adds a new line, unlike C")
import pandas as pd # 열이름을 key로 두고, 리스트를 value로 갖는 딕셔너리 정의 (2차원배열) dict_data = {"c0": [1, 2, 3], 'c1': [4, 5, 6], 'c2' : [7, 8, 9], 'c3' : [10, 11, 12], "c4" : [13, 14, 15]} # 판다스 DataFrame() 함수로 딕셔너리를 데이터 프레임으로 변환, 변수 df에 저장 df = pd.DataFrame(dict_data) # df의 자료형 출력 print(type(df)) print() # 변수 df에 저장되어 있는 데이터프레임 겍체를 출력 print(df)
import os import time for numero in range(3, -1, -1): os.system('cls') print(numero) time.sleep(1) print('Se Muestra una cuenta regresiva') print('*'*20) print('''Tabla de multiplicar de un número ingresado por el usuario. El usuario también podrá ingresar hasta qué valor llegará la tabla de multiplicar. ''') numero = int(input('¿De qué número deseas ver la tabla de multiplicar?: ')) limite = int(input('Hasta que múltiplo deseas ver?: ')) print(f' Tabla del {numero}') for multiplo in range(1, limite+1): print (f'{numero} X {multiplo} = {numero * multiplo}')
print ("JUEGO PARA ADIVINAR EN QUE NÚMERO PIENSA EL USUARIO") print("""\n Vamos a jugar, te voy a solicitar que realizes unas operaciones sencillas y posteriormente adivinare el número que tienes en mente""") nombre = input("Por favor digita tú nombre: ") print (input(nombre + " presiona enter cuado estes list@")) print ("piensa en un número") print (input(nombre + " presiona enter cuado estes list@")) print ("Multiplica el número por dos") print (input(nombre + " presiona enter cuado estes list@")) print ("Súmale 10 a ese valor") print (input(nombre + " presiona enter cuado estes list@")) print ("Divide el resultado en 2") print (input(nombre + " presiona enter cuado estes list@")) print ("Restale tu número inicial") print (input(nombre + " presiona enter cuado estes list@")) print ("El número que tienes en mente es...") print ("\nEl Cinco")
demo_list = [1, 'hello', 1.34, True, [1, 2,3]] colors = ['red', 'green', 'blue'] numbers_list = list((1, 2, 3, 4)) print (type(numbers_list)) rango = list(range(1, 11)) print (rango) print (type(colors)) print (type(demo_list)) print (len(colors)) print (len(demo_list)) print (colors[2]) colors[0] = 'white' print (colors) #print (dir(colors)) colors.append ("black") print (colors) colors.extend (["orange", "brown"]) print (colors) colors.insert(0, "gray") print (colors) colors.pop() #quita el ultimo print (colors) colors.remove("blue") # remueve el que se digite colors.sort() print (colors)
def solve_euler12(): """The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors?""" next_triangular_num = 0 triangular_nums = {} for i in range(1, 13000): next_triangular_num += i triangular_nums[next_triangular_num] = sorted(find_factors(next_triangular_num)) #print triangular_nums number_of_factors = {} for num in sorted(triangular_nums): number_of_factors[num] = len(triangular_nums[num]) #print max(number_of_factors.values()) over_500 = [] for num in number_of_factors: if number_of_factors[num] > 500: over_500.append((num, number_of_factors[num])) print over_500 def find_factors(num): all_factors = [1, num] for i in range(2,int(num**0.5+1)): if num % i == 0: all_factors.extend([i, num/i]) return all_factors solve_euler12()
class Solution: def longestPath(self, parent: List[int], chrs: str) -> int: children = [[] for i in range(len(parent))] lb = [1] * len(parent) # longest branch of subtree rooted at node i lp = 0 # longest path in general. for n, p in enumerate(parent): if p >= 0: children[p].append(n) s = [0] cb = [] # Callback in reverse order. while len(s) > 0: n = s.pop() for c in children[n]: s.append(c) cb.append(n) """ Cases: leaf => P & B is 1 2 max children branches wo mathcing char + 1 compare to LP LB max child brnach wo mathcing char + 1 compare LP """ while len(cb) > 0: n = cb.pop() lsbs = [] for c in children[n]: if chrs[n] != chrs[c]: if lb[c] + 1 > lb[n]: lb[n] = lb[c] + 1 lsbs.append(lb[c]) if lb[n] > lp: lp = lb[n] lsbs.sort(reverse=True) if len(lsbs) >= 2 and lsbs[0] + lsbs[1] + 1 > lp: lp = lsbs[0] + lsbs[1] + 1 return lp
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] if root == None: return res s = [root] # The stack while len(s) > 0: p = s.pop() if p.right == None and p.left == None: res.append(p.val) else: if p.right != None: s.append(p.right) s.append(p) if p.left != None: s.append(p.left) p.right = None p.left = None return res
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def pairSum(self, head): """ :type head: Optional[ListNode] :rtype: int """ s = [] n = 0 p = head while p != None: p = p.next n += 1 p = head for i in range(n/2): s.append(p.val) p = p.next m = 0 for i in range(n/2): t = s.pop() + p.val if t > m: m = t p = p.next return m
vertex_sets = {} def make_set(x): return {'parent': x, 'count': 1} def find_set(x): if vertex_sets[x]['parent'] == x: return x else: y = find_set(vertex_sets[x]['parent']) vertex_sets[x]['parent'] = y return y def union_set(x, y): x, y = map(find_set, (x, y)) if vertex_sets[x]['count'] < vertex_sets[y]['count']: x, y = y, x vertex_sets[y]['parent'] = x vertex_sets[x]['count'] += vertex_sets[y]['count'] def key_el(x): return x[2] E = [] N, M = map(int, input().split()) for _ in range(M): x, y, w = input().split() w = float(w) vertex_sets[x] = make_set(x) vertex_sets[y] = make_set(y) E.append((x, y, w)) E.sort(key=key_el) min_tree = [] min_weight = 0 for x, y, w in E: if find_set(x) != find_set(y): min_weight += w min_tree.append((x, y, w)) union_set(x, y) print(min_weight, *min_tree, vertex_sets)
""" Сортировка вставками. Идея - берём первый элемент. Он отсортирован. Двигаемся вперёд. Если второй элемент больше первого, то ничего не делаем. В противном случае меняем их местами. Двигаемся дальше. Если третий элемент меньше второго, мы путём обмена местами ставим его на место второго и затем сравниваем с первым..... """ def insert_sort(array): N = len(array) for top in range(1, N): ## top - индекс элемента, который мы хотим вставить в отсортированную часть k = top while k > 0 and array[k] < array[k - 1]: array[k], array[k - 1] = array[k - 1], array[k] k -= 1 if __name__ == "__main__": a = [3,46,345,2,23,3452,0,34,32,1,8,92,4] insert_sort(a) print(a)
# Waiter helper program # Create a menu for the restaurant menu = ["macaroni cheese", "chilli", "fish and chips", "arancini", "nachos", "garlic bread", "falafels"] # Display menu print("Menu:") for item in menu: print(item) # prints each item in the menu # Let the customer order three times ordering = True order_items = [] while ordering: new_item = input("Please enter an order item, or enter 'x' to finish ") if new_item in menu: order_items.append(new_item) # only add the item to the order if it is on the menu print("Thank you, noted") # confirmation message when correctly entered elif new_item == "x": ordering = False # ordering set to False will end the loop else: print("Please make sure the item is on the menu, or enter 'x' to finish") # Read back order in formatted way print("You have ordered:") for item in order_items: print(item)
''' Functions for calculating tau parameters from coordination angles The functions can be used directly for calculations or the combined 'tau' function can be used Christopher Varjas (November 2017) ''' import math theta = math.degrees(math.acos(-1 / 3)) # theta = 109.5 def tau5(b, a): return (b - a) / 60 def tau4(b, a): return (360 - (a + b)) / (360 - (2 * theta)) def tau4prime(b, a): return ((b - a) / (360 - theta)) + ((180 - b) / (180 - theta)) def tau(angles, ligands=None): ''' Angles expects a list If all angles are defined, the correct tau 4 or 5 function will be selected Or the number of ligands can be defined with the second parameter as an integer with only a few angles included in the list ''' # Sort angles that were input angles.sort(reverse=True) # If ligands is defined, use the appropriate function if ligands == 5: return tau5(angles[0], angles[1]) elif ligands == 4: return tau4prime(angles[0], angles[1]) # If ligand count was not defined, try to determine if all angles are defined if len(angles) == 10: return tau5(angles[0], angles[1]) elif len(angles) == 6: return tau4prime(angles[0], angles[1]) else: print('Need to define all complex angles, or set the calculation type to 4 or 5') return False
import random from cell import Person, Sex, Couple from config import * population = {} generations = 0 happiness_per_gen = {} def generate_indexes(num): """ generate random indexes (i,j) pairs in range of width, height :param num: number of indexes to randomly pick :return: array with tuples of (i,j) randomly selected on grid """ places = [] for i in range(WIDTH): for j in range(HEIGHT): places.append((i, j)) xy = random.sample(places, num) return xy def generate_population(num_of_men=50, num_of_women=50): """ generate population of {@num_of_men} men and {@num_of_women} women located in random position on the grid :param num_of_men: how much men are in the population :param num_of_women: how much women are in the population """ def add_person(i, xy): """ adding a person to the population :param i: index of the person :param xy: tuple of (i,j) """ x = xy[i][0] y = xy[i][1] sex = Sex.Male if i < num_of_men else Sex.Female population[(x, y)] = Person(x, y, sex) population.clear() xy = generate_indexes(num_of_men + num_of_women) for i in range(num_of_men + num_of_women): add_person(i, xy) def get_neighbors(current_population, person, radius=2): """ builds dictionary of neighbors from current population to that person :param radius: how far to search :param current_population: dictionary of the current population :param person: to find its neighbors :return: dictionary of (i,j)->neighbor """ start = -radius end = radius + 1 x, y = person.x, person.y neighbors = {} for i in range(start, end): for j in range(start, end): if (i != 0 or j != 0) and (x + i, y + j) in current_population: neighbors[(x + i, y + j)] = (current_population[(x + i, y + j)]) return neighbors def update_potential_partner(current_population): """ create dictionary of couples who both wants each other :param current_population: population of people :return: dictionary of couples """ singles = [p for p in current_population.values() if p.sex != Sex.Couple] # all singles potential_couples = {} for person in singles: best_match = person.best_match(get_neighbors(current_population, person, radius=1)) # best match for couple potential_couples[person] = best_match couples = {} added = [] # add only one of them for person1, person2 in potential_couples.items(): if (person2 in potential_couples) and (person1 not in added): # partner is here if potential_couples[person2] == person1: # mutual desire couples[person1] = person2 added.append(person2) return couples def next_generation(): """ moves all the cells and progress generation """ global generations generations += 1 current_population = population.copy() population.clear() current_population = breakup_couples_if_necessary(current_population) # swap couples potential_couples = update_potential_partner(current_population) # new couples for index, person in current_population.items(): if person in potential_couples: population[(person.x, person.y)] = Couple(person, potential_couples[person]) elif person not in potential_couples.values(): person.move(get_neighbors(current_population, person)) # move regular non empty cells population[(person.x, person.y)] = person happiness_per_gen[generations] = happiness_value() def breakup_couples_if_necessary(current_population): """ search for better option in neighbors for each couple :param current_population: :return: new population with swapped couples """ couples = [couple for couple in current_population.values() if couple.sex == Sex.Couple] for couple in couples: neighbors = get_neighbors(current_population, couple, radius=1) for neighbor in neighbors.values(): couple, neighbor = swap_if_better(couple, neighbor) # swap if better current_population[(couple.x, couple.y)] = couple current_population[(neighbor.x, neighbor.y)] = neighbor return current_population def happiness_value(): happiness = 0 for person in population.values(): happiness += person.happiness_val() return happiness def get_generation_number(): global generations return generations def swap_if_better(couple, p): """ checks if swapping gives a better happiness value :param couple: :param p: couple or person to swap :return: new or same (coupe,p) tuple """ if not CAN_BREAKUP: return couple, p current_val = couple.happiness_val() + p.happiness_val() p = couple.swap(p) new_val = couple.happiness_val() + p.happiness_val() if new_val > current_val: return couple, p p = couple.swap(p) return couple, p def singles_left(): return len([p for p in population.values() if p.sex != Sex.Couple]) > 0 # still singles found
def selection_sort(v): for i in range(len(v)): index_min = i for j in range(i+1, len(v)): if(v[j] > v[index_min]): index_min = j v[i], v[index_min] = v[index_min], v[i] def insertion_sort(v): for i in range(1, len(v)): j = i while j != 0 and v[j] > v[j-1] : v[j], v[j-1] = v[j-1], v[j] j -= 1 def bubble_sort(v): for i in range(len(v)): troca = False for j in range(0, len(v)-i-1): if v[j] < v[j+1]: v[j], v[j+1] = v[j+1], v[j] troca = True if troca == False: break def shell_sort(v): gap = len(v)//2 while gap > 0: for i in range(gap, len(v)): temp = v[i] j = i while j >= gap and v[j-gap] < temp: v[j] = v[j-gap] j -= gap v[j] = temp gap //= 2
from functools import reduce class TreeNode: def __init__(self, value=None, children=None): self.value = value if children: self.children = children else: self.children = [] def __str__(self): return str(self.value) def num_nodes(root): return sum(map(num_nodes, root.children)) + 1 def contains(root, value): return root.value == value or any(contains(r, value) for r in root.children) def preorder(root): ''' reduce is foldl lol ''' return [root.value] + reduce(lambda rec_return, x: rec_return + preorder(x), root.children, []) if __name__ == "__main__": root = TreeNode (1, [TreeNode(2, [TreeNode(5), TreeNode(6)]), TreeNode(3, [TreeNode(7), TreeNode(8), TreeNode(9)]), TreeNode(4)]) print(num_nodes(root)) print(contains(root, 7)) print(contains(root, 90)) print(preorder(root))
age = 21 txt = "My name is Bam, and I am {},{},{}" result = txt.format(age, 28.09, True) print("result", result) # Output: "result My name is Bam, and I am 21"
from collections import MutableMapping # The NormalizedDict type executes a function on the key name # and uses the return value of that function to access # an item in the dictionary. class NormalizedDict(MutableMapping): def __init__(self, normalize_func, *args, **kwargs): self.norm_func = normalize_func self.dict = dict() self.update(dict(*args, **kwargs)) def __getitem__(self, key): return self.dict[self.norm_func(key)] def __setitem__(self, key, value): self.dict[self.norm_func(key)] = value def __delitem__(self, key): del self.dict[self.norm_func(key)] def __contains__(self, key): return self.norm_func(key) in self.dict def __iter__(self): return iter(self.dict) def __len__(self): return len(self.dict) def __str__(self): return str(self.dict) def __repr__(self): return repr(self.dict) if __name__ == "__main__": def lowercase(item): return item.lower() example_data = {"SoMeTHING" : 123, "randomString" : 321} thing_dict = NormalizedDict(lowercase, example_data) print(thing_dict) # The keys from example_data are now lower case! print(thing_dict["something"]) # 123 for key in thing_dict: # Still works because the key will be set to lower case again # when accessing the dict. print(thing_dict[key.upper()]) thing_dict.pop("SOMETHING") print(thing_dict)
""" This exercise stub and the test suite contain several enumerated constants. Since Python 2 does not have the enum module, the idiomatic way to write enumerated constants has traditionally been a NAME assigned to an arbitrary, but unique value. An integer is traditionally used because it’s memory efficient. It is a common practice to export both constants and functions that work with those constants (ex. the constants in the os, subprocess and re modules). You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type """ # Score categories. # Change the values as you see fit. YACHT = lambda d: 50 if len(set(d)) == 1 else 0 ONES = lambda d: d.count(1) TWOS = lambda d: 2 * d.count(2) THREES = lambda d: 3 * d.count(3) FOURS = lambda d: 4 * d.count(4) FIVES = lambda d: 5 * d.count(5) SIXES = lambda d: 6 * d.count(6) FULL_HOUSE = lambda d: sum(d) if len(set(d)) == 2 and (d.count(d[0]) == 2 or d.count(d[0]) == 3) else 0 FOUR_OF_A_KIND = lambda d: 4 * d[0] if d.count(d[0]) >= 4 else 0 + 4 * d[1] if d.count(d[1]) >= 4 and d[0] != d[1] else 0 LITTLE_STRAIGHT = lambda d: 30 if len(set(d)) == 5 and 6 not in d else 0 BIG_STRAIGHT = lambda d: 30 if len(set(d)) == 5 and 1 not in d else 0 CHOICE = lambda d: sum(d) def score(dice, category): return category(dice)
def binary_search(list, item): low = 0 high = len(list)-1 while low <= high: mid = (low+high)//2 guess = list[mid] if guess == item: return mid if guess > item: high = mid-1 else: low = mid+1 return None my_list = [1,3,5,7,9] print(binary_search(my_list, 7))
print ("Welcome to area calculator this program calculates shapes of:") print ("1. Cylinder") print ("2. Pyramid") print ("3. Box") def Cylinder(R,H): #methodos embadon kilindrou brethike apo typo toy internet PI = 3.14 CALC =2 * PI * R * (H + R) return CALC #epistrofh apotelesmatos ston arxiko mas programma def Pyramid(L,H): CALC = 1 / 2 * BL * H * 4 return CALC def Box(BL,BW,H): CALC = (2*BL*BW) + (2*BL*H) + (2*BW*H) return CALC #arxikopoihsh metablhths gia xrish pros ton elegxo ths eisodou toy xrhsth CHOICE = 0; while CHOICE > 3 or CHOICE <= 0: #i used try and except for exception handling to check user input for not using anything rather than interger try: CHOICE = int(input("Please make enter a choice between 1 and 3: ")) except ValueError: print("Please Characters are now allowed!!") else: #diaforetika kanei elegxo ths eisodou toy xrhsth an einai h epilogh 1 if CHOICE == 1: print("\nYou have choose the Cylinder area calculator") #zhtaeu 2 eisagwges toy xrhsth radius kai height xrhsimopoihsa float gia eisodo me dekadika psifia R = float(input("Please enter Radius: ")) H = float(input("Please enter Height: ")) #stelnei sthn method Cylinder tis dyo eisagwges toy xrhsth CALC = float(Cylinder(R,H)) elif CHOICE == 2: print("\nYou have choose the Pyramid area calculator") BL = float(input("Please enter base length: ")) H = float(input("Please enter Height: ")) CALC =float(Pyramid(BL,H)) elif CHOICE == 3: print("\nYou have choose the Box area calculator") BL = float(input("please enter Box Length: ")) BW = float(input("please enter Box Width: ")) H = float(input("please enter Height: ")) CALC = float(Box(BL,BW,H)) #i used if option for more readable option of export if CHOICE == 1: print("The area or Cylinder is: ",CALC) elif CHOICE == 2: print("The area or Pyramid is: ",CALC) elif CHOICE == 3: print("The area or Box is: ",CALC)
#!/usr/bin/python # coding=utf-8 # Copyright 2020 yaitza. All Rights Reserved. # # https://yaitza.github.io/ # # My Code hope to usefull for you. # =================================================================== __author__ = "yaitza" __date__ = "2020-12-23 14:33" ''' 剑指 Offer 06. 从尾到头打印链表 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 示例 1: 输入:head = [1,3,2] 输出:[2,3,1] ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def toString(self): if not self.next: print(str(self.val)) return print(str(self.val) + "->", end='') tmp = self.next while tmp.next: print(str(tmp.val) + "->", end='') if isinstance(tmp.next, ListNode): tmp = tmp.next print(str(tmp.val)) class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head tmp = head stack = list() while tmp.next: stack.append(tmp.val) if isinstance(tmp.next, ListNode): tmp = tmp.next stack.append(tmp.val) nodes = [] for i in stack[::-1]: nodes.append(ListNode(i)) for node in nodes: if nodes.index(node) + 1 < len(nodes): node.next = nodes[nodes.index(node) + 1] return nodes[0] def reverseListEx(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head cur = head while head.next: tmp = head.next.next head.next.next = cur cur = head.next head.next = tmp head.toString() cur.toString() return cur if __name__ == "__main__": node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node5.next = node6 node4.next = node5 node3.next = node4 node2.next = node3 node1.next = node2 node1.toString() ss = Solution() ss.reverseListEx(node1).toString()
#!/usr/bin/python # coding=utf-8 # Copyright 2020 yaitza. All Rights Reserved. # # https://yaitza.github.io/ # # My Code hope to usefull for you. # =================================================================== __author__ = "yaitza" __date__ = "2020-12-24 16:56" ''' 剑指 Offer 25. 合并两个排序的链表 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 示例1: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 限制: 0 <= 链表长度 <= 1000 ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def toString(self): if not self.next: print(str(self.val)) return print(str(self.val) + "->", end='') tmp = self.next while tmp.next: print(str(tmp.val) + "->", end='') if isinstance(tmp.next, ListNode): tmp = tmp.next print(str(tmp.val)) class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1 and not l2: return ListNode() middle_result = [] while l1 or l2: if not l1 and l2: middle_result.append(ListNode(l2.val)) l2 = l2.next if l1 and not l2: middle_result.append(ListNode(l1.val)) l1 = l1.next if (l1 and l2) and (l1.val < l2.val): middle_result.append(ListNode(l1.val)) l1 = l1.next if (l1 and l2) and (l1.val >= l2.val): middle_result.append(ListNode(l2.val)) l2 = l2.next for node in middle_result: if middle_result.index(node) + 1 < len(middle_result): node.next = middle_result[middle_result.index(node) + 1] return middle_result[0] def mergeTwoListsEx(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ cur = dum = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 if l1 else l2 return dum.next if __name__ == "__main__": l14 = ListNode(4) l13 = ListNode(3) l13.next = l14 l1 = ListNode(1) l1.next = l13 l24 = ListNode(4) l22 = ListNode(2) l22.next = l24 l2 = ListNode(1) l2.next = l22 l1.toString() l2.toString() ss = Solution() ss.mergeTwoLists(l1, l2).toString() ss.mergeTwoListsEx(l1, l2).toString()
#!/usr/bin/python # coding=utf-8 # Copyright 2020 yaitza. All Rights Reserved. # # https://yaitza.github.io/ # # My Code hope to usefull for you. # =================================================================== __author__ = "yaitza" __date__ = "2020-12-14 17:02" ''' 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 示例 3: 输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' def isPalindrome(intNo): intStr = str(intNo) n = len(intStr) result = True for i in range(int(n/2)): if intStr[i].__eq__(intStr[-(i+1)]): result = result and True else: result = result and False return result def isPalindromeEx(x): if x < 0 or (x % 10 == 0 and x != 0): return False revert_number = 0 while x > revert_number: revert_number = revert_number * 10 + x % 10 x = int(x / 10) if revert_number == x or int(revert_number / 10) == x: return True else: return False print(isPalindromeEx(0)) print(isPalindromeEx(101)) print(isPalindromeEx(-121))
561. Array Partition I class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums = sorted(nums) return sum(nums[::2]) #the minimum of each pair in a sorted list will always be the first number
import RPi.GPIO as GPIO # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up the GPIO channels - one input and one output GPIO.setup(11, GPIO.IN) GPIO.setup(12, GPIO.OUT) # input from pin 11 input_value = GPIO.input(11) # output to pin 12 GPIO.output(12, GPIO.HIGH) # the same script as above but using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(18, GPIO.OUT) input_value = GPIO.input(17) GPIO.output(18, GPIO.HIGH) """ import sys, pygame pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("intro_ball.gif") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() """
from math import pi, sin, cos from time import sleep from threading import Thread class Fractal: def __init__(self, canvas, depth, x=500, y=1000, length=250, angle=pi/2, deviation=pi/4, decrease=0.7, time=0.0001): self.canvas = canvas self.x, self.y = x, y self.length = length self.angle = angle self.deviation = deviation self.decrease = decrease self.depth = depth self.time = time self.__draw_first_tree(self.x, self.y, self.length, self.angle, self.deviation, self.decrease, self.depth, self.time) def __draw_first_tree(self, x, y, length, angle, deviation, decrease, depth, time): """ Draws part of the tree and passes the rest of the rendering in multi-threaded mode """ x_1, y_1, x_2, y_2 = self.__calculating_coordinates(x, y, length, angle) self.canvas.create_line(x_1, y_1, x_2, y_2, fill='#ffffff') self.canvas.update() sleep(time) if depth > 1: new_length = length * decrease thread_1 = Thread(target=self.__draw_tree_to_right, args=(x_2, y_2, new_length, angle - deviation + pi / 2, deviation, decrease, depth - 1, time,), daemon=True) thread_1.start() thread_2 = Thread(target=self.__draw_tree_to_left, args=(x_2, y_2, new_length, angle - deviation, deviation, decrease, depth - 1, time), daemon=True) thread_2.start() def __draw_tree_to_right(self, x, y, length, angle, deviation, decrease, depth, time): """ Draws a tree from left to right """ x_1, y_1, x_2, y_2 = self.__calculating_coordinates(x, y, length, angle) self.canvas.create_line(x_1, y_1, x_2, y_2, fill='#ffffff') self.canvas.update() sleep(time) if depth > 1: new_length = length * decrease self.__draw_tree_to_right(x_2, y_2, new_length, angle - deviation + pi / 2, deviation, decrease, depth - 1, time) self.__draw_tree_to_right(x_2, y_2, new_length, angle - deviation, deviation, decrease, depth - 1, time) def __draw_tree_to_left(self, x, y, length, angle, deviation, decrease, depth, time): """ Draws a tree from right to left """ x_1, y_1, x_2, y_2 = self.__calculating_coordinates(x, y, length, angle) self.canvas.create_line(x_1, y_1, x_2, y_2, fill='#ffffff') self.canvas.update() sleep(time) if depth > 1: new_length = length * decrease self.__draw_tree_to_left(x_2, y_2, new_length, angle - deviation, deviation, decrease, depth - 1, time) self.__draw_tree_to_left(x_2, y_2, new_length, angle - deviation + pi / 2, deviation, decrease, depth - 1, time) @staticmethod def __calculating_coordinates(x, y, length, angle): """ Calculating coordinates for building a tree branch """ return x, y, round(x + length * cos(angle)), round(y - length * sin(angle))
import random def ordenamiento(lista): """Sorts a list of ints in ascending order. Big-O Complexity: O(n^2)""" for i in range(len(lista)): key = lista[i] j = i - 1 while j >= 0 and lista[j] > key: lista[j + 1] = lista[j] j -= 1 lista[j + 1] = key return lista list_int = [random.randint(0, 100) for i in range(20)] print("before: ", list_int) ordenamiento(list_int) print("after: ", list_int)
def genPrimes(): 'Yield generator of prime numbers' p=[] x=2 while True: while True: prime=True for i in p: if x%i==0: prime=False break if prime==False: x+=1 else: next=x break yield next p.append(x) x=next+1 primes=genPrimes() def getPrimes(): while True: n=input('How many prime numbers do you want to generate? ') try: for i in range(int(n)): print(primes.__next__()) break except ValueError: print('Please choose a positive integer')
def make_set(x): p[x] = x def find_set(x): if p[x] == x: return x else: return find_set(p[x]) def union(x, y): # x의 대표자, y의 대표자를 찾음 p[find_set(y)] = find_set(x) N = 6 p = [0] * (N+1) for i in range(1, N+1): make_set(i) # print(p) union(1, 3) union(2, 3) union(5, 6) print(p) print(find_set(6))
#Desafio 1 # num = int(input("Ingresá un número: ")) # if num % 2 == 0: # print("Es par") # else: # print("Es impar") #Desafio 2 # num = int(input("Ingresá un número: ")) # if num % 2 == 0: # print("Es múltiplo de 2") # elif num % 3 == 0: # print("Es múltiplo de 3") # elif num % 5 == 0: # print("Es múltiplo de 5") # else: # print("No es múltiplo de 2, 3 ó 5") #Desafio 3 # letra = input("Ingresá una letra: ") # if letra >= 'a' and letra <= 'z': # print("Es minúscula") # elif letra >= "A" and letra <= "Z": # print("Es mayúscula") # else: # print("No es una letra") #Desafio 4 # caracter = input("Ingresa un caracter: ") # if caracter == '\"': # print("Es una comilla") # else: # print("NO es una comilla") #Desafio 5 # cadena1 = input("Ingresá una palabra: ") # cadena2 = input("Ingresá otra palabra: ") # if len(cadena1) > len(cadena2): # print(cadena1) # else: # print(cadena2) #Desafio 6 cadena = input("Ingrese una palabra: ") cantidad = 0 for car in cadena: if car == "a": cantidad = cantidad + 1 print(f"Cantidad de letras \"a\": {cantidad}")
#! /usr/bin/env python3 import random def d6(sides, faces): n = 0 for i in range(sides): n += random.randint(1, faces) return n def room(): n = d6(1,6) m = d6(1,6) if n==1 or n == 2: print ("monster in room", file=f) if m == 1 or m == 2 or m == 3: print ("treasure present", file=f) else: print("empty") if m == 1: print ("treasure present", file=f) def rollHMStats(): Str = str(d6(3,6)) Dex = str(d6(3,6)) Con = str(d6(3,6)) Int = str(d6(3,6)) Wis = str(d6(3,6)) Cha = str(d6(3,6)) Com = str(d6(3,6)) StrP = str(d6(1,100)) DexP = str(d6(1,100)) ConP = str(d6(1,100)) IntP = str(d6(1,100)) WisP = str(d6(1,100)) ChaP = str(d6(1,100)) ComP = str(d6(1,100)) print ("Str: "+Str+" / "+StrP, file=f) print ("Dex: "+Dex+" / "+DexP, file=f) print ("Con: "+Con+" / "+ConP, file=f) print ("Int: "+Int+" / "+IntP, file=f) print ("Wis: "+Wis+" / "+WisP, file=f) print ("Cha: "+Cha+" / "+ChaP, file=f) print ("Com: "+Com+" / "+ComP, file=f) try: filename = input("enter filename here \n")+".txt" except EOFError: filename = "default.txt" f = open(filename, 'w') rollHMStats() f.close()
import Tkinter as tk import time def current_iso8601(): """Get current date and time in ISO8601""" # https://en.wikipedia.org/wiki/ISO_8601 # https://xkcd.com/1179/ return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.now = tk.StringVar() self.time = tk.Label(self, font=('Helvetica', 24)) self.time.pack(side="top") self.time["textvariable"] = self.now self.QUIT = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.QUIT.pack(side="bottom") # initial time display self.onUpdate() def onUpdate(self): # update displayed time self.now.set(current_iso8601()) # schedule timer to call myself after 1 second self.after(1000, self.onUpdate) root = tk.Tk() app = Application(master=root) root.mainloop()
## Linear SVC machine learning and testing our data import numpy as np import matplotlib.pyplot as plt from sklearn import svm import pandas as pd from matplotlib import style style.use("ggplot") ##defined a function to build our dataset def Build_Data_Set(features = ["DE Ratio", "Trailing P/E"]): ##loaded our data to the variable data_df data_df = pd.DataFrame.from_csv("key_stats1.csv") ##extracted first 100 rows of the data data_df = data_df[:100] ##we fill the X parameter with the NumPy array containing rows of features X = np.array(data_df[features].values) ##we replace our status column with numerical data y = (data_df["Status"] .replace("underperform",0) .replace("outperform",1) .values.tolist()) ##finally we return X and y return X,y ##Analysing and visualising our data def Analysis(): X, y = Build_Data_Set() clf = svm.SVC(kernel="linear", C= 1.0) clf.fit(X,y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(min(X[:, 0]), max(X[:, 0])) yy = a * xx - clf.intercept_[0] / w[1] h0 = plt.plot(xx,yy, "k-", label="non weighted") plt.scatter(X[:, 0],X[:, 1],c=y) plt.ylabel("Trailing P/E") plt.xlabel("DE Ratio") plt.legend() plt.show() Analysis()
# 代入する引数x, y, z x = 5 y = 6 z = 2 # defを用いてfunc3を作成して下さい def func3(x,y,z): return x*y +z # lambdaを用いてfunc4を作成して下さい func4 = lambda x,y,z:x*y +z # 出力 print(func3(x, y, z)) print(func4(x, y, z))
# 時間データhour, 分データminute hour = [0, 2, 3, 1, 0, 1, 1] minute = [30, 35, 0, 14, 11, 0, 22] # 時, 分を引数に、分に換算する関数を作成して下さい conv_minute = lambda x,y: x*60+y # リスト内包表記を用いて所定の配列を作成してください result = [conv_minute(x,y) for x,y in zip(hour,minute)] # 出力して下さい print(result)
from functools import reduce #Google的文章 #Pythone内置了 map 和 reduce 函数() #map() #原型 map(fn,lsd) #参数1 是函数 #参数2 是序列 #功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回 #将单个字符转成对应字面的整数 def chr2int(chr): return {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[chr] list1 = ["2","1","4","2","4","5","6",] res = map(chr2int,list1) print(res) print(list(res)) #将list1里面的元素 都进入 cha2int 计算一次 #res序列对象 是一个惰性列表 需要使用list()显示 #将整数元素的序列,转为字符串类型 #【1,2,3,4,5】->【"1","2","3","4","5"】 l = map(str,[1,2,3,4,5]) print(list(l)) #reduce(fn,lsd) #参数1 :函数 #参数2:列表 #功能:一个函数作用在序列上,这个函数必须接受两个参数,reduce把结果继续和序列下一个元素累计计算 #reduce(f,[a.b.c.d]) #f(f(f(a,b),c),d) #求一个序列的 和 list2 = [1,2,3,4,5,6,7,8,9] def mysun(x,y): return x+y r = reduce(mysun,list2) print(r) #需求:将字符串转成对应字面量的数字 def str22int(str): def fc(x,y): return x * 10 + y def fs(chr): return {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}[chr] return reduce(fc,map(fs,str)) print(str22int("1232321321")) print(int("123"))
import threading,time a = 10 def run(num): print("子线程(%s)启动" % threading.current_thread().name) print(num) print(a) time.sleep(2) #实现线程的功能 print("打印") time.sleep(2) print("子线程(%s)结束"% threading.current_thread().name) if __name__ == "__main__": #任何进程默认就会启动一个线程,这个线程称为主线程,主线程可以启动新的子线程 #threading.current_thread() :返回当前线程的实例 print("主线程(%s)启动" % (threading.current_thread().name)) #创建子线程 t = threading.Thread(target=run,name="runThread",args=(1,)) t.start() #等待线程结束 t.join() print("主线程(%s)结束" % (threading.current_thread().name))
import datetime ''' datetime比time高级很多,可以理解为datetime基于time进行了封装,提供了更多使用的函数,datetime模块的接口也更直观,更容易调用 模块中的类: datetime 同时有时间和日期 timedelta 主要用于计算时间的跨度 tzinfo 时区相关 time 只关注时间 date 只关注日期 ''' #获取当前时间 d1 = datetime.datetime.now() print(d1) print(type(d1)) #获取指定的时间 d2 = datetime.datetime(1999,10,1,10,28,25,123456) print(d2) #将时间转换为字符串 d3 = d1.strftime("%Y-%m-%d %X") print(d3) print(type(d3)) #将格式化字符串转换为datetime对象 #转换的格式要与字符串一致 d4 = datetime.datetime.strptime(d3,"%Y-%m-%d %X") print(d4) d5 = datetime.datetime(1999,10,1,10,28,25,123456) d6 = datetime.datetime.now() d7 = d6 - d5 print(d7) print(type(d7)) #间隔天数 print(d7.days) #间隔天数除外的秒数 print(d7.seconds)
import tkinter def func(): print("sunck is a good man .") win = tkinter.Tk() win.title("标题") win.geometry("400x400+200+20") ''' ''' #创建按钮 #text 按钮的文字 #command 按钮的动作 button1 = tkinter.Button(win, text = "按钮", command = func, width = 3, height =5) button1.pack() button2 = tkinter.Button(win, text = "按钮", command = lambda :print("sunck ")) button2.pack() button3 = tkinter.Button(win, text = "关闭", command = win.quit) button3.pack() win.mainloop()
def table(): for i in range(1,11): x = [] for j in range(1,11): k = i*j x.append(k) print(x) return None table()
def num2word(): yourNum = list(input("Input you number: ")) ones = {'1':'one', '2':'two', '3':'three', '4':'four', '5':'five', '6':'six', '7':'seven', '8':'eight', '9':'nine'} teens = {'10':'ten', '11':'eleven', '12':'twelve', '13':'thirteen', '14':'fourteen', '15':'fifteen', '16':'sixteen', '17':'seventeen', '18':'eighteen', '19':'nineteen'} numLength = len(yourNum) if numLength == 1: return ones[yourNum[0]] elif numLength == 2 and yourNum[0] == '1': return teens["".join(yourNum)] else: return beyond(yourNum) def beyond(yourNum): print(num2word())
# -*- coding: utf-8 -*- import unittest def intersection(head1, head2): A = {} while head1: A[head1] = 1 head1= head1.next while head2: if head2 in A: return head2 head2 = head2.next return None class Node(): def __init__(self, data, next=None): self.data, self.next = data, next def __str__(self): string = str(self.data) if self.next: string += ',' + str(self.next) return string class Test(unittest.TestCase): def test_intersection(self): head1 = Node(10,Node(20,Node(30))) head2 = Node(20,Node(30,Node(40))) self.assertEqual(intersection(head1, head2), None) node = Node(70,Node(80)) head3 = Node(50,Node(20,node)) head4 = Node(60,Node(90,Node(10,node))) self.assertEqual(intersection(head3, head4), node) unittest.main()
# Design a binary tree class that can return a random node. class Node(): def __init__(self, data=None, left=None, right=None): self.data, self.left, self.right = data, left, right self.count = 1 if self.left: self.count += self.left.count if self.right: self.count += self.right.count def get_random_node(self): return self.get_numbered_node(randint(0, self.count - 1)) def get_all_nodes(self, node): if not node: return None array = [node] if node.left: array+=self.get_all_nodes(node.left) if node.right: array+=self.get_all_nodes(node.right) return array def get_numbered_node(self, number): return self.get_all_nodes(self)[number] import random import unittest mock_random_value = False def randint(lower_bound, upper_bound): if not mock_random_value is False: return mock_random_value return random.randint(lower_bound, upper_bound) class Test(unittest.TestCase): def test_mock_randint(self): global mock_random_value mock_random_value = 12 self.assertEqual(randint(0, 2000), 12) def test_get_random_value(self): global mock_random_value tree = Node(11,Node(21,Node(31),Node(32,Node(41),Node(42,None,Node(51)))), Node(22,Node(33),Node(34))) mock_random_value = 0 self.assertEqual(tree.get_random_node().data, 11) mock_random_value = 4 self.assertEqual(tree.get_random_node().data, 41) mock_random_value = 8 self.assertEqual(tree.get_random_node().data, 33) if __name__ == "__main__": unittest.main()
import unittest class Solution(object): def longestPalindrome(self, s): li = list(s) li_int = [0] * 256 for item in li: li_int[ord(item)] = li_int[ord(item)] + 1 count = 0 for item in li_int: if item % 2 != 0: count = count + 1 if count == 0: count = 1 return len(s) - count + 1 class Test(unittest.TestCase): def test(self): self._test('AaBbfjosejif',5) def _test(self, ls,expected): actual = Solution().longestPalindrome(ls) self.assertEqual(actual, expected) if __name__ == '__main__': unittest.main()
print "This is python 2.7" def add(a, b): return a + b i = add(5, 7) print 'meow' x = 5 + 6 print 'this is more text' y = "JUlian the born again boolean" print y y = "JUlian the born again boolean" print y y = "JUlian the born again boolean" print y print i
# Multiply all the elements in a list def multiply_list(l): if len(l) == 1: return l[0] else: return l[0] * multiply_list(l[1:]) # Return the factorial of n def factorial(n): if n == 1: return n else: return factorial(n-1) * n # Count the number of elements in the list l def count_list(l): count = 1 if len(l) == 1: return 1 else: count = count_list(l[1:]) + 1 return count # Sum all of the elements in a list def sum_list(l): if len(l) == 1: return l[0] else: return l[0] + sum_list(l[1:]) # Reverse a list without slicing or loops def reverse(l): if len(l) == 1: return l else: popped = l.pop(0) reverse(l) l.append(popped) return l # Fibonacci returns the nth fibonacci number. The nth fibonacci number is # defined as fib(n) = fib(n-1) + fib(n-2) def fibonacci(n): if n == 1 or n == 0: return 1 else: return fibonacci(n-1) + fibonacci(n-2) # Finds the item i in the list l.... RECURSIVELY def find(l, i): if l[0] == i: return True elif len(l) == 1: return False else: return find(l[1:], i) # Determines if a string is a palindrome def palindrome(some_string): if len(some_string) <= 1: return some_string elif some_string[0] == some_string[-1]: palindrome(some_string[1:-1]) return True return False # Given the width and height of a sheet of paper, and the number of times to fold it, return the final dimensions of the sheet as a tuple. Assume that you always fold in half along the longest edge of the sheet. def fold_paper(width, height, folds): if folds == 0: return width, height else: if width > height: return fold_paper(width/2.0, height, folds-1) else: return fold_paper(width, height/2.0, folds-1) # Count up # Print all the numbers from 0 to target def count_up(target, n): if n == 0: print n else: count_up(target, n-1) print n
# utilize a file named on the command line from sys import argv script, filename = argv # open the file named on the command line def open_read_close(some_file): f = open(some_file) filetext = f.read() f.close() return filetext # We want to make everything lowercase before we separate it in separate() def make_lower(some_string): some_string = some_string.lower() return some_string # separate words by white space def separate(some_string): output = some_string.split() return output # strip the words of punctuation # you're not making a copy of this list. You're changing the original list #Liz2Lizz def strip_punctuation(some_list): for i in range(len(some_list)): some_list[i] = some_list[i].strip(".,'!?\";") return some_list # create a dictionary to store words (keys) and their counts (values) # count how many times a word occurs in that file def counts(some_list): count_dict = {} for each in some_list: # if key is not in dictionary, create a new key and set it's value to 1 if count_dict.get(each, 0) == 0: count_dict[each] = 1 # else: increment value of key by 1 else: count_dict[each] += 1 return count_dict # make a dictionary that has counts as keys and list of words as values def sort_frequency(some_dict): # prime an empty dictionary sorted_dict = {} #create a word list from the dictionary argument word_list = some_dict.keys() #sort it alphabetically word_list.sort() #take each word from the word_list and sort it in the dictionary based on its count for word in word_list: value = some_dict[word] # check if the word's count is already a key. If it isn't create one and place the word in a list as the count's value. if sorted_dict.get(value, 0) == 0: sorted_dict[value] = [word] # if the word's count is already a key, append the word to the value list else: sorted_dict[value].append(word) return sorted_dict def print_counts(some_dict): # make a list of keys and sort them by frequency keys = some_dict.keys() keys.sort() # print the key and value for key in keys: for each in some_dict[key]: print each, key opened = open_read_close(filename) lowered = make_lower(opened) separated = separate(lowered) no_punctuation = strip_punctuation(separated) counted = counts(no_punctuation) s = sort_frequency(counted) print_counts(s)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 类的继承 class Animal(object): def __init__(self, name: str = 'animal'): self.__name = name def __len__(self): # 使用系统函数len()时会调用类的__len__()方法 return self.__name.__len__() # len(obj)和obj.__len__()效果相同 def run(self): print('{} is running...'.format(self.__name)) def eat(self): print('{} is eating...'.format(self.__name)) class Cat(Animal): def __init__(self, name: str = 'cat'): super().__init__(name) class Dog(Animal): def __init__(self, name: str = 'cat'): super().__init__(name) class Python(Animal): def __init__(self, name: str = 'python'): super().__init__(name) def main(): mycat = Cat('mycat') mycat.run() print(isinstance(mycat, Cat)) # 判断对象实例的类型是否是Cat print(isinstance(mycat, Animal)) # 继承自Animal的Cat仍然也是Animal print('len(mycat):', len(mycat), 'mycat.__len__():', mycat.__len__()) print('dir(mycat):', dir(mycat)) # 查看实例的所有属性和方法 if __name__ == '__main__': main()
# 小球移动一次的函数 def move(ball: list, lenth_of_line: int): if ball[0] == "right": if ball[1] == lenth_of_line: # 到右边界 ball[1] -= 1 ball[0] = "left" else: ball[1] += 1 else: if ball[1] == 0: # 到左边界 ball[1] += 1 ball[0] = "right" else: ball[1] -= 1 # 碰撞检测 def meet(ball1: list, ball2: list): if ball1[1] == ball2[1]: return True else: return False # 显示所有小球位置 def display_balls(ball_list: list): for ball in ball_list[:-1:]: print(ball[1], end=' ') print(ball_list[-1][1]) # 改变小球方向 def change_direction(ball: list): if ball[0] == "right": ball[0] = "left" else: ball[0] = "right" if __name__ == '__main__': args_g1 = input().split(" ") # 个数 线段长 时间 args_g2 = input().split(" ") # 初始时刻小球位置 ball_list = list() line_lenth = int(args_g1[1]) time = int(args_g1[2]) for number in range(0, int(args_g1[0])): # 小球的格式: ball[direction: str, position: int] ball_list.append(["right", int(args_g2[number]), False]) while True: if time == 0: break for aball in ball_list: # 对所有小球的两两组合进行碰撞检测 if aball[2]: # 如果已经逆置方向则跳过 aball[2] = False continue for bball in ball_list: if bball == aball: continue if meet(aball, bball): bball[2] = True # 避免重复逆置方向的标记 change_direction(aball) change_direction(bball) break for ball in ball_list: # 移动所有小球 move(ball, line_lenth) time -= 1 display_balls(ball_list)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################################################## n = 123 f = 456.789 s1 = 'Hello, world' s2 = 'Hello, \'Adam\'' s3 = r'Hello, "Bart"' s4 = r'''Hello, Lisa!''' print(n) print(f) print(s1) print(s2) print(s3) print(s4) s1.encode('ascii') ################################################################## str='Runoob' print(str) # 输出字符串 print(str[0:-1]) # 输出第一个到倒数第二个的所有字符 print(str[0]) # 输出字符串第一个字符 print(str[2:5]) # 输出从第三个开始到第五个的字符 print(str[2:]) # 输出从第三个开始的后的所有字符 print(str * 2) # 输出字符串两次 print(str + '你好') # 连接字符串 print('------------------------------') print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符 print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义 ################################################################## # print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=""或end='' print(x, end="") print(y, end='') input('\n按enter退出\n============================\n')
import json import csv def json_to_csv(): with open("1.json", "rt", encoding="utf-8") as f: content = f.read() li = json.loads(content) print(li) with open("out.csv", "wt", encoding="utf-*", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "id"]) for item in li: writer.writerow([item["name"], item["id"]]) def csv_to_json(): li = [] with open("out.csv", "rt", encoding="utf-8") as f: reader = csv.reader(f) next(reader) for line in reader: obj = {"name": line[0], "id": line[1]} li.append(obj) with open("to_json.json", "wt") as f: json_str = json.dumps(li) f.write(json_str) if __name__ == "__main__": csv_to_json()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 用一系列运算测试一下多进程多线程和普通方法的速度 from multiprocessing import Process, Queue from threading import Thread import time # 待解决问题:尝试过将子进程、线程函数分别装入 多进程计算主函数 和 多线程计算主函数 # 会导致程序报错 """""" # 普通方法计算 def normal(number): res = 0 for i in range(number): res = res + i + i ** 2 + i ** 3 + i ** 4 return res # 在多进程/线程中将计算任务拆分成两部分 def job1(q, number): """ 计算任务1 """ res = 0 for i in range(number): res = res + i + i ** 2 + i ** 3 q.put(res) def job2(q, number): """ 计算任务2 """ res = 0 for i in range(number): res = res + i ** 4 q.put(res) # 多进程计算主函数 def mp(number, *args): queue = Queue() p1 = Process(target=args[0], args=(queue, number)) p2 = Process(target=args[1], args=(queue, number)) p1.start() p2.start() p2.join() p1.join() return queue.get() + queue.get() # 多线程计算主函数 def mt(number, *args): queue = Queue() t1 = Thread(target=args[0], args=(queue, number)) t2 = Thread(target=args[1], args=(queue, number)) t1.start() t2.start() t2.join() t1.join() return queue.get() + queue.get() def main(): # 计算1-n的平方、立方、四次方的和 number = 10000000 time_normalstart = time.time() normal_res = normal(number) time_normalend = time.time() print('普通计算:\n用时:{}s\n结果:{}\n'.format(time_normalend - time_normalstart, normal_res)) time_mpstart = time.time() mp_res = mp(number, job1, job2) time_mpend = time.time() print('多进程:\n用时:{}s\n结果:{}\n'.format(time_mpend - time_mpstart, mp_res)) time_mtstart = time.time() mt_res = mt(number, job1, job2) time_mtend = time.time() print('多线程:\n用时:{}s\n结果:{}\n'.format(time_mtend - time_mtstart, mt_res)) if __name__ == '__main__': main()
#!/usr/bin/env python class Name: """ Name Class """ def __init__(self, fname, mname, lname): self.first_name = fname self.middle_name = mname self.last_name = lname @property def first_name(self): return self._first_name @first_name.setter def first_name(self, fname): if fname: self._first_name = fname else: ValueError('First name can not be none') @property def middle_name(self): return self._middle_name @middle_name.setter def middle_name(self, mname): self._middle_name = mname @property def last_name(self): return self._last_name @last_name.setter def middle_name(self, lname): self._last_name = lname
import random board = [["1","2","3"], ["4","5","6"], ["7","8","9"]] def initialiseBoard(): global board board = [["1","2","3"], ["4","5","6"], ["7","8","9"]] def getPos(y,x): global board '''We need to return whatever is at the board position x,y''' def setPos(y,x,value): global board '''We need to set the board position at x,y to the value we have passed in''' # # # Only look at the code below here if you are interested! # If you just want to get the game working, you only have to write the code above # # def displayBoard(): global board #Loop through each row of the board, and display it for y in range(0,3): print (board[y]) def checkForWin(): hasWon = False #First check for 3 across for y in range(0,3): same = True for x in range(0,3): if x > 0: same = same and getPos(y,(x-1)) == getPos(y,x) if (same): hasWon = True #Then check for 3 down for x in range(0,3): same = True for y in range(0,3): if y > 0: same = same and getPos((y-1),x) == getPos(y,x) if (same): hasWon = True #Finally check diagonals hasWon = hasWon or (getPos(0,0) == getPos(1,1) and getPos(1,1) == getPos(2,2)) or (getPos(0,2) == getPos(1,1) and getPos(1,1) == getPos(2,0)) return hasWon running = True while running: wouldYouLikeToPlay = input("Would you like to play a game? (Y/n)") if wouldYouLikeToPlay == "" or wouldYouLikeToPlay.lower().startswith("y"): gameWon = False #Clear the board initialiseBoard() print("You are going to play as O, so the computer will move first") #Place the computer's first piece setPos(random.randint(0,2),random.randint(0,2),"X") #Loop while the game has not been won while not gameWon: #Display the board displayBoard() #Get the players input playerChoice = input("Where would you like to place a piece?") playHappened = False for y in range(0,3): for x in range(0,3): #If this coordinate is the number that the player entered (and they didn't try to cheat by using "X" or "O") if getPos(y,x) == playerChoice and (playerChoice != "X" and playerChoice != "O"): #Confirm that something has happened this turn, and set the board position to an O playHappened = True setPos(y,x,"O") #If there has been a win since that piece was placed, the player has won, so tell them that if checkForWin(): print("You won!") displayBoard() gameWon = True #Otherwise, we need to see what the computer will do else: nextPosX = random.randint(0,2) nextPosY = random.randint(0,2) #Generate new random numbers until the computer has selected an empty square while getPos(nextPosY,nextPosX) == "X" or getPos(nextPosY,nextPosX) == "O": nextPosX = random.randint(0,2) nextPosY = random.randint(0,2) #Place an X in the square that the computer has chosen setPos(nextPosY,nextPosX,"X") #If there has been a win after that piece was placed, the computer has won, so say that if checkForWin(): print("Computer won!") displayBoard() gameWon = True #If nothing happened this turn, it means the player chose an invalid space, so tell them that if not playHappened: print("Please choose an unoccupied space") #Otherwise, we need to check if there are any free spaces else: vacantSquare = False for y in range(0,3): for x in range(0,3): #This line is a bit complicated, but, basically, if there is any unfilled square, this will set vacantSquare to True. If you've got any questions about this, I can explain it to you in more detail. vacantSquare = vacantSquare or (getPos(y,x) != "X" and getPos(y,x) != "O") #If there are no blank spaces, and the game hasn't been won, then there has been a draw. if not vacantSquare and not gameWon: gameWon = True print("It was a draw!") displayBoard()
def chess(test): queen = [] obstacles = [] for y in range(len(test)): n = len(test) for x in range(len(test[y])): if test[y][x] == 'K': queen = [y+1, x+1] if test[y][x] == 'X': obstacles.append([y+1,x+1]) print(queen) print(obstacles) test = [ [ "","","","","" ], [ "","X","X","X","X" ], [ "X","X","K","X","" ], [ "","X","X","X","X" ], [ "","","","","" ] ] # print(len(test)) chess(test)
def chess(test): queen = [] obstacles = [] n = len(test[0]) for y in range (len(test)): for x in range (len(test[y])): if test[y][x] == 'K': queen = [y+1, x+1] if test[y][x] == 'X': obstacles.append([y+1, x+1]) step_up = queen[0] - 1 step_down = n - queen[0] step_right = n - queen[1] step_left = queen[1] - 1 for obs in obstacles: if obs[0] == queen[0]: if obs[1] < queen[1] and ((queen[1] -obs[1] -1 ) < step_left): step_left = queen[1] - obs[1] -1 if obs[1] > queen[1] and ((obs[1]- queen[1] - 1) < step_right ): step_right = obs[1] - queen[1] - 1 if obs[1] == queen[1]: if obs[0] < queen[0] and ((queen[0] - obs[0] - 1) <step_up): step_up = queen[0] - obs[0] - 1 if obs[0] > queen[0] and (( obs[0] -queen[0] - 1) > step_down): step_down = obs[0] -queen[0] - 1 print(step_down) chess( [ [ "","","","","" ], [ "","","","","" ], [ "X","","K","","" ], [ "","","X","","" ], [ "","","","","" ] ])
import matplotlib.pyplot as plt import numpy as np import pandas as pd import skfuzzy as fuzz from pandas._typing import FrameOrSeries from source.Input import Fuzzy_input class Fuzzy(): ''' intialize the fuzzy class ''' def __init__(self): pass def fuzzify(self, data : FrameOrSeries,cont_feats:list,potencial_index:int, Target_index:int) -> FrameOrSeries : """ Class method aiming to fuzzify only on data frame serie at once The output of every single serie will be appended to one fuzzified dataframe containing all equivalent fuzzified dataframe series. Parameters: ---------- data : Pandas DataFrame, serie to fuzzify. cont_feats: list , precising which variables are continuous to an index list. potencial_index : int , index of the variable to to estimate it's effect(eq. to treatment) Target_index : int, index of the variable to search it's causes(eq. to outcome) Returns: ------- out : list of fuzzy sets. Notes ----- The process of precising the Closure of the given data and the number of fuzzy sets is automated , This class adds also the automoation of numbers of fuzzy sets using fuzzy C-means Clustering testing multiple outcomes with a number of clusters ranging from 2 to 9 and using the optimal number of fuzzy sets corresponding to the highest fuzzy partition coefficient(In case if the input data has more than two continuous variables so it is possible to apply the clustering). """ ########################## #Fuzzy c-means clustering# ########################## if len(cont_feats)>1 and isinstance(data, pd.DataFrame) : np.random.seed(10) xpts=np.asanyarray(data.iloc[:,0]) ypts=np.asanyarray(data.iloc[:,1]) colors = ['b', 'orange', 'g', 'r', 'c', 'm', 'y', 'k', 'Brown', 'ForestGreen'] fig1, axes1 = plt.subplots(3, 3, figsize=(8, 8)) alldata = np.vstack((xpts, ypts)) fpcs = [] for ncenters, ax in enumerate(axes1.reshape(-1), 2): cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans( alldata, ncenters, 2, error=0.005, maxiter=1000, init=None) # Store fpc values for later fpcs.append(fpc) # Plot assigned clusters, for each data point in training set cluster_membership = np.argmax(u, axis=0) for j in range(ncenters): ax.plot(xpts[cluster_membership == j], ypts[cluster_membership == j], '.', color=colors[j]) fig2, ax2 = plt.subplots() ax2.plot(np.r_[2:11], fpcs) ax2.set_xlabel("Number of centers") ax2.set_ylabel("Fuzzy partition coefficient") ############################################################# #Building the model With Argmax(Fuzzy partition Coefficient)# #-----------------------------------------------------------# ############################################################# cntr, u_orig, _, _, _, _, _ = fuzz.cluster.cmeans( alldata, 3, 2, error=0.005, maxiter=1000) # Show 3-cluster model fig2, ax2 = plt.subplots() ax2.set_title('Trained model') for j in range(3): ax2.plot(alldata[0, u_orig.argmax(axis=0) == j], alldata[1, u_orig.argmax(axis=0) == j], 'o', label='series ' + str(j)) ax2.legend() # Generate uniformly sampled data spread across the range [0, 10] in x and y newdata = np.random.uniform(0, 1, (1100, 2)) * 10 u, u0, d, jm, p, fpc = fuzz.cluster.cmeans_predict( newdata.T, cntr, 2, error=0.005, maxiter=1000) cluster_membership = np.argmax(u, axis=0) else : raise Exception("Not Enough Continuous Variable to Cluster") if np.argmax(fpcs)>1 and np.argmax(fcps)%2==1 : num_set=np.argmax(fpcs) else : num_set=3 bin_feats=[i for i in range(len(data.columns)) if i not in cont_feats ] df=data.copy() out=pd.DataFrame() for column in df.columns: if df.columns.get_loc(column) in cont_feats: obj = Fuzzy_input() col = pd.DataFrame({column + '_low': obj.fuzzify(df[column], 'gaussian')[0], column + '_average': obj.fuzzify(df[column], 'gaussian')[1], column + '_high': obj.fuzzify(df[column], 'gaussian')[2]}) out = pd.concat([out, col], axis=1) else : out = pd.concat([out,df[column]],axis=1) return out
""" Ejemplo1: Uso de la funcion lambda """ #map lista = [10,2,3,5,1] funciones = lambda x: x+100 print (min(list(map(funciones,lista))))
""" Desarrollar la función anónima que retorne True or False si el número dado es par. """ #Ingreso por teclado del numero a evaluar numero = input("Ingrese el numero: \n") #Especificar el tipo de dato numero = int(numero) #Funcion para realizar una comparacion impar = lambda numero : numero%2 !=0 #Al final luego de realizar la comparacion se arroja un dato True or False print(impar(numero))
#!/usr/bin/python3 """ Writes a string to a text file (UTF8), returns the number of characters written """ def write_file(filename="", text=""): """ args: filename= name of the file, text = text to write in the file """ with open(filename, mode="w", encoding="utf-8") as myFile: numb_bites_written = myFile.write(text) return numb_bites_written
#!/usr/bin/python3 """Function that prints a text with 2 new lines after each of these characters: ., ? and : """ def text_indentation(text): """ text = text to indent """ types = [str] check = ['.', '?', ':'] if type(text) not in types: raise TypeError("text must be a string") new = [] for i, char in enumerate(text): if i != len(text) - 1: if char == " ": if text[i + 1] not in check: new.append(char) else: new.append(char) if char in check: new.append("\n\n") print("".join(new))
#!/usr/bin/python3 def new_in_list(my_list, idx, element): if idx >= 0 and idx < len(my_list): new = [] for i in my_list: new.append(i) new[idx] = element return new else: return my_list
#A program to find the canonical donor splice site candidates in an input DNA sequence dna = input('Enter a DNA Sequence: ') #A canonical donor splce site will always start with the base pair sequence GT pos = dna.find('gt', 0) while (pos>1) : print("Donor splice site at position %d"% pos) pos = dna.find('gt', pos+1)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def closestValue(self, root: TreeNode, target: float) -> int: def inorder(r: TreeNode): return inorder(r.left) + [r.val] + inorder(r.right) if r else [] return min(inorder(root), key=lambda x: abs(target - x))
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 vals = [] while l1 or l2: if l1: l1v = l1.val l1 = l1.next else: l1v = 0 if l2: l2v = l2.val l2 = l2.next else: l2v = 0 total = l1v + l2v + carry if total >= 10: total = total - 10 carry = 1 else: carry = 0 vals.append(total) if carry > 0: vals.append(carry) dummy = ListNode(0) head = dummy while len(vals) > 0: now = vals.pop(0) head.next = ListNode(now) head = head.next return dummy.next # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummyHead = ListNode(0) curr = dummyHead carry = 0 while l1 != None or l2 != None: x = l1.val if (l1 != None) else 0 y = l2.val if (l2 != None) else 0 total = carry + x + y carry = total // 10 curr.next = ListNode(total % 10) curr = curr.next if l1 != None: l1 = l1.next if l2 != None: l2 = l2.next if carry > 0: curr.next = ListNode(carry) return dummyHead.next # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummyHead = ListNode(0) curr = dummyHead carry = 0 while l1 != None or l2 != None: x = l1.val if (l1 != None) else 0 y = l2.val if (l2 != None) else 0 total = carry + x + y carry = total // 10 curr.next = ListNode(total % 10) curr = curr.next if l1 != None: l1 = l1.next if l2 != None: l2 = l2.next if carry > 0: curr.next = ListNode(carry) return dummyHead.next
#!/bin/python # Dijkstra import math import os import random import re import sys # is prime? def main(num): for i in range(2, num - 1): if num % i == 0: return False return True print(main(10)) print(main(53)) print(main(295927)) # divisor def main(num): res = [] for i in range(2, num): if i * i <= num: if num % i == 0: res.append(i) if i != num / i: res.append(num / i) return not len(res) print(main(10)) print(main(53)) print(main(295927)) # prime factorization def main(num): res = [] for i in range(2, num): if i * i <= num: while num % i == 0: num //= i res.append(i) return not len(res) print(main(10)) print(main(53)) print(main(295927))
# If the current combination is done - add it to output. # Iterate over the integers from first to n. # Add integer i into the current combination curr. # Proceed to add more integers into the combination : backtrack(i + 1, curr). # Backtrack by removing i from curr. # Approach # backtracking style class Solution: def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ def backtrack(first=1, curr=[]): # if the combination is done if len(curr) == k: output.append(curr[:]) for i in range(first, n + 1): # add i into the current combination curr.append(i) # use next integers to complete the combination backtrack(i + 1, curr) # backtrack curr.pop() output = [] backtrack() return output s = Solution() s.combine(4, 2) # Lexicographic (binary sorted) combinations # Initiate nums as a list of integers from 1 to k. Add n + 1 as a last element, it will serve as a sentinel. # Set the pointer in the beginning of the list j = 0. # While j < k : # Add the first k elements from nums into the output, i.e. all elements but the sentinel. # Find the first number in nums such that nums[j] + 1 != nums[j + 1] and increase it by one nums[j]++ to move to the next combination. # class Solution: # def combine(self, n: int, k: int) -> List[List[int]]: # # init first combination # nums = list(range(1, k + 1)) + [n + 1] # output, j = [], 0 # while j < k: # # add current combination # output.append(nums[:k]) # # increase first nums[j] by one # # if nums[j] + 1 != nums[j + 1] # j = 0 # while j < k and nums[j + 1] == nums[j] + 1: # nums[j] = j + 1 # j += 1 # nums[j] += 1 # return output
class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ if n < 2: return n # make square array i = 1 candidates = [] # initialization while i < n: candidates.append(i * i) i += 1 candidates.reverse() cnt = 0 toCheck = {n} while toCheck: cnt += 1 temp = set() for checkCandidate in toCheck: print checkCandidate for cadidate in candidates: if checkCandidate == cadidate: return cnt if checkCandidate < cadidate: break print 'checkCandidate - cadidate: ', checkCandidate - cadidate temp.add(checkCandidate - cadidate) print 'toCheck = temp: ', toCheck, temp toCheck = temp return cnt # s = Solution() # s.numSquares(12) class Solution(object): def numSquares(self, n): front, back, pm = [0], [n], 1 # pm is "plus minus" # depth[0] == 0, depth[n] == -1, depth[everythingElse] == None depth = [0] + [None] * (n - 1) + [-1] print 'front: ', front, back, pm, depth while front: newFront = [] for v in front: i = 1 while True: w = v + pm * i * i # generate a neighbor if w < 0 or w > n: # all neighbors have been generated break if depth[w] is None: # w has not been discovered # mark it as discovered by assigning a depth to it depth[w] = depth[v] + pm newFront.append(w) # w has been discovered in the `back` tree, so we're done elif (depth[w] < 0) != (depth[v] < 0): return abs(depth[w] - depth[v]) i += 1 front = newFront if len(front) > len(back): front, back, pm = back, front, -pm # always expand the tree with fewer leaves s = Solution() print s.numSquares(12) # print s.numSquares(13)
# sort-an-array class Solution(object): def sortArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ if len(nums) <= 1: return nums pivot = int(len(nums)) / 2 left = sortArray(nums[0:pivot]) right = sortArray(nums[pivot:]) return self.merge(left, right) def merge(self, left, right): left_cursor = right_cursor = 0 ret = [] while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] < right[right_cursor]: ret.append(left[left_cursor]) left_cursor += 1 else: ret.append(right[right_cursor]) right_cursor += 1 ret.extend(left[left_cursor:]) ret.extend(right[right_cursor:]) return ret
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None curr = head while curr != None: nextTemp = curr.next curr.next = prev prev = curr curr = nextTemp print(prev) return prev class Solution: def reverseList(self, head: ListNode) -> ListNode: queue = [] self.stock(head, queue) self.reverse(head, queue) return head def stock(self, h, q): if h == None: return q q.append(h.val) self.stock(h.next, q) def reverse(self, h, q): if h == None: return h h.val = q[len(q) - 1] q.pop() self.reverse(h.next, q) class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None curr = head while curr != None: nextTemp = curr.next curr.next = prev prev = curr curr = nextTemp return prev class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None: return head currentHead = head while head.next != None: p = head.next head.next = p.next p.next = currentHead currentHead = p return currentHead # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head memory = [] dummyHead = ListNode(0) dummyHead.next = head current = head while current != None: memory.append(current.val) current = current.next reversed_memory = memory[::-1] i=0 while head != None: head.val = reversed_memory[i] i+=1 head = head.next return dummyHead.next
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) # Non-recursive style # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: # if p and q does not exists # if p and q exists # if either p or q exists def check(p, q): # if both are None if not p and not q: return True # one of p and q is None if not q or not p: return False if p.val != q.val: return False return True queue = [(p, q)] while len(queue) > 0: print(queue) now = queue[0] queue.pop(0) if not check(now[0], now[1]): return False if now[0]: queue.append((now[0].left, now[1].left)) queue.append((now[0].right, now[1].right)) return True
import re from collections import Counter words = re.findall(r'\w+',open('dq.py').read().lower()) cnt = Counter() #to check count of all the words in a text for word in words: cnt[word] += 1 #check count of one given string print(cnt.items())
def merge(A:list, B:list): C = [0]*(len(A)+len(B)) i = k = n = 0 while i < len(A) and k < len(B): if A[i] <= B[k]: #устойчивость благодаря = C[n] = A[i] i+= 1 n+= 1 else: C[n] = B[k] k+= 1 n+= 1 while i < len(A): C[n] = A[i] i+= 1 n+= 1 while k < len(B): C[n] = B[k] k+= 1 n+= 1 return C def merge_sort(A): if len(A)<= 1: return middle = len(A) // 2 L = [ A[i] for i in range(0, middle)] R = [ A[i] for i in range(middle, len(A))] merge_sort(L) merge_sort(R) C = merge(L,R) #A = C[:] for i in range(len(A)): A[i] = C[i]
# a^n == a^(n-1) * a def pow1(a:float, n:int): if n == 0: return 1 elif n%2 == 1: return pow1(a, n - 1) * a else: return pow(a**2 , n//2)
from db import db """ Additional table to map the many to many relationship between Prize and Laureate Maps laureate id to prize id, with the values being a foreign key representing the id attribute in each table """ laureates = db.Table('tags', db.Column('laureate_id', db.Integer, db.ForeignKey('laureate.id')), db.Column('prize_id', db.Integer, db.ForeignKey('prize.id')) ) """ Class representing the Prize table Class variables are columns Each instance of this class is a row """ class Prize(db.Model) : id = db.Column(db.Integer, primary_key=True) category = db.Column(db.String(80)) year = db.Column(db.Integer) nr_laureates = db.Column(db.Integer) motivation = db.Column(db.String(300)) url = db.Column(db.String(200)) search_text = db.Column(db.String(500)) #Many to many relationship laureates = db.relationship('Laureate', secondary=laureates, backref=db.backref('prizes', lazy='dynamic')) # Constructor def __init__(self, category, year, nr_laureates, motivation, url): self.category = category self.year = year self.nr_laureates = nr_laureates self.motivation = motivation self.url = url def __repr__(self): return '<Prize ' + self.category + ' ' + str(self.year) + '>' """ Class representing the Laureate table Class variables are columns Each instance of this class is a row """ class Laureate(db.Model) : id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) nr_prizes = db.Column(db.Integer) date_of_birth = db.Column(db.String(10)) gender = db.Column(db.String(10)) url = db.Column(db.String(200)) search_text = db.Column(db.String(500)) #One to many relationship country_id = db.Column(db.String(2), db.ForeignKey('country.country_code')) #Constructor def __init__(self, name, nr_prizes, date_of_birth, gender, url, country_id) : self.name = name self.nr_prizes = nr_prizes self.date_of_birth = date_of_birth self.gender = gender self.url = url self.country_id = country_id def __repr__(self) : return '<Laureate %r>' % self.name """ Class representing the Country table Class variables are columns Each instance of this class is a row """ class Country(db.Model) : country_code = db.Column(db.String(2), primary_key=True) name = name = db.Column(db.String(80)) nr_laureates = db.Column(db.Integer) nr_prizes = db.Column(db.Integer) population = db.Column(db.Integer) url = db.Column(db.String(200)) search_text = db.Column(db.String(500)) #One to many relationship laureates = db.relationship('Laureate', backref='country', lazy='select') #Constructor def __init__(self, country_code, name, nr_laureates, nr_prizes, population, url) : self.country_code = country_code self.name = name self.nr_laureates = nr_laureates self.nr_prizes = nr_prizes self.population = population self.url = url def __repr__(self) : return '<Country %r>' % self.name
class Person(object) : def __init__(self,name,score) : self.name = name self.__score = score def getGrade(self) : if(self.__score >= 90) : return 'A' elif (self.__score >= 60) : return 'B' else : return 'C' if __name__ == '__main__': p1 = Person('Bob',92) p2 = Person('Alice',65) p3 = Person('Tim',45) list = [p1,p2,p3] for p in list : print p.getGrade()
###This program was written for my Ap physics 1 class, test 1 from math import sqrt print("this program calculates either the area or the perimeter of a square") diagonal = input("Input the measurement of the diagonal: ") choice = input("Do you want the area or the perimeter of a square?: ") if choice.lower() == "area": answer = (sqrt(2) * float(diagonal) / float(2)) **2 print "The area of the square with diagonal length measuring " + str(diagonal) + " meters is " + str(answer) + " meters squared" elif choice.lower() == "perimeter": answer = 4 * (float(diagonal) * sqrt(2)) print "The perimeter of the square with diagonal length measuring " + str(diagonal) + " meters is " + str(answer) + " meters"
#!/usr/bin/env python # coding: utf-8 # In[5]: #number is armstrong or not num=153 sum=0 for i in str(num): sum+=int(i)**3 print(sum) if num==sum: print(f"{num} is armstrong") else: print(f"{num} is not armstrong") # In[7]: #find LCM num=12 num2=4 maxnum=max(num,num2) while(True): if maxnum%num==0 and maxnum%num2==0: break maxnum=maxnum+1 print(f"the lcm of {num} and {num2} is {maxnum}") # In[12]: # find HCF for two number num=12 num2=4 hcf=1 maxnum=max(num,num2) for i in range(1,maxnum+1): if num%int(i)==0 and num2%int(i)==0: hcf=i print(f"the hcf of {num} and {num2} is {hcf}") # In[18]: #fibonacci series def fibonaccis(n): prenum=0 currentnum=1 for i in range(1,n): preprenum=prenum prenum=currentnum currentnum=preprenum+prenum return currentnum fibonaccis(4)
x=int(input("enter number:")) sum=0 for i in range (1,x): if(x%i==0): sum=sum+i if(sum==x): print("perfect number") else: print("not perfect")
mylist=[1,5,4,6,8,11,3,2] newlist=list(map(lambda x:x+2,mylist)) print(newlist)
row=int(input("enter number of rows:")) i=row while(i>=1): for j in range(1,i+1): print(i,end=' ') i=i-1 print()
filepath=r'Learn1\1.txt' #filepath=r'C:\Users\loeoe\Desktop\Python Codes\Learn1\1.txt' f=open(filepath, mode='r') #存储key,存在的字符有哪些 list1=[] for i in f: #print(i) for j in i: #print(j) if j not in list1: list1.append(j) print(list1)
def main(): import random import sys def start_game(): print("Welcome to the Guessing Game!") print("There is no game without risk! You will only be allowed 5 attempts and the number you are looking for is between 1 and 10. GOOD LUCK my friend!") correct_answer = random.randrange(1, 10) attempt_count = 1 while True: try: guess = int(input("Guess a number!: ")) if attempt_count >= 2: print("You have made {} attempts so far...".format(attempt_count)) if guess > 10: print("That's quite far out. Remeber, the number you are looking for is betweek 1 and 10. Try again!") if attempt_count > 5: sys.exit("oooo unlucky I'm afraid you've exceeded the 5 attempts. Better Luck next time!") if restart == "yes": main() else: exit() attempt_count += 1 if guess == int(correct_answer): print("Congratulations, {} is the right answer!!!".format(guess)) print("It took you {} attempts well done! That is the end of the game.".format(attempt_count)) restart = input("Would you like to try again? yes/no ") if restart == "yes": main() else: exit() #taken from https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=2ahUKEwjv4O6g9ariAhWlVBUIHfU9AxAQ-4ACMAB6BAgLEAY&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSZdQX4gbql0&usg=AOvVaw091tCI51bex_gv00opRwj8 elif guess > int(correct_answer): print("The correct number is lower. Try again.") continue elif guess < int(correct_answer): print("The correct number is higher. Try again.") continue #Create an argument that doesn't allow the user to select a number outside the parameters also that they cannot enter another text except ValueError: print("Error: You did not enter a number") if __name__ == '__main__': start_game() main()
n: int; abaixo: int; acima: int; entre: int lucroTotal: float; lucro_compra: float; lucro_venda: float; lucro: float; percentualLucro: float percentualLucro = acima = entre = abaixo = lucro_compra = lucro_venda = lucroTotal = 0 n = int(input('Quantos alunos serao digitados? ')) nomes: [str] = [0 for x in range(n)] precoCompra: [float] = [0 for x in range(n)] precoVenda: [float] = [0 for x in range(n)] for i in range(0, n): print(f'Produto {i+1}:') nomes[i] = input('Nome: ') precoCompra[i] = float(input('Preco de compra: R$')) precoVenda[i] = float(input('Preco de venda: R$')) for i in range(0, n): lucro = precoVenda[i] - precoCompra[i] percentualLucro = lucro * 100 / precoCompra[i] if percentualLucro < 10: abaixo += 1 elif percentualLucro <= 20: entre += 1 else: acima += 1 for i in range(0, n): lucro_compra += precoCompra[i] lucro_venda += precoVenda[i] lucroTotal = lucro_venda - lucro_compra print('RELATORIO:') print(f'Lucro abaixo de 10%: {abaixo}') print(f'Lucro entre 10% e 20%: {entre}') print(f'Lucro acima de 20%: {acima}') print(f'Valor total de compra: R${lucro_compra:.2f}')#30.00 print(f'Valor total de venda: R${lucro_venda:.2f}') #33.50 print(f'Lucro total: R${lucroTotal:.2f}')
c: float; f : float; escala: str escala = str(input('Voce vai digitar a temperatura em qual escala [C/F]? ')).upper()[0] if escala == 'F': f = float(input('Digite a temperatura em Fahrenheit: '))#75.00 c = 5 / 9 * (f - 32) print(f'Temperatura equivalente em Celsius: {c:.2f}ºC') else: c = float(input('Digite a temperatura em Celsius: ')) f = c * 9 / 5.0 + 32 print(f'Temperatura equivalente em Fahrenheit: {f:.2f}')
def calcularPotencia(base, expoente): potencia: int potencia = 1 for i in range(1, expoente+1): potencia *= base return potencia base = int(input('Informe a base: ')) expoente = int(input('Informe expoente: ')) print(f'Potencia = {calcularPotencia(base,expoente)}')
def informarSexo(s): sexo = s.upper() if sexo == 'M': return 'Masculino' elif sexo == 'F': return 'Feminino' else: return 'Inválido' sexo = str(input('Informe o sexo [M]/[F]: ').upper()[0]) print(f'O sexo é {informarSexo(sexo)}')
def converterCentimetros(m): return m * 100; metros = float(input('Informe o valor em metros: ')) print(f'Valor em centimetros {converterCentimetros(metros):.1f}cm')
def termos(n): for i in range(1, n+1): print(i) for i in range(21, 42): print(i, end=' ') return '<= Acabou' n = int(input('Informe o número de termos: ')) print(termos(n))
n: int; menor: float; maior: float; mulheres : int; homens: int; media_mulheres: float; soma_mulheres : float media_mulheres = soma_mulheres = mulheres = homens = 0 n = int(input('Quantos alunos serao digitados? ')) alturas: [float] = [0 for x in range(n)] generos : [str] = [0 for x in range(n)] for i in range(0, n): alturas[i] = float(input(f'Altura da {i + 1}ª pessoa: ')) generos[i] = str(input(f'Genero da {i + 1}ª pessoa: ').upper()[0]) menor = alturas[0] maior = alturas[0] for a in alturas: if a > maior: maior = a if a < menor: menor = a print(f'\nMenor altura = {menor:.2f}') # 1.54 print(f'Maior altura = {maior:.2f}') #1.83 for i in range(0, n): if generos[i] == 'M': homens += 1 elif generos[i] == 'F': mulheres += 1 soma_mulheres += alturas[i] media_mulheres = soma_mulheres / mulheres print(f'Media das alturas das mulheres = {media_mulheres:.2f}') # 1.69 print(f'Numero de homens = {homens}') #2
def validacaoNota(n): while 0 < n > 10: if 0 < n > 10: n = float(input('Inválido, informe novamente: ')) return 'Nota válida' nota = float(input('Informe um nota: ')) print(validacaoNota(nota)) """Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido."""
def mostrarTabuada(t): produto: int linhas = '=' * 13 print(linhas) print(f'Tabuada de {t}') print(linhas) for i in range(1, 11): produto = t * i print(f'{t} x {i} = {produto}') return linhas tabuada = int(input('Informe o número da tabuada: ')) print(mostrarTabuada(tabuada))
def consoanteVogal(l): if l == 'A' or l == 'E' or l == 'I' or l == 'O' or l == 'U': return f'A letra {l} é vogal' else: return f'A letra {l} é consoante' letra = str(input('Informe uma letra: ').upper()[0]) print(consoanteVogal(letra))
def calcularPrecoCq(q): return 1.20 * q def calcularPrecoBs(qtde): return 1.30 * qtde def calcularPrecoBo(qtde): return 1.50 * qtde def calcularPrecoHam(qtde): return 1.20 * qtde def calcularPrecoCheese(qtde): return 1.30 * qtde def calcularPrecoRefrigerante(qtde): return 1.00 * qtde def somarPrecos(calcularPrecoCq, calcularPrecoBs, precoBo, precoHamburguer, precoCheeseburguer, precoRefrigerante): return calcularPrecoCq + calcularPrecoBs + precoBo + precoHamburguer + precoCheeseburguer + precoRefrigerante linhas = '-=' * 20 print(linhas) print('Especificação Código Preço') print(linhas) print('Cachorro Quente 100 R$ 1.20') print('Bauru Simples 101 R$ 1.30') print('Bauru com ovo 102 R$ 1.50') print('Hambúrguer 103 R$ 1.20') print('Cheeseburguer 104 R$ 1.30') print('Refrigerante 105 R$ 1.00') print(linhas) valorPagar = qtde = preco = codigo = precoCq = precoBo = precoBs = precoHamburguer = precoCheeseburguer = precoRefrigerante = 0 cont = 'S' while cont == 'S': codigo = int(input('Informe o código: ')) if codigo == 100: qtde = int(input('Qual quantidade de Cachorro Quente: ')) precoCq = calcularPrecoCq(qtde) elif codigo == 101: qtde = int(input('Qual quantidade de Bauru Simples: ')) precoBs = calcularPrecoBs(qtde) elif codigo == 102: qtde = int(input('Qual quantidade Bauru com ovo: ')) precoBo = calcularPrecoBo(qtde) elif codigo == 103: qtde = int(input('Qual quantidade Hambúrguer: ')) precoHamburguer = calcularPrecoHam(qtde) elif codigo == 104: qtde = int( input('Qual quantidade Cheeseburguer: ')) precoCheeseburguer = calcularPrecoCheese(qtde) elif codigo == 105: qtde = int(input('Qual quantidade Refrigerante: ' ) ) precoRefrigerante = calcularPrecoRefrigerante( qtde ) else: print('Inválido, informe um código válido de 100 a 105: ') preco = somarPrecos(precoCq, precoBo, precoBs, precoHamburguer, precoCheeseburguer, precoRefrigerante) cont = str(input('Deseja continuar [S][N]: ').upper().strip()[0]) print(f'Valor a Pagar R${preco:.2f}')
n: int; pares: float; media_pares:float; cont: int; pares = media_pares = cont = 0 n = int(input('Quantos elementos vai ter o vetor? ')) numeros: [int] = [0 for x in range(n)] for i in range(0, n): numeros[i] = int(input(f'Digite {i + 1 }º numero: ')) for nums in numeros: if nums % 2 == 0: pares += nums cont += 1 if cont == 0: print('NENHUM NUMERO PAR') else: media_pares = pares / cont print(f'MEDIA DOS PARES = {media_pares}')
# -*- coding: utf-8 -*- """Emulator of markov algothm.""" TEMPLATE = """#!/bin/env python3 # -*- coding: utf-8 -*- from turingmarkov.markov import Algorithm from sys import stdin algo = Algorithm() """ class Algorithm: """Now supports only execution of algorithm. >>> algo = Algorithm(['aa -> a', 'bb -> b', 'cc -> c']) >>> algo.execute('aabbbcb') abcb In future, there will be debug. """ def __init__(self, rules=tuple()): """See help(type(a)).""" self.rules = [] self.last_rule = None for rule in rules: rule = rule.strip() if rule != '': self.add_rule(rule) def add_rule(self, rule): """Supported rules: `a -> b` and `a => b` (terminal rule).""" parsed_rule = None if rule.count('->') == 1 and rule.count('=>') == 0: parsed_rule = tuple(''.join(part.split()) for part in rule.split('->')) + (0,) elif rule.count('->') == 0 and rule.count('=>') == 1: parsed_rule = tuple(''.join(part.split()) for part in rule.split('=>')) + (1,) if parsed_rule is None: raise SyntaxError('Wrong format: ' + rule) else: self.rules.append(parsed_rule) def debug(self): """Now it do nothing.""" pass def execute_once(self, string): """Execute only one rule.""" for rule in self.rules: if rule[0] in string: pos = string.find(rule[0]) self.last_rule = rule return string[:pos] + rule[1] + string[pos+len(rule[0]):] self.last_rule = None return string def execute(self, string, max_tacts=None): """Execute algorithm (if max_times = None, there can be forever loop).""" counter = 0 self.last_rule = None while True: string = self.execute_once(string) if self.last_rule is None or self.last_rule[2]: break counter += 1 if max_tacts is not None and counter >= max_tacts: raise TimeoutError("algorithm hasn't been stopped") return string def compile(self): """Return python code for create and execute algo.""" result = TEMPLATE for rule in self.rules: if rule[2]: arrow = '=>' else: arrow = '->' repr_rule = repr(rule[0] + arrow + rule[1]) result += "algo.add_rule({repr_rule})\n".format(repr_rule=repr_rule) result += "for line in stdin:\n" result += " print(algo.execute(''.join(line.split())))" return result
d = {'matt', 'kim', 'joe', 'ray','mary'} # for k in d: # print (k) names = ['ray', 'rachel', 'sue', 'kim'] colors = ['red', 'green', 'blue'] d = dict(zip(names, colors)) {'kim': 'red', 'joe': 'green', 'ray': 'blue'} print (d)
from functools import reduce def betterThanAverage (classPoints, yourPoints): avg = reduce(lambda a, b: a + b, classPoints) / len(classPoints) if ( yourPoints > avg ): result = True else: result = False return result def main(): classpoints = [33, 55, 66, 77, 88, 99] betterThanAverage(classpoints, 92) if __name__ == '__main__': main()
def date(months): """ takes todays date and then calculates the date in the inputted month time :param months: :return: """ from dateutil.relativedelta import relativedelta from datetime import date date = date.today() months = relativedelta(months=months) date = date + months return date