text
stringlengths
37
1.41M
string1 = str(input()) string2 = str(input()) if string1.lower() < string2.lower(): print("-1") elif string1.lower() > string2.lower(): print("1") else: print("0")
student_heights = [180, 124, 165, 173, 189, 169, 146] total = 0 number_of_students = len(student_heights) for height in student_heights: total += height print(f"The total height for this group is {total}") average = total/number_of_students print(f"The average height for this group is {average}")
length = int(input("Largo de la lista: ")) numberList = [] while( length ): newNumber = int(input("Elemento nuevo: ")) numberList.append( newNumber ) length -= 1 print("Numeros menores a 5:") for number in numberList: if( number < 5 ): print(str(number), end=" ")
import datetime todays = datetime.datetime.now() name = input("Please enter your name: ") age = input("Please enter your age: ") age = int(age) yearsLeft = 100 - age res = todays.year + yearsLeft print("You will be 100 years old in " + str(res))
# def cortar (v) # b=v.copy() # b.pop() # b.pop(0) # print(b) # a=[1,2,3,4,5,6,7] #cortar(a) def Orden(a): c=[] c=a.sort(a) print(a) print(c) if(c!=a): print("FALSE") else: print("TRUE") def Ingresar(): a =[] b =[] while(a!="1"): a=input("Ingrese otro termino mas que desee agregar a la lista y 1 si desea salir ") b.append(a) return b p=Orden(Ingresar()) print(p) ##a =[] ##b =[] ##while(a!="1"): ## ## a=input("Ingrese otro termino mas que desee agregar a la lista y 1 si desea salir ") ## b.append(a) ## ##print(b)
import pandas as pd import os from math import * def get_spherical_distance(lat1,lat2,long1,long2): """ Get spherical distance any two points given their co-ordinates (latitude, longitude) """ # print lat1," ", lat2," ",long1," ",long2 # print type(lat1)," ", type(lat2)," ",type(long1)," ",type(long2) # print type(lat1)," ", type(lat2)," ",type(long1)," ",type(long2) # print type(long1)," ",type(long2) # print float(long1)," ",float(long2) lat1,lat2,long1,long2= float(lat1),float(lat2),float(long1),float(long2) q=radians(lat2-lat1) r=radians(long2-long1) lat2r=radians(lat2) lat1r=radians(lat1) a=sin(q/2)*sin(q/2)+cos(lat1r)*cos(lat2r)*sin(r/2)*sin(r/2) c=2*atan2(sqrt(a),sqrt(1-a)) R=6371*1000 d=R*c return d def signal(): signal1=[] signal2=[] signal=[] name='feature.csv' name2='signal/Signal_1.csv' name3='signal/Signal_2.csv' df=pd.read_csv(name) df1=pd.read_csv(name2) df2=pd.read_csv(name3) l1=len(df1) l2=len(df2) l=len(df) i=0 while i<l: signal1.append(0) signal2.append(0) i+=1 k=0 # k=int(k) while k<l1: if 'Signal' in str(df1.iloc[k]['Signal']): print(str(df1.iloc[k]['Signal'])) j=0 while j<l: if get_spherical_distance(df.iloc[j]['latitude'],df1.iloc[k]['lat'],df.iloc[j]['longitude'],df1.iloc[k]['long'])<30: if signal1[j]==0: signal1[j]=1 j+=1 print("Epoch1 Complete") k+=1 print("1 done") k=0 while k<l2: if 'Signal' in str(df2.iloc[k]['Signal']): print(str(df2.iloc[k]['Signal'])) j=0 while j<l: if get_spherical_distance(df.iloc[j]['latitude'],df2.iloc[k]['lat'],df.iloc[j]['longitude'],df2.iloc[k]['long'])<30: if signal2[j]==0: signal2[j]=1 j+=1 print("Epoch2 Complete") k+=1 z=0 while z<l: if signal1[z]==1 or signal2[z]==1: signal.append(1) else: signal.append(0) z+=1 df['Signal']=signal #df['Population_class']=population_class df.to_csv(name,index=False) def main(): #name=["details_54feet_up.csv","details_ukhra_up.csv","details_8B_up.csv","details_azone_up.csv"] #for i in name: signal() main()
#!/usr/bin/python # -*- coding: UTF-8 -*- import random name = ['万前','梁栋','张毅','李政','周煜林','谢雄鑫'] win = random.choice(name) print(f"恭喜{win}!你中了一个没有奖金的大奖!")
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 14:25:54 2021 @author: Dahire """ #LISTS[] #lists are surrounded by square brackates and oblects are separated by commas #creating a list var=['A','C','z',10,2.5,['ab','xy'],'name'] fruits=['apple','banana','guava'] cities=['raigarh','raipur','bilaspur'] #list indexing var[3] print(var[3:6])#including 3 upto 6 but not including 6 #range function in the list print(range(var)) #range only works for integer variables like below x=print(range(len(var))) for y in range(len(fruits)): #using range for counted loop print("at index",y,"in list fruit, exists",fruits[y]) for city in cities: #looping using list print("I lived in",city) #concatanation of the lists newls=fruits+cities #adds two lists subtrsction doesnot works here print(newls) #mutating the list as they are muatble newls[4]='Bhilai' print(newls) #using append to add some data to list ls=[] #an enpety list ls.append('abc') ls.append(99,200,2.33)#append takes exactly one agruement hence error ls.append(2.33) #this is correct #checking something is in the list or not 'A' in var #returns true or false 'apple' in var 'apple' not in var #sort in the list fruits.sort() cities.sort() print(cities) #other operations in the list numls=[1,3,5,23,90,100,2.2,4.6,9.9,23] print(max(numls)) print(min(numls)) print(sum(numls)) print(len(numls)) print(max(fruits)) print(min(fruits)) #splitting the string and creating the list st="write three words" stls=st.split()#splits the string from spaces print(stls) st="write;three;words" stls=st.split(';')#splits the string from ";" print(stls) #GRADED ASSIGNMENT 8.4 #QUESTION: Open the file romeo.txt and read it line by line. #For each line, split the line into a list of words using the split() method. #The program should build a list of words. #For each word on each line check to see if the word is already in the list and if not append it to the list. #When the program completes, sort and print the resulting words in alphabetical order. fname = input("Enter file name: ") fh = open(fname) ls=[] #or we can also write ls=list() for line in fh: l=line.rstrip() words=l.split() for word in words: if word not in ls: ls.append(word) ls.sort() print(ls) fh.close() #GRADED ASSIGNMENT 8.5 #Open the file mbox-short.txt and read it line by line. #When you find a line that starts with 'From ' like the following line: #"From [email protected] Sat Jan 5 09:14:16 2008" #You will parse the From line using split() and print out the second word in the line #Then print out a count at the end. fname="mbox-short.txt" fh=open(fname) count=0 for line in fh: if not line.startswith('From '): continue #print(line) l=line.rstrip() words=l.split() print(words[1]) count=count+1 print("There were", count, "lines in the file with From as the first word") fh.close()
def make_great(magicians,changes): while magicians: change = "The Great " + magicians.pop() changes.append(change) def show_magicians(magicians): for magician in magicians: print(magician) magicians = ["wang", "hu", "zhao"] changes = [] make_great(magicians, changes) show_magicians(changes) show_magicians(magicians)
"""用户类""" class User(): """存储用户的信息""" def __init__(self, first_name, last_name, gender, age): """初始化用户的属性""" self.first_name = first_name self.last_name = last_name self.gender = gender self.age = age def describe_user(self): """打印用户的信息""" print("The user's first name is " + self.first_name.title() + ", last name is " + self.last_name.title() + ", gender is " + self.gender + ", age is " + str(self.age)) def greet_user(self): """打印个性化信息""" print("Hello, " + self.first_name.title() + " " + self.last_name.title() + "!")
cats = {'mi': 'wang', 'cici': 'kun'} dogs = {'cathey': 'hu', 'eric': 'hua'} pets = [cats, dogs] for pet_owner in pets: for pet_name, owner_name in pet_owner.items(): print(pet_name.title() + ' belongs to ' + owner_name.title() + '.')
"""例题13.6角色(飞船)和球(外星人)代码""" import pygame from alien_settings_13_6 import Settings from alien_game_stats_13_6 import GameStats from alien_ship_13_6 import Ship from alien_ball_13_6 import Alien import alien_game_functions_13_6 as gf from pygame.sprite import Group def run_game(): # 初始化pygame、设置和屏幕对象 pygame.init() ai_settings = Settings() # 整个屏幕的初始设置 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # 设置屏幕的宽和高 pygame.display.set_caption("例题13-6") # 设置屏幕顶部的标题 # 创建一个用于存储游戏统计信息的实例 stats = GameStats(ai_settings) # 创建一个飞船(角色),一个外星人(球)编组 ship = Ship(ai_settings, screen) alien = Alien(ai_settings, screen) aliens = Group() aliens.add(alien) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 gf.check_events(ship) # 按键响应对飞船(角色)的位置是否移动进行设定 # 游戏处于活动状态时,才需要更新游戏元素的位置 if stats.game_active: ship.update() # 具体更新飞船(角色)的位置 # 具体更新外星人(球)的位置 gf.update_aliens(ai_settings, stats, screen, ship, aliens) # 更新屏幕上的图像,并切换到新屏幕 gf.update_screen(ai_settings, screen, ship, aliens) run_game()
# Another O(n log n) sorting mechanism # We sort by picking a pivot point to compare against import time import random # randomly picks a value to pivot def quick_sort_naive(array, debug=False, verbose=False): start = time.time() sorted_array = _quick_sort_naive(array, debug, verbose) end = time.time() if debug: print(""" Summary: Quick Sort Naive Start: {} End: {} Duration: {} """.format(start, end, end - start)) return sorted_array def _quick_sort_naive(array, debug=False, verbose=False): if len(array) <= 1: if debug and verbose and len(array) == 1: print(array) return array pivot_index = random.randint(0, len(array) - 1) pivot_value = array[pivot_index] if debug and verbose: print("Picked pivot {} at index {} from {}".format(pivot_value, pivot_index, array)) low = [] equal = [] high = [] for i in array: if i < pivot_value: low.append(i) elif i > pivot_value: high.append(i) elif i == pivot_value: equal.append(i) merged = _quick_sort_naive(low, debug) + _quick_sort_naive(equal, debug) + _quick_sort_naive(high, debug) if debug and verbose: print(merged) return merged ####################################### # picking last value in array def quick_sort_lomuto(array, debug=False, verbose=False): start = time.time() _quick_sort_lomuto(array, 0, len(array) - 1, debug, verbose) end = time.time() if debug: print(""" Summary: Quick Sort Lomuto Start: {} End: {} Duration: {} """.format(start, end, end - start)) def _quick_sort_lomuto(array, low, high, debug=False, verbose=False): if low < high: pivot_index = _partition_lomuto(array, low, high, debug, verbose) _quick_sort_lomuto(array, low, pivot_index - 1, debug, verbose) _quick_sort_lomuto(array, pivot_index + 1, high, debug, verbose) def _partition_lomuto(array, low, high, debug=False, verbose=False): pivot = array[high] pivot_index = 0 for i in range(pivot_index, high): current_value = array[i] if current_value <= pivot: array[i] = array[pivot_index] array[pivot_index] = current_value pivot_index += 1 array[high] = array[pivot_index] array[pivot_index] = pivot return pivot_index ####################################### def quick_sort_median(array, debug=False, verbose=False): start = time.time() _quick_sort_median(array, 0, len(array) - 1, debug, verbose) end = time.time() if debug: print(""" Summary: Quick Sort Median Start: {} End: {} Duration: {} """.format(start, end, end - start)) def _quick_sort_median(array, low, high, debug=False, verbose=False): if low < high: # sort low, middle and high center_index = _median_of_three(array, low, high, debug, verbose) # swap middle and high center_value = array[center_index] array[center_index] = array[high] array[high] = center_value # call lomuto sort pivot_index = _partition_lomuto(array, low, high, debug, verbose) _quick_sort_lomuto(array, low, pivot_index - 1, debug, verbose) _quick_sort_lomuto(array, pivot_index + 1, high, debug, verbose) def _median_of_three(array, low, high, debug=False, verbose=False): # return median value of three values if debug and verbose: print("Array before median swap {}".format(array)) center = int((low + high) / 2) if array[low] > array[center]: temp_value = array[center] array[center] = array[low] array[low] = temp_value if array[low] > array[high]: temp_value = array[high] array[high] = array[low] array[low] = temp_value if array[center] > array[high]: temp_value = array[high] array[high] = array[center] array[center] = temp_value if debug and verbose: print("Array before median swap {}".format(array)) return center
from .binary_tree import BinaryTree class BinarySearchTree(BinaryTree): def insert(self, value): self.root = self._insert(self.root, value) def _insert(self, node, value): if node == None: return self._create_node_for(value) if value < node.value: node.left = self._insert(node.left, value) else: node.right = self._insert(node.right, value) return node
class TrieNode(object): def __init__(self, key=None, parent=None): # value should be hashable self.key = key self.parent = parent # of TrieNode type self.children = {} # dictionary where key is key and value is node self.is_terminating = False # def __str__(self): # return "Trie { key: {}, parent: {}, children: {}, is_terminating: {}".format(key, parent.)
#Первый сценарий Python import sys #Загрузить библиотечный модуль print(sys.platform) print(2**100) #Возвести 2 в степень x="spam!" print(x*8) #Повторить строку input()
#5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. with open('hw_5_5_text.txt', "w", encoding="utf-8") as numbers_file: sum_numbers = 0 numbers = input('please insert some numbers with split \n: ') numbers_file.writelines(numbers) numbers_list = numbers.split() for i in numbers_list: sum_numbers += int(i) print(sum_numbers)
#2. Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). my_list = list(input("Пожалуйста введите X любых значений:")) print(my_list) for el in range(0, (len(my_list))//2*2, 2): my_list[el], my_list[el+1] = my_list[el+1], my_list[el] el = el + 2 print(my_list)
# Shows inventory if player inputs # 'open inventory' action import enemy as enemy import game_map as game_map inventory_list = [] def open_inventory(): print(f"""\nWhat would you like to see? Type 'quit' when finished: {inventory_list}""") prompt = 'ACTION: ' while True: key = input(prompt) if key == 'mysterious book': enemy.show_enemies() game_map.show_gamemap() elif key == 'magic spellbook': print("""\nSpecial book of spells. This book includes three spells that can be used at any point. Spells available: Flame Thrower: a spell that throws fire, doing 20 damage. Special Attack: this spell is a mystery, it does 30 damage Final Blow: it aims a powerful blow, it does 30 damage""") elif key == 'magic wand': print("""\nMagic wand, you can cast any spell you learn.""") elif key == 'magic potion': print("""\nHealing potion that heals 30 damage. Can only be used once.""") elif key == 'quit': break else: print("\nHuh? You can't do that right now.")
# Quits the game if the player inputs # 'quit game' option during the game def quit_game(): prompt = """Are you sure you want to quit? (type yes or no) """ while True: key = input(prompt) if key == 'yes': print("Quitting game...") import sys sys.exit() elif key == 'no': print("Continue gameplay...") break else: "Huh?"
"""Functions to humanize values.""" def humanize_list(value): """ Humanizes a list of values, inserting commas and "and" where appropriate. ========================= ====================== Example List Resulting string ========================= ====================== ``["a"]`` ``"a"`` ``["a", "b"]`` ``"a and b"`` ``["a", "b", "c"]`` ``"a, b and c"`` ``["a", "b", "c", "d"]`` ``"a, b, c, and d"`` ========================= ====================== """ if len(value) == 0: return "" elif len(value) == 1: return value[0] s = ", ".join(value[:-1]) if len(value) > 3: s += "," return "%s and %s" % (s, value[-1])
import os import string def rename_file(): """ the function opens specific folder, lists it, and then removes all didgits from the the file name and renames the files in our folder""" file_list = os.listdir("D:/Users/pbutkowski/Desktop/prank") saved_path = os.getcwd() os.chdir("D:/Users/pbutkowski/Desktop/prank") for file_name in file_list: translation_table = str.maketrans("0123456789", " ", "0123456789") os.rename(file_name, file_name.translate(translation_table)) os.chdir(saved_path) rename_file()
# -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame print '用字典生成DataFrame,key为列的名字。' data = {'state':['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year':[2000, 2001, 2002, 2001, 2002], 'pop':[1.5, 1.7, 3.6, 2.4, 2.9]} print DataFrame(data) print DataFrame(data, columns = ['year', 'state', 'pop']) # 指定列顺序 print print '指定索引,在列中指定不存在的列,默认数据用NaN。' frame2 = DataFrame(data, columns = ['year', 'state', 'pop', 'debt'], index = ['one', 'two', 'three', 'four', 'five']) print frame2 print frame2['state'] print frame2.year print frame2.ix['three'] frame2['debt'] = 16.5 # 修改一整列 print frame2 frame2.debt = np.arange(5) # 用numpy数组修改元素 print frame2 print
from math import pi, sin, cos, acos from FC2 import utils from FC2 import linkList class Itenerary: """This class creates the required list of dictionaries that will hold all the required values like Latitude, Longitude and the Euro conversion price for the airport""" def __init__(self): self.__airports = {} # -------- Dictionary of airports provided self.__allAirports = [] # ----- List of Dictionaries of all the airports from the DB self.__itenerary = [] # ------- List of all airports with their calculated distance and from Euro value self.__utils = utils.Utility() # Utility Object for formatted Prints self.__radiusEarth = 6371 # radius of earth in km def getIteneraryData(self,itList,allData): """This method will return a dictionary that will contain only the important fields like Lat, Lng, Eur value etc""" for key in itList[0]: # ------ Tuple's 0 position has airports and 1 position has aircraft self.__airports[key] = allData.get(key) # ----- Dictionary with required fields return self.__airports def getDistance(self,latitude1,latitude2,longitude1,longitude2): theta1 = longitude1 * (2*pi)/360 # Radians theta2 = longitude2 * (2*pi)/360 # Radians phi1 = (90-latitude1)*(2*pi)/360 # Radians phi2 = (90-latitude2)*(2*pi)/360 # Radians return acos(sin(phi1)*sin(phi2)*cos(theta1-theta2) + cos(phi1)*cos(phi2))*self.__radiusEarth def getAdjacencyGraph(self,locations): """This method will return an adjacency list of the airports graph in interest""" length = len(locations) if length<2 or length>5: self.__utils.displayErrFormatMessage('Locations are not with required range') return None else: __adjacencyList = [[]*x for x in range(len(locations))] # --- Adjaceny List that will hold adjacent vertex of the node of interest in graph for j,src in enumerate(locations): self.__linkList = linkList.LinkList() for i,dest in enumerate(locations): __linkList = [] # --- A linked list that will hold the distance of the node with source node in the adjacency list if i==j: __linkList.append(i) # --- Link list pointer to previous node. If 0 then thats the head __linkList.append(0) # --- Value in the node self.__linkList.addNode(__linkList) else: # theta1 = src[1] * (2*pi)/360 # Radians # theta2 = dest[1] * (2*pi)/360 # Radians # phi1 = (90-src[0])*(2*pi)/360 # Radians # phi2 = (90-dest[0])*(2*pi)/360 # Radians distance = self.getDistance(src[0],dest[0],src[1],dest[1]) __linkList.append(i) __linkList.append(distance) self.__linkList.addNode(__linkList) __adjacencyList[j] = self.__linkList.getList() return __adjacencyList
from FC2 import utils class LinkList: """This is representation of a linked List""" def __init__(self): self.__linkList = [] # A list to hold a node of a linked List # A node represented as a list # A node will have two values [pointer,value] # Pointer will point to the next node in the list # If pointer is 0 it is the head of the linked list self.__utils = utils.Utility() # Utility Object to display printed Messages def addNode(self,node): self.__linkList.append(node) def getNode(self,index): try: return self.__linkList[index] except IndexError as err: self.__utils.displayErrFormatMessage("Index: {}, could not be found in the list. Check the size of the list".format(index)) def getHead(self): try: return self.__linkList[0] except IndexError as err: self.__utils.displayErrFormatMessage("Head, could not be found in the list. List is empty") def getList(self): return self.__linkList def removeNode(self,node): try: self.__linkList.remove(node) except ValueError as err: self.__utils.displayErrFormatMessage("Cannot find the element: {} requested to remove".format(node)) except TypeError as err: self.__utils.displayErrFormatMessage("Provide a node to remove") def getSize(self): return len(self.__linkList)
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def __init__(self): self.stack=[] def leftMost(self,root,result): while root: self.stack.append(root) result.append(root.val) root=root.left def preorderTraversal(self, root): result=[] self.leftMost(root,result) while self.stack: temp=self.stack.pop() if temp.right: self.leftMost(temp.right,result) return result
class Solution: # @param s, a string # @return a boolean def isPalindrome(self, s): if len(s)==0 or len(s)==1: return True start,end=0,len(s)-1 while start<end: if not (s[start].isalpha() or s[start].isdigit()): start+=1 continue elif not (s[end].isalpha() or s[end].isdigit()): end-=1 continue else: temp1=s[start] temp2=s[end] if ord(s[start])<=ord('z') and ord(s[start])>=ord('a'): temp1=chr(ord(s[start])-32) if ord(s[end])<=ord('z') and ord(s[end])>=ord('a'): temp2=chr(ord(s[end])-32) if temp1==temp2: start+=1 end-=1 continue else: return False return True
# 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 inorder(self, root, ind, trange): if ind > trange[1]: trange[1] = ind if ind < trange[0]: trange[0] = ind if root.left: self.inorder(root.left, ind - 1, trange) if root.right: self.inorder(root.right, ind + 1, trange) return def BFS(self, root, mindex, res): q = collections.deque([(0, root)]) while q: n = len(q) for i in range(n): temp = q.popleft() res[temp[0] - mindex].append(temp[1].val) if temp[1].left: q.append((temp[0] - 1, temp[1].left)) if temp[1].right: q.append((temp[0] + 1, temp[1].right)) def verticalOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] trange = [0, 0] if root: self.inorder(root, 0, trange) else: return res res = [[] for i in range(trange[0], trange[1] + 1)] self.BFS(root, trange[0], res) return res
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def deleteDuplicates(self, head): before=head if head==None: return head else: after=head.next while before.next!=None: if after.val==before.val: #cancel after before.next=after.next after=before.next else: #all move forward before=before.next after=after.next return head
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a tree node def inorder_traverse(self,root,result): if root.left!=None: self.inorder_traverse(root.left,result) if result[0]!=None: if result[0].val>root.val: # problems now if result[1]==None: result[1]=result[0] result[2]=root else: result[2]=root result[0]=root #change previous node if root.right!=None: self.inorder_traverse(root.right,result) def recoverTree(self, root): if root==None: return root result=[None,None,None] #prev, first and second self.inorder_traverse(root,result) #record first and second node if result[1]!=None and result[2]!=None: result[1].val,result[2].val=result[2].val,result[1].val return root
class Solution: # @return a boolean def isInterleave(self, s1, s2, s3): if len(s1)+len(s2)!=len(s3): return False if s1=='': return s2==s3 if s2=='': return s1==s3 #now we have all non-empty set pre=[False]*(len(s1)+1) cur=[False]*(len(s1)+1) for i in range(len(s2)+1): cur=[False]*(len(s1)+1) for j in range(len(s1)+1): if i==0: #first line if j==0: cur[j]=True else: if cur[j-1]==True and s1[j-1]==s3[j-1]: cur[j]=True else: if pre[j]==True and s2[i-1]==s3[i+j-1]: cur[j]=True if j>0: if cur[j-1]==True and s1[j-1]==s3[i+j-1]: cur[j]=True pre,cur=cur,pre return pre[len(s1)]
def recur_fibo(n): if n<=1: return n else: return(recur_fibo(n-1)+recur_fibo(n-2)) nterms=20 if nterms<=0: print("please enter a positive number") else: print("fibonnaci sequence:") for i in range(nterms): print(reccur_fibo(i))
import time #? to sleep from datetime import datetime #? birthday calculation from datetime import date #? learning today import webbrowser as wb #? url opering from functools import wraps #? decorator #? getting birth date date_of_birth = datetime.strptime(input( 'Please, enter the "birthday" of whom will be celebrated by you: (dd.mm.yyyy): '), "%d.%m.%Y") #? getting name and capitalize it birthday_person = str( input('Please enter a "name" of whose birthday this is: ')).capitalize() #? calculating age of the person def calculate_age(born): today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) age = calculate_age(date_of_birth) age_sec = datetime.now() - date_of_birth #? celebration decorator def celebrator(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): w_max = "*"*150 print(f"{w_max}\t\n\t{orig_func(*args, **kwargs)}\t\n{w_max}") return wrapper #? congratulatory address for birthday @celebrator def birthday(age): w_min = "*"*10 return f"{w_min}Happy birthday, {birthday_person}! You've survived {age_sec.total_seconds()} seconds from now on. Have magnificent {age} with your loved ones{w_min}" birthday(age) # Celebration starts here... time.sleep(5) #! Thus, printed text can be read easily by everyone who is literated. #? A final countdown! for countdown in range(age, 0, -1): print(countdown) if age < 5: time.sleep(3.3) # you have more time elif 5 < age < 10: time.sleep(1.25) # when you're a child elif 10 < age < 20: time.sleep(.86) # but when you grow elif 20 < age < 30: time.sleep(.55) # older and older elif 30 < age < 50: time.sleep(.33) # time works for relativity else: time.sleep(0.11) #* and then, time flies like an arrow; fruit flies like a banana! #? Just a random funny birthday celebration song which is created by Ata Demirer the Turkish stand up comedian. url = "https://www.youtube.com/watch?v=04V7Llpn6iM" wb.open(url, new=2)
# -*- coding: utf-8 -*- """ Responsible for finding the regions of interest (subimages) on a given image. """ import cv2 import utilities as utils def find_contours(image): """ Given an image, it finds all the contours on it. Just an abstraction over cv2.findContours Parameters ---------- image : opencv image An image to be processed. Returns ------- contours : opencv contours """ if utils.CV_V3: _, contours, _ = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) else: contours, _ = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) return contours def get_contour_list(image, preprocessed, MIN_FILTER=3000): """ Given an image and its preprocessed version, returns the cropped image and its contours. The return value is in the format: [(CroppedImage, Contour)] Parameters ---------- image : opencv image The original unprocessed image preprocessed: opencv image The processed image MIN_FILTER : int Contours with an area lower than this value are discarded MAX_FILTER_PERCENT: float Contours with dimensions that exceed this percentage of the image will be discarded Returns ------- result : array of tuples """ contours = find_contours(preprocessed) #gets contours in the preprocessed image result = [] if utils.CV_V3 or utils.CV_V4: orb = cv2.ORB_create() else: orb = cv2.ORB() kp = orb.detect(image, None) for cnt in contours: c_area = cv2.contourArea(cnt) has_keypoint = any([cv2.pointPolygonTest(cnt, k.pt, False) > -1 for k in kp]) if not has_keypoint: continue if(c_area > MIN_FILTER): #FILTERING MIN SIZE if utils.DEBUG : print(cv2.contourArea(cnt)) (x,y),r = cv2.minEnclosingCircle(cnt) (x,y, r) = (int(max(r,x)), int(max(r,y)), int(r)) #FILTERING MAX SIZE #if r > MAX_FILTER_PERCENT*image.shape[1] or r > MAX_FILTER_PERCENT*image.shape[0]: #continue (y1,y2,x1,x2) = (y-r,y+r,x-r,x+r) result.append( (image[y1:y2,x1:x2], cnt) ) return result def extract(img, preproc): """ The method to be used outside this module. Takes an image and a preprocessing method, and return a list of tuples whose first position is the cropped image, and second position is the contour that generated it. Visually, it takes this format: [(CroppedImage, Contour)] Parameters ---------- img : opencv image The image to be processed. preproc : function A function that will process the image, i.e., one of the functions available in the "preprocessor" module. Returns ------- result : array of tuples """ if utils.DEBUG: utils.image_show(preproc(img)) return get_contour_list(img, preproc(img))
import matplotlib.pyplot as plt def letter_subplots(axes=None, letters=None, xoffset=-0.1, yoffset=1.0, xlabel=None, ylabel=None, **kwargs): """Add letters to the corners of subplots. By default each axis is given an upper-case bold letter label. axes: list of pyplot ax objects. letters: list of strings to use as labels, default ["A", "B", "C", ...] xoffset, yoffset: positions of each label relative to plot frame (default -0.1,1.0 = upper left margin). Can also be a list of offsets, in which case it should be the same length as the number of axes. xlabel,ylabel: (optional) add label(s) to all the axes Other arguments will be passed to plt.annotate() Examples: >>> fig, axes = plt.subplots(1,3) >>> letter_subplots(axes, letters=['(a)', '(b)', '(c)'], fontweight='normal') >>> fig, axes = plt.subplots(2,2, sharex=True, sharey=True) >>> letter_subplots(fig.axes) # fig.axes is a list when axes is a 2x2 matrix """ # handle single axes: if axes is None: axes = plt.gcf().axes try: iter(axes) except TypeError: axes = [axes] # set up letter defaults (and corresponding fontweight): fontweight = "bold" ulets = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:len(axes)]) llets = list('abcdefghijklmnopqrstuvwxyz'[:len(axes)]) if letters is None or letters == "A": letters = ulets elif letters == "(a)": letters = [ "({})".format(lett) for lett in llets ] fontweight = "normal" elif letters == "(A)": letters = [ "({})".format(lett) for lett in ulets ] fontweight = "normal" elif letters == "lower" or letters == "lowercase" or letters == "a": letters = llets # make sure there are x and y offsets for each ax in axes: if isinstance(xoffset, (int, float)): xoffset = [xoffset]*len(axes) else: assert len(xoffset) == len(axes) if isinstance(yoffset, (int, float)): yoffset = [yoffset]*len(axes) else: assert len(yoffset) == len(axes) # defaults for annotate (kwargs is second so it can overwrite these defaults): my_defaults = dict(fontweight=fontweight, fontsize='large', ha="center", va='center', xycoords='axes fraction', annotation_clip=False) kwargs = dict( list(my_defaults.items()) + list(kwargs.items())) list_txts = [] for ax,lbl,xoff,yoff in zip(axes,letters,xoffset,yoffset): if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) t = ax.annotate(lbl, xy=(xoff,yoff), **kwargs) list_txts.append(t) return list_txts
from tkinter import * from tkinter.ttk import * pantalla=Tk() pantalla.title('COVID Estados') pantalla.geometry('400x240') opcion=StringVar() etiesta=Label(pantalla,text='Estados') etiesta.place(x=170,y=10) coahuila=Radiobutton(pantalla,text='Coahuila',value='Coahuila',variable=opcion) coahuila.place(x=160,y=40) nuevoleon=Radiobutton(pantalla,text='Nuevo Leon',value='Nuevo Leon',variable=opcion) nuevoleon.place(x=160,y=60) tamaulipas=Radiobutton(pantalla,text='Tamaulipas',value='Tamaulipas',variable=opcion) tamaulipas.place(x=160,y=80) chihuahua=Radiobutton(pantalla,text='Chihuahua',value='Chihuahua',variable=opcion) chihuahua.place(x=160,y=100) sonora=Radiobutton(pantalla,text='Sonora',value='Sonora',variable=opcion) sonora.place(x=160,y=120) sinaloa=Radiobutton(pantalla,text='Sinaloa',value='Sinaloa',variable=opcion) sinaloa.place(x=160,y=140) def operacion(): buscar=opcion.get() def busquedalineal(x,y): encontrar=False posicion=0 while posicion<len(y) and not encontrar: if y[posicion]==x: encontrar=True posicion= posicion+1 return encontrar estados=['Coahuila', 'Nuevo Leon', 'Tamaulipas', 'Chihuahua', 'Sonora', 'Sinaloa'] busqueda=busquedalineal(buscar,estados) if busqueda: data={} data['Coahuila']=[] data['Coahuila'].append({'Muertes':1868, 'Recuperados':21278, 'Hospitalizados':3831}) data['Nuevo Leon']=[] data['Nuevo Leon'].append({'Muertes':3027, 'Recuperados':28585, 'Hospitalizados':7904}) data['Tamaulipas']=[] data['Tamaulipas'].append({'Muertes':2195, 'Recuperados':23256, 'Hospitalizados':4472}) data['Chihuahua']=[] data['Chihuahua'].append({'Muertes':1377, 'Recuperados':7324, 'Hospitalizados':3296}) data['Sonora']=[] data['Sonora'].append({'Muertes':2864, 'Recuperados':18082, 'Hospitalizados':5756}) data['Sinaloa']=[] data['Sinaloa'].append({'Muertes':3194, 'Recuperados':11739, 'Hospitalizados':6403}) pantalla2=Tk() pantalla2.title('COVID Estadisticas') pantalla2.geometry('400x200') archivo=open('covidprogramacion'+buscar+'.txt','w') for c in data[buscar]: eti=Label(pantalla2,text=(buscar)) eti1=Label(pantalla2,text=('Muertes:',c['Muertes'])) eti2=Label(pantalla2,text=('Recuperados:',c['Recuperados'])) eti3=Label(pantalla2,text=('Hospitalizados:',c['Hospitalizados'])) c['Muertes']=str(c['Muertes']) c['Recuperados']=str(c['Recuperados']) c['Hospitalizados']=str(c['Hospitalizados']) archivo.write(buscar) archivo.write('\n'+'Muertes: '+c['Muertes']) archivo.write('\n'+'Recuperados: '+c['Recuperados']) archivo.write('\n'+'Hospitalizados: '+c['Hospitalizados']+'\n\n') archivo.close() etia=Label(pantalla2,text='Se guardaron correctamente los datos en') etib=Label(pantalla2,text='el archivo de texto "covidprogramacion'+buscar+'.txt"') etia.place(x=85,y=150) etib.place(x=60,y=170) eti.place(x=150,y=20) eti1.place(x=150,y=60) eti2.place(x=150,y=80) eti3.place(x=150,y=100) pantalla2.mainloop() else: pantalla2=Tk() pantalla2.title('COVID Estadisticas') pantalla2.geometry('400x200') no=Label(pantalla2,text='Selecciona una opcion del menu por favor') no.place(x=88,y=80) pantalla2.mainloop() enter=Button(pantalla,text='Enter',command=operacion) enter.place(x=160,y=190) pantalla.mainloop()
an=int(input('anul = ')) an -= 2000 if an % 12 == 0: print('Este anul dragon') if an % 12 == 1: print('Este anul sarpe') if an % 12 == 2: print('Este anul cal') if an % 12 == 3: print('Este anul oaie') if an % 12 == 4: print('Este anul maimuta') if an % 12 == 5: print('Este anul cocos') if an % 12 == 6: print('Este anul caine') if an % 12 == 7: print('Este anul porc') if an % 12 == 8: print('Este anul sobolan') if an % 12 == 9: print('Este anul bou') if an % 12 == 10: print('Este anul tigru') if an % 12 > 10: print('Este anul iepure')
from typing import List class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: up, down = 1, 1 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: up = down + 1 if nums[i] < nums[i - 1]: down = up + 1 return 0 if 0 == len(nums) else max(up, down) if __name__ == "__main__": solution = Solution() result = solution.wiggleMaxLength(nums=[1, 7, 4, 9, 2, 5]) print(result)
class Solution: def longestSubstring(self, s: str, k: int) -> int: if k > len(s): return 0 for c in set(s): if s.count(c) < k: return max(self.longestSubstring(i, k) for i in s.split(c)) return len(s) if __name__ == "__main__": solution = Solution() ret = solution.longestSubstring(s = "ababbc", k = 2) print(ret)
from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: num = nums[0] count = 0 for each in nums: if count == 0: num = each count = count + 1 if each == num else count - 1 return num if __name__ == "__main__": solution = Solution() ret = solution.majorityElement(nums=[1, 2, 3, 2, 2, 2, 5, 4, 2]) print(ret)
from typing import List class Solution: def arrayPairSum(self, nums: List[int]) -> int: nums.sort() result, i = 0, len(nums) while i > 0: result += nums[i - 2] i -= 2 return result if __name__ == "__main__": solution = Solution() ret = solution.arrayPairSumK([1,2,3,4]) print(ret)
from typing import List class Solution: def generateParenthesis1(self, n: int) -> List[str]: res = [] left, right, length = 0, 0, 0 def backtrace(trace: str): nonlocal left, right, length if length == 2 * n: res.append(trace) return if right >= left and left < n: trace += '(' left += 1 length += 1 backtrace(trace) trace = trace[:-1] left -= 1 length -= 1 else: if left < n: trace += '(' left += 1 length += 1 backtrace(trace) trace = trace[:-1] left -= 1 length -= 1 if right < n: trace += ')' right += 1 length += 1 backtrace(trace) trace = trace[:-1] right -= 1 length -= 1 backtrace('') return res def generateParenthesis(self, n: int) -> List[str]: res = [] left, right, length = 0, 0, 0 def backtrace(trace: str): nonlocal left, right, length if length == 2 * n: res.append(trace) return if left < n: trace += '(' left += 1 length += 1 backtrace(trace) trace = trace[:-1] left -= 1 length -= 1 if right < left: trace += ')' right += 1 length += 1 backtrace(trace) right -= 1 length -= 1 backtrace('') return res if __name__ == "__main__": solution = Solution() ret = solution.generateParenthesis(n=3) print(ret)
"""The game of life algorithm. """ import numpy as np def compute_next_state(matrix): """Returns the next state of a matrix according to the game of life algs. Parameters ---------- matrix: array A matrix with entities 1 or 0 (live or dead) Returns ------- next_matrix: array The evoluted state. Note ---- Any live cell with fewer than two live neighbours dies. Any live cell with two or three live neighbours lives on to the next generation. Any live cell with more than three live neighbours dies. Any dead cell with exactly three live neighbours becomes a live cell. """ matrix = np.array(matrix) alive_matrix = get_alive_matrix(matrix) # For each cell, check the number of lives around itself and apply # the Conway's game of life rules. next_matrix = np.vectorize(compute_cell_next_state)(matrix, alive_matrix) return next_matrix def compute_cell_next_state(current, neighbours): """Return the next state of the cell on position (i, j) in alive_matrix. Parameters ---------- current: int The state of the cell, 1 or 0 (live or dead) neighbours: array The number of alive cells around the cell. Returns ------- new_state: int The new state of the cell, 1 or 0 (live or dead) """ new_state = 0 if current > 0: if neighbours == 2 or neighbours == 3: new_state = 1 elif neighbours == 3: new_state = 1 return new_state def get_alive_neighbours(matrix, i, j): """Returns the number of alive neighbours around the i,j cell. Parameters ---------- matrix: array A matrix with entities 1 or 0 (live or dead) i: int Number of rows of the main cell of interest. j: int Number of column of the main cell of interest. Returns ------- nalive: int The number of alive cells around cell of interest. """ # Get slicers which capture a 3x3 matrix around the main cell if i-1 < 0: slice_i_min = 0 else: slice_i_min = i-1 if i+1 > len(matrix)-1: slice_i_max = len(matrix)-1+1 else: slice_i_max = i+1+1 if j-1 < 0: slice_j_min = 0 else: slice_j_min = j-1 if j+1 > len(matrix[i])-1: slice_j_max = len(matrix[i])-1+1 else: slice_j_max = j+1+1 sliced_matrix = matrix[slice_i_min:slice_i_max, slice_j_min:slice_j_max] # Count the number of entities that are non zero (alive) nalive = np.count_nonzero(sliced_matrix) # uncount our cell of interest: if matrix[i][j] > 0: nalive -= 1 return nalive def get_alive_matrix(matrix): """Returns a matrix with number of lives around each cell. Parameters ---------- matrix: array A matrix with entities 1 or 0 (live or dead) Returns ------- alive_matrix: array The number of alive cells around each cell. """ alive_matrix = np.zeros_like(matrix) for i in range(len(matrix)): for j in range(len(matrix[i])): alive_matrix[i][j] = get_alive_neighbours(matrix, i, j) return alive_matrix def mutation(matrix, mutation_rate): """Mutate the population Parameters ---------- matrix: array A matrix with entities 1 or 0 (live or dead) mutation_rate: float A float from 0 to 1. The chance that a cell would flip. This applies after each evolution. Returns ------- matrix: array The mutated matrix. """ random_binomial = np.random.binomial(1, mutation_rate, np.shape(matrix)) return np.bitwise_xor(matrix, random_binomial)
def password_gen(): import random uppers = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') lowers = list('abcdefghijklmnopqrstuvwxyz') digits = list('1234567890') password = uppers.pop(random.randint(0, len(uppers)-1)) password += lowers.pop(random.randint(0, len(lowers)-1)) password += digits.pop(random.randint(0, len(digits)-1)) remaining = uppers + lowers + digits for i in range(random.randint(3, 17)): password += remaining.pop(random.randint(0, len(remaining)-1)) return password
import time numeropar=0 multiplo3=0 menu="si" while menu =="si": numeropar=int(input("Dime un Nº:\n")) if numeropar%2==0: multiplo3=numeropar print ("PAR") time.sleep (1) else: print ("IMPAR") time.sleep (1) if multiplo3%3==0: print ("Multiplo de 3") time.sleep (1) else: print ("No es multiplo de 3") time.sleep (1) menu=input("¿Quieres continuar? (si o no)\n") if menu != "si": print ("hasta luego")
from typing import List from cryptoxlib.Pair import Pair def map_pair(pair: Pair) -> str: return f"{pair.base}-{pair.quote}" def map_multiple_pairs(pairs : List[Pair], sort = False) -> List[str]: pairs = [pair.base + "-" + pair.quote for pair in pairs] if sort: return sorted(pairs) else: return pairs
#! /usr/bin/env python3 # First notice we are importing the fuctions from the "collections" class. # We need to do this to gain access to the functions. They are not part of # the default name space. from collections import OrderedDict, defaultdict, deque, Counter, namedtuple from datetime import datetime, timedelta # An ordered dictionary will keep the order of insertion when # called in a loop. A regular dictionary may or may not follow # the order of insertion. if True: norm_dict = dict() norm_dict["a"] = 1 norm_dict["b"] = 2 norm_dict["c"] = 3 norm_dict["d"] = 4 ord_dict = OrderedDict() ord_dict["one"] = 1 ord_dict["two"] = 2 ord_dict["three"] = 3 ord_dict["four"] = 4 for key, value in norm_dict.items(): print(key, value) for key, value in ord_dict.items(): print(key, value) # A default dictionary will allow setting a default value for any # new entry. This includes when the key does not exist. So when # the dictionary is called without a key it is added to the dictionary # with the default value as the value. if False: # Create the default dictionary and use lambda to set the default # value to use if created with no value. ice_cream = defaultdict(lambda: "Vanilla") ice_cream["Sarah"] = "Chunky Monkey" ice_cream["Abdul"] = "Butter Pecan" print("ice_cream.keys():", ice_cream.keys()) print('ice_cream["Sarah"]:', ice_cream["Sarah"]) print('ice_cream["Joe"]:', ice_cream["Joe"]) # Using a default dictionary with the int as the default # will start at 0. Using increment notation will add a number # to the default of 0 or the value if one is set. This allows # using a dictionary as a counter of items. if False: from collections import defaultdict food_list = "spam spam spam spam spam spam eggs spam".split() food_count = defaultdict(int) # default value of int is 0 print('food_count:', food_count) for food in food_list: food_count[food] += 1 # increment element's value by 1 print(food_count) # Using a default dictionary with a list of tuples allows adding a # city to a state without needing to define all states initially. if False: from collections import defaultdict city_list = [ ("TX", "Austin"), ("TX", "Houston"), ("NY", "Albany"), ("NY", "Syracuse"), ("NY", "Buffalo"), ("NY", "Rochester"), ("TX", "Dallas"), ("CA", "Sacramento"), ("CA", "Palo Alto"), ("GA", "Atlanta"), ] cities_by_state = defaultdict(list) print('cities_by_state:', cities_by_state) for state, city in city_list: # The .append() method is adding the city name to the end # of the list stored in a dictionary with the state name as the key. cities_by_state[state].append(city) for state, cities in cities_by_state.items(): print(state, ", ".join(cities)) # deques are much faster at prepending than lists. They also allow faster # removal of first element. They are helpful when adding and removing to # both front and end of a list of items. if False: num = 200000 list_a = list() deque_b = deque() start_datetime = datetime.now() for ii in range(num): list_a.insert(0, ii) diff = datetime(1970, 1, 1, 0, 0, 0) + timedelta( seconds=(datetime.now() - start_datetime).seconds) print("list elapsed time for prepending {} values: ".format(num) + diff.strftime("%H:%M:%S"), "\n") start_datetime = datetime.now() for ii in range(num): deque_b.appendleft(ii) diff = datetime(1970, 1, 1, 0, 0, 0) + timedelta( seconds=(datetime.now() - start_datetime).seconds) print("deque elapsed time for prepending {} values: ".format(num) + diff.strftime("%H:%M:%S"), "\n") start_datetime = datetime.now() while len(list_a) > 0: list_a.pop(0) diff = datetime(1970, 1, 1, 0, 0, 0) + timedelta( seconds=(datetime.now() - start_datetime).seconds) print("list elapsed time for poping first element of {} values: ".format(num) + diff.strftime("%H:%M:%S"), "\n") start_datetime = datetime.now() while len(deque_b) > 0: deque_b.popleft() diff = datetime(1970, 1, 1, 0, 0, 0) + timedelta( seconds=(datetime.now() - start_datetime).seconds) print("deque elapsed time for poping first element of {} values: ".format(num) + diff.strftime("%H:%M:%S"), "\n") # A tuple stores information by index number. A named tuple stores information # by a name for each piece of information. if False: # Create the new named tuple with the named keys. Person = namedtuple("Person", "name age gender") bob = Person(name="Bob", age=30, gender="male") print("\nRepresentation:", bob) jane = Person(name="Jane", age=29, gender="female") print("\nField by name:", jane.name) print("\nFields by name:") for p in [bob, jane]: print("{} is a {} year old {}".format(p.name, p.age, p.gender)) # A counter is a container that keeps track of how many times values are added. # The standard use is with letters. if False: # There are three ways to initialize a counter object list_counter = Counter(['a', 'b', 'c', 'a', 'b', 'b']) dict_counter = Counter({'a':2, 'b':3, 'c':1}) keyword_couner = Counter(a=2, b=3, c=1) # Can creaet an empty counter and then update with a second call. # This looks a little strange with the input being a single string, # but the update expects a list object. If a string is entered it # will automatically convert to a list. When Python converts a single # sting to a list all the charactrs are separated into individual # elements. Go ahead and try print(list('abcabb')). empty_counter = Counter() empty_counter.update('abcabb') for counter_element in [list_counter, dict_counter, keyword_couner, empty_counter]: print(counter_element) # As new data is added the couner is updated. empty_counter.update(['a', 'd']) print('\nUpdated counter:', empty_counter) if False: # But we can also use the counter on full words. # Start off with a sentence. my_str = "This this this is really really good." print('myStr:', my_str) # Next split the single string of a sentence into a list of words # by splitting at white spaces. The .split() method assumes whitespace # if no delimiter is provided. my_list = my_str.split() print('my_str:', my_str) # Now use the list of words as input into the Counter. It will # return a dictionary with the words as keys and values as number # of times that word is counted. Notice how the count is case sensitive. my_dict = Counter(my_list) print('myDict:', my_dict) # To remove case sensitive counter just lower the calse of all characters # befor entering into the Counter() my_lower_case_list = [ii.lower() for ii in my_list] my_lower_case_dict = Counter(my_lower_case_list) print('my_lower_case_dict:', my_lower_case_dict) if False: # A counter will also work with numbers other objects. my_numbers = [0, 1, 2, 3, 4, 4, 4, 55, 67, 67, 10242425242552] number_dict = Counter(my_numbers) print('number_dict:', number_dict) # To just see the n number of most common use the .most_common() method. # Notice how the type is different. It is no longer a dictionary but a # list of tuples. This is important when you want to extract the values # and use them. They will be extracted with different syntax. print('number_dict.most_common(2):', number_dict.most_common(2)) # convert to a regular dictionary number_dict_most_common_as_dict = dict(number_dict.most_common(2)) print('number_dict_most_common_as_dict:', number_dict_most_common_as_dict) # Here is a list of the more common patterns used with Counters() total = sum(number_dict.values()) # total of all counts print('total:', total) # list unique elements or "keys" if that is easier to understand number_dict_list = list(number_dict) print('number_dict_list:', number_dict_list) # Reset all counts, or essentially just make number_dict set to None number_dict = number_dict.clear() print('number_dict:', number_dict) if False: # Counters have the ability to perform mathematical operations from within # the Counter object. c = Counter(Tom=3, Jerry=1) d = Counter(Tom=1, Jerry=2, Scooby=4) c_plud_d = c + d # add two counters together: c[x] + d[x] c_minus_d = c - d # subtract (keeping only positive counts) c_intersect_d = c & d # intersection: min(c[x], d[x]) c_union_d = c | d # union: max(c[x], d[x]) print('c_plud_d:', c_plud_d) print('c_minus_d:', c_minus_d) print('c_intersect_d:', c_intersect_d) print('c_union_d:', c_union_d)
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """Template file for python 3 script""" # import os # import sys import argparse # import datetime def main(): """[docstring/purpose of this script]""" args=parse_arguments() print("Required arg: ",args.requiredArg) if args.optionalArg : print("Optional: ",args.optionalArg) if args.secondOptionalArg : print("2nd Optional: ",args.secondOptionalArg) increment_number(args.secondOptionalArg) def increment_number(n): try: n=n+1 print("Incremented: ",n) except TypeError: print("Can't add to %s" % (type(n))) def parse_arguments(): """Configure and return command line arguments""" parser = argparse.ArgumentParser( description="A description for this script", epilog="An epilog for the help" ) parser.add_argument("requiredArg") parser.add_argument("-o", "--optionalArg", default='', help='This is an optional argument' ) parser.add_argument("-s", "--secondOptionalArg", default=0, type=int, help="""This is an optional argparse that requires an int""" ) parser.add_argument("-b", "--booleanFlag", action='store_true', help="""True when passed, defaults to false""") args = parser.parse_args() return args if __name__ == '__main__': main()
"""dumb json to jina2 template renderer """ import argparse import jinja2 import json import sys def render(data, template): """render jija2 template Args: data(obj): dict with data to pass to jinja2 template template(str): jinja2 template to use Returns: string, rendered all, or pukes with error :) """ with open(template, 'r'): templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) template = templateEnv.get_template(template) outputText = template.render(data=data) return outputText def run(): """ Parses arguments and runs the script """ epilog = """ Example usage: Use stdin and stdout: cat examples/test.json | python render.py -t templates/test.j2 | sort Use specific files for input and output: python render.py -i examples/test.json -t templates/test.j2 -o output/test2.txt """ parser = argparse.ArgumentParser( epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-i", "--input", help='input json file, can be multiline json from stdin or file', type=argparse.FileType('r'), default=sys.stdin, ) parser.add_argument( "-t", "--template", help='Jinja2 template to use to render the output', default='templates/plaintext.j2', ) parser.add_argument( "-o", "--output", nargs='?', help='Where to pass rendered output default stdout', type=argparse.FileType('w'), default=sys.stdout, ) args = parser.parse_args() js_input = args.input template = args.template output = args.output # read json input data = json.load(js_input) # render template rendered = render(data, template) # write out the rendered output output.write(rendered) if __name__ == '__main__': run()
''' The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after growth cycles? For example, if the number of growth cycles is , the calculations are as follows: Period Height 0 1 1 2 2 3 3 6 4 7 5 14 Function Description Complete the utopianTree function in the editor below. It should return the integer height of the tree after the input number of growth cycles. utopianTree has the following parameter(s): n: an integer, the number of growth cycles to simulate Input Format The first line contains an integer, , the number of test cases. subsequent lines each contain an integer, , denoting the number of cycles for that test case. Constraints Output Format For each test case, print the height of the Utopian Tree after cycles. Each height must be printed on a new line. Sample Input 3 0 1 4 Sample Output 1 2 7 ''' import math import os import random import re import sys # Complete the utopianTree function below. def utopianTree(n): return print(((2 << (n >> 1)) - 1) << (n & 1)) if __name__ == '__main__': t = int(input()) for t_itr in range(t): n = int(input()) result = utopianTree(n)
import tkinter as tk import numpy as np import math from tkinter import * class game (): def __init__ (self, WindowW = 1000, WindowH = 800): self.Window = Tk() self.WindowW = WindowW self.WindowH = WindowH self.initWindow() def initWindow(self): self.CarW = 30.0 self.CarH = 40.0 self.CarDiagonal = math.sqrt(pow(self.CarW, 2) + pow(self.CarH, 2))/2 self.carRotation = 0 self.SensorW = self.CarW / 5.0 self.SensorH = self.CarH / 5.0 self.SensorDiagonal = math.sqrt(pow(self.SensorH, 2) + pow(self.SensorW, 2))/2 self.sensorPosition = [] self.TargetW = 10.0 self.targetPosition = [] self.ObstacleW = 6.0 self.obstaclePosition = [] self.Window.title('DQN_Car') self.canvas = Canvas(self.Window, bg = 'white', width = self.WindowW, height = self.WindowH) print('WindowW:', self.WindowW, 'WindowH:', self.WindowH) self.initCar() self.initButton() self.canvas.pack() self.Window.mainloop() def initCar(self): self.carPosition = [self.CarW/2, self.CarH/2] self.carWidgetEvent = self.canvas.create_polygon((self.carPosition[0] - self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW)), self.carPosition[1] - self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW)), \ self.carPosition[0] + self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW)), self.carPosition[1] - self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW)), \ self.carPosition[0] + self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW)), self.carPosition[1] + self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW)), \ self.carPosition[0] - self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW)), self.carPosition[1] + self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW))),\ fill = 'blue') print('CarPosX:', self.carPosition[0], 'CarPosY:', self.carPosition[1]) self.initSensors(self.carPosition) def initButton(self): self.placeObstacleButton = Button(self.Window, text = 'Place obstacle', command = self.placeObstacle) self.placeObstacleButton.pack(side = BOTTOM)#放置障碍物按钮 self.placeTargetButton = Button(self.Window, text = 'Place target', command = self.placeTarget) self.placeTargetButton.pack(side = BOTTOM)#放置目标点的按钮 self.placeForwardButton = Button(self.Window, text = 'Forward', command = self.goForward) self.placeForwardButton.pack(side = RIGHT) self.placeRotateButton = Button(self.Window, text='Rotate', command=self.Rotate) self.placeRotateButton.pack(side=RIGHT) self.resetButton = Button(self.Window, text = 'RESET', command = self.reset) self.resetButton.pack(side = BOTTOM)#重置 self.runButton = Button(self.Window, text = 'RUN', command = self.run) self.runButton.pack(side = BOTTOM)#运行按钮 def placeObstacle(self): try : self.Window.unbind('<B1-Motion>', self.mousePressEvent) except : pass self.mouseMotionEvent = self.Window.bind(sequence = '<B1-Motion>', func = self.processMouseEvent) def processMouseEvent(self, MOUSE): self.obstacleWidgetEvent = self.canvas.create_rectangle(MOUSE.x - self.ObstacleW/2, \ MOUSE.y - self.ObstacleW/2, \ MOUSE.x + self.ObstacleW/2, \ MOUSE.y + self.ObstacleW/2, \ fill = '#9D9D9D') self.obstaclePosition.append([MOUSE.x, MOUSE.y]) print('Obstacle placed at :', self.obstaclePosition[len(self.obstaclePosition) - 1]) def placeTarget(self): try: self.Window.unbind('<B1-Motion>', self.mouseMotionEvent) except : pass try: self.canvas.delete(self.targetWidgetEvent) except AttributeError: pass self.mousePressEvent = self.Window.bind(sequence = '<Button-1>', func = self.processPlaceTargetEvent) def processPlaceTargetEvent(self, MOUSE): self.targetWidgetEvent = self.canvas.create_rectangle(MOUSE.x - self.TargetW/2, \ MOUSE.y - self.TargetW/2, \ MOUSE.x + self.TargetW/2, \ MOUSE.y + self.TargetW/2, \ fill='#FFDC35') self.targetPosition = ([MOUSE.x, MOUSE.y]) print('Target placed at :', self.targetPosition) self.Window.unbind('<Button-1>', self.mousePressEvent) def initSensors(self, carPosition): sensor1Position = [carPosition[0], carPosition[1] + self.CarH*2/5] #the front sensor2Position = [carPosition[0] - self.CarW*2/5, carPosition[1]] #left sensor3Position = [carPosition[0], carPosition[1] - self.CarH*2/5] #after end sensor4Position = [carPosition[0] + self.CarW*2/5, carPosition[1]] #right self.sensor1WidgetEvent = self.canvas.create_polygon((sensor1Position[0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor1Position[1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor1Position[0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor1Position[1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor1Position[0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor1Position[1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor1Position[0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor1Position[1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW))), \ fill = 'white')#the front self.sensor2WidgetEvent = self.canvas.create_polygon((sensor2Position[0] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor2Position[1] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor2Position[0] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor2Position[1] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor2Position[0] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor2Position[1] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor2Position[0] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor2Position[1] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW))), \ fill = 'green')#left self.sensor3WidgetEvent = self.canvas.create_polygon((sensor3Position[0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor3Position[1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor3Position[0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor3Position[1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor3Position[0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor3Position[1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), \ sensor3Position[0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), sensor3Position[1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW))), \ fill = 'red')#after end self.sensor4WidgetEvent = self.canvas.create_polygon((sensor4Position[0] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor4Position[1] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor4Position[0] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor4Position[1] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor4Position[0] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor4Position[1] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW)), \ sensor4Position[0] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW)), sensor4Position[1] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW))), \ fill = '#FF8EFF')#right self.sensorPosition = ([sensor1Position, sensor2Position, sensor3Position, sensor4Position]) print('Sensor position :\n', self.sensorPosition) def moveCarWidget(self, velocity, rotation): rotation = rotation/180 * math.pi self.carRotation += rotation self.carPosition[0] += velocity*math.cos(self.carRotation) self.carPosition[1] += velocity*math.sin(self.carRotation) self.sensorPosition[0][0] += velocity * math.cos(self.carRotation) - self.CarH*2/5*math.sin(self.carRotation) self.sensorPosition[1][0] += velocity * math.cos(self.carRotation) self.sensorPosition[2][0] += velocity * math.cos(self.carRotation) self.sensorPosition[3][0] += velocity * math.cos(self.carRotation) self.sensorPosition[0][1] += velocity * math.sin(self.carRotation) - self.CarH*2/5*(1 - math.cos(self.carRotation)) self.sensorPosition[1][1] += velocity * math.sin(self.carRotation) self.sensorPosition[2][1] += velocity * math.sin(self.carRotation) self.sensorPosition[3][1] += velocity * math.sin(self.carRotation) #move self.canvas.move(self.carWidgetEvent, velocity*math.cos(self.carRotation), \ velocity*math.cos(self.carRotation)) self.canvas.move(self.sensor1WidgetEvent, velocity * math.cos(self.carRotation) - self.CarH*2/5*math.sin(self.carRotation), \ velocity * math.cos(self.carRotation) - self.CarH*2/5*(1 - math.cos(self.carRotation))) self.canvas.move(self.sensor2WidgetEvent, velocity * math.cos(self.carRotation) , \ velocity * math.cos(self.carRotation)) self.canvas.move(self.sensor3WidgetEvent, velocity * math.cos(self.carRotation), \ velocity * math.cos(self.carRotation)) self.canvas.move(self.sensor4WidgetEvent, velocity * math.cos(self.carRotation), \ velocity * math.cos(self.carRotation)) #rotation self.canvas.coords(self.carWidgetEvent, self.carPosition[0] - self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW) + self.carRotation), self.carPosition[1] - self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW) + self.carRotation), \ self.carPosition[0] + self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW) - self.carRotation), self.carPosition[1] - self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW) - self.carRotation), \ self.carPosition[0] + self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW) + self.carRotation), self.carPosition[1] + self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW) + self.carRotation), \ self.carPosition[0] - self.CarDiagonal*math.cos(math.atan(self.CarH/self.CarW) - self.carRotation), self.carPosition[1] + self.CarDiagonal*math.sin(math.atan(self.CarH/self.CarW) - self.carRotation)) self.canvas.coords(self.sensor1WidgetEvent, self.sensorPosition[0][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[0][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[0][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[0][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation)), \ self.sensorPosition[0][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[0][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[0][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[0][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation))) self.canvas.coords(self.sensor2WidgetEvent, self.sensorPosition[1][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[1][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[1][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[1][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation)), \ self.sensorPosition[1][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[1][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[1][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[1][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation))) self.canvas.coords(self.sensor3WidgetEvent, self.sensorPosition[2][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[2][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[2][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[2][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation)), \ self.sensorPosition[2][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[2][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[2][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[2][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation))) self.canvas.coords(self.sensor4WidgetEvent, self.sensorPosition[3][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[3][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[3][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[3][1] - self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation)), \ self.sensorPosition[3][0] + self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW - self.carRotation)), self.sensorPosition[3][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW - self.carRotation)), \ self.sensorPosition[3][0] - self.SensorDiagonal*math.sin(math.atan(self.SensorH/self.SensorW + self.carRotation)), self.sensorPosition[3][1] + self.SensorDiagonal*math.cos(math.atan(self.SensorH/self.SensorW + self.carRotation))) def goForward(self): self.moveCarWidget(10, 0) def Rotate(self): self.moveCarWidget(0, 10) # def moveCar(self, action, velocity, rotation): # # if action == 'forward':#x:+, y:+ # self.moveCarWidget() # # # elif action == 'backward':#x:-, y:- # self.canvas.move() # # elif action == 'left':#x:+, y:- # self.canvas.move() # # elif action == 'right':#x:-, y:+ # self.canvas.move() def reset(self): self.canvas.delete('all') self.carPosition = [] self.obstaclePosition = [] self.targetPosition = [] self.sensorPosition = [] self.initCar() print('CarPositionList :', self.carPosition, '\n' 'ObstaclePositionList :', self.obstaclePosition, '\n' 'TargetPositionList :', self.targetPosition, '\n') print('GAME RESTART') def run(self): print('GAME BEGINS') # def main(): # tk = Tk() # canvas = Canvas(tk, width = 1000, height = 800) #设置画布 # canvas.pack() #显示画布 # def moveCar(event): # 绑定方向键 # if event.keysym == "Up": # canvas.move(1,0,-5) # 移动的是 ID为1的事物【move(2,0,-5)则移动ID为2的事物】,使得横坐标加0,纵坐标减5 # elif event.keysym == "Down": # canvas.move(1,0,5) # elif event.keysym == "Left": # canvas.move(1,-5,0) # elif event.keysym == "Right": # canvas.move(1,5,0) # '事件ID可能跟程序的先后顺序有关,例如,下面先创建了200*200的矩形,后创建了20*20的矩形' # r = canvas.create_rectangle(180,180,220,220,fill="red") # 事件ID为1 # print(r) #打印ID验证一下 # m = canvas.create_rectangle(10,10,20,20,fill="blue") #事件ID为2 # print(m) #打印ID验证一下 # canvas.bind_all("<KeyPress-Up>",moverectangle) #绑定方向键与函数 # canvas.bind_all("<KeyPress-Down>",moverectangle) # canvas.bind_all("<KeyPress-Left>",moverectangle) # canvas.bind_all("<KeyPress-Right>",moverectangle) # tk.mainloop() if __name__ == '__main__': game = game()
##输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。 ##输入一个int型整数 ##按照从右向左的阅读顺序,返回一个不含重复数字的新的整数 ###!/usr/bin/python ### -*- coding: UTF-8 -*- ## ##str = "-"; ##seq = ("a", "b", "c"); # 字符串序列 ##print str.join( seq ); ##a-b-c a = input() b = [] for i in a[::-1]: if i not in b: b.append(i) print(''.join(b))
sum = 0 for i in range (101): if i%2 == 0 : sum += i print(sum)
str_in1 = 'abcdefyux' #input("输入字符串1:") str_in2 = 'abcrdeqyux' #input("输入字符串2:") str_out = "1" str_list = [] length = 0 longest_list = [] last_statioin = -1 for i in str_in1: if str_in2.find(i) >= 0 : if str_in2.find(i) != last_statioin + 1 : str_list.append(str_out[1:]) str_out = "1" last_statioin = str_in2.find(i) str_out += i if i == str_in1[len(str_in1)-1] and str_out != "1": str_list.append(str_out[1:]) str_out = "1" for j in str_list: if len(j) >= length: length = len(j) for k in str_list: if length == len(k): longest_list.append(k) print(" ".join(longest_list))
##int() 函数用于将一个字符串或数字转换为整型。 ##class int(x, base=10), 默认x为10进制数据,转换成10进制整形数据 ##int(x, base=16),认为输入是16进制数据,将其转化为10进制整形 print( int(input(), base=16))
def factorial_using_for_loop(num): fact = 1 if num < 0: print("Not possible") return -1 elif num == 0: return 1 else: for i in range(1, num+1): fact *= i return fact print(factorial_using_for_loop(0))
#Initially create a DataBase in MySQL #Create a table with AccNo,Name,Deposit,Withdraw #Give a AccNo,Name, Deposit,Withdraw for Initials #Next follow below process #Note: Transaction is a table name in database import mysql.connector import sys #BANK DETAILS; class Bank: def __init__(self): self.bankname="STATE BANK OF INDIA" connection=mysql.connector.connect(user="manu317",password="manu317@ROBOT",host="127.0.0.1",database="Bank") def deposit(self,amt): try: connection=mysql.connector.connect(user="manu317",password="manu317@ROBOT",host="127.0.0.1",database="Bank") x=input("Enter your ACCOUNT NUMBER as per your account :") query2="select * from Transactions where ID='{}'".format(x) c=connection.cursor() c.execute(query2) record=c.fetchall() #print(record[0][2]) self.deposited=record[0][2] self.deposited+=amt query3="update Transactions set Deposit={} where ID='{}'".format(self.deposited,x) c.execute(query3) connection.commit() print("Your Account Balance is:",self.deposited) except Exception as msg: print("Exception:",msg) def withdraw(self,amt): try: connection=mysql.connector.connect(user="manu317",password="manu317@ROBOT",host="127.0.0.1",database="Bank") x=input("Enter your ACCOUNT NUMBER as per your account :") query2="select * from Transactions where ID='{}'".format(x) c=connection.cursor() c.execute(query2) record=c.fetchall() #print(record[0][2]) self.deposited=record[0][2] if self.deposited>amt: self.deposited-=amt print("Collect Cash") print("Your Balance is:",self.deposited) print("Thank you") query3="update Transactions set Withdraw={} where ID='{}'".format(self.deposited,x) query4="update Transactions set Deposit={} where ID='{}'".format(self.deposited,x) c.execute(query3) c.execute(query4) connection.commit() else: print("Sorry,insufficient Balance") sys.exit() except Exception as msg: print("Exception:",msg) def BalanceEnquiry(self): connection=mysql.connector.connect(user="manu317",password="manu317@ROBOT",host="127.0.0.1",database="Bank") x=input("Enter your ACCOUNT NUMBER as per your account :") query2="select * from Transactions where ID='{}'".format(x) c=connection.cursor() c.execute(query2) record=c.fetchall() print("Your Balance is:",record[0][3]) class CustomerGuidance: def main(): print("Press-1 for Deposit") print("Press-2 for WithDraw") print("Press-3 for BalanceEnquiry") x=int(input("Enter a number to Withdraw or Deposit or BalanceEnquiry")) if x==1: b=Bank() amt=float(input("Enter amount to Deposit")) b.deposit(amt) elif x==2: b=Bank() amt=float(input("Enter amount to WithDraw")) b.withdraw(amt) elif x==3: b=Bank() b.BalanceEnquiry() b=Bank() print("Welcome to",b.bankname) CustomerGuidance.main()
# -*- coding: utf-8 -*- ''' 4、编写程序,完成以下要求: 提示用户进行输入数据 获取用户的数据数据(需要获取2个) 对获取的两个数字进行求和运行,并输出相应的结果 ''' import re def add(l): return int(l[0]) + int(l[1]) a = input('请输入两个数字,用逗号或空格隔开:') if re.match(r'^(\d*)([\s\,\;]+)(\d*)$', a): al = re.split(r'[\s\,\;]+', a) if len(al) != 2: print('输入不合法,输入两个数字') else: print('结果是 %d:' % add(al)) else: print('输入不合法')
""" 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 """ def isPalindrome(x): """ :type x: int :rtype: bool """ l = list(str(x)) l.reverse() n = ''.join(l) return str(n) == str(x) # 高级做法 # str(x)[::-1] == str(x) print(isPalindrome(78987))
class StringFmt: def __init__(self, append_zero=False, char_sz=1, to_lower=False, to_upper=False): self._append_zero = append_zero self._char_sz = char_sz self._to_lower = to_lower self._to_upper = to_upper def format(self, s): zero_char = "\x00" * self._char_sz if self._to_lower: s = s.lower() if self._to_upper: s = s.upper() if self._char_sz == 2: wcs = "" for x in s: wcs += "%s\x00" % x s = wcs if self._append_zero: s += zero_char return s
#!/usr/bin/env python3 filename = input('Enter file path:') try: f = open(filename) print(f.read()) f.close() except FileNotFoundError as err: print('Erro: {0}'.format(err))
#!/usr/bin/env python ''' Created on 12/20/14 @author: EI ''' # Written by Tim Ioannidis Mar 12 2015 for HJK Group # Dpt of Chemical Engineering, MIT ########################################################## ######## Defines class of 3D molecules that ############# ######## will be used to manipulate ############# ######## coordinates within RDkit ############# ########################################################## from math import sqrt def distance(R1,R2): dx = R1[0] - R2[0] dy = R1[1] - R2[1] dz = R1[2] - R2[2] d = sqrt(dx**2+dy**2+dz**2) return d class mol3D: """ Class mol3D represents a molecule with its coordinates for easy manipulation in 3D space """ def __init__(self): """ Create a new molecule object """ self.atoms = [] self.natoms = 0 self.mass = 0 self.size = 0 def coords(self): ss = '' # initialize returning string ss += "%d \n\n" % self.natoms for atom in self.atoms: xyz = atom.coords() ss += "%s \t%f\t%f\t%f\n" % (atom.sym,xyz[0],xyz[1],xyz[2]) return ss def addatom(self,atom): # adds new atom self.atoms.append(atom) self.natoms += 1 self.mass += atom.mass self.size = self.molsize() def deleteatom(self,atomIdx): self.mass -= self.GetAtom(atomIdx).mass self.natoms -= 1 for i in range(atomIdx,self.natoms): self.atoms[i] = self.atoms[i+1] def translate(self,dxyz): # translates molecules by dx,dy,dz for atom in self.atoms: atom.translate(dxyz) def GetAtom(self,idx): return self.atoms[idx] def GetAtoms(self): return self.atoms def centermass(self): # calculates center of mass of molecule # initialize center of mass and mol mass pmc = [0, 0, 0] mmass = 0 # loop over atoms in molecule for atom in self.atoms: # calculate center of mass (relative weight according to atomic mass) xyz = atom.coords() pmc[0] += xyz[0]*atom.mass pmc[1] += xyz[1]*atom.mass pmc[2] += xyz[2]*atom.mass mmass += atom.mass # normalize pmc[0] /= mmass pmc[1] /= mmass pmc[2] /= mmass return pmc def distance(self,mol): # gets distance between 2 molecules (centers of mass) cm0 = self.centermass() cm1 = mol.centermass() pmc = distance(cm0,cm1) return pmc def alignmol(self,mol,atom1,atom2): ''' aligns molecule 2(mol) based on atoms 1 and 2 ''' # get vector of distance between atoms 1,2 dv = atom2.distancev(atom1) # align molecule self.translate(dv) def molsize(self): # calculates maximum distance between center of mass and atoms maxd = 0 cm = self.centermass() for atom in self.atoms: if distance(cm,atom.coords()) > maxd: maxd = distance(cm,atom.coords()) return maxd def combine(self,mol): cmol = self '''combines 2 molecules in self''' for atom in mol.atoms: cmol.addatom(atom) return cmol def overlapcheck(self,mol,silence): # checks for overlap with another molecule overlap = False for atom1 in mol.atoms: for atom0 in self.atoms: if (distance(atom1.coords(),atom0.coords()) < atom1.rad + atom0.rad): overlap = True if not (silence): print "#############################################################" print "!!!Molecules might be overlapping. Increase distance!!!" print "#############################################################" break return overlap def mindist(self,mol): # checks for overlap with another molecule mind = 1000 for atom1 in mol.atoms: for atom0 in self.atoms: if (distance(atom1.coords(),atom0.coords()) < mind): mind = distance(atom1.coords(),atom0.coords()) return mind def maxdist(self,mol): # checks for overlap with another molecule maxd = 0 for atom1 in mol.atoms: for atom0 in self.atoms: if (distance(atom1.coords(),atom0.coords()) > maxd): maxd = distance(atom1.coords(),atom0.coords()) return maxd def writexyz(self,filename): ''' writes xyz file for self molecule''' ss = '' # initialize returning string ss += "%d \nXYZ structure generated by mol3D Class, rdklol\n" % self.natoms for atom in self.atoms: xyz = atom.coords() ss += "%s \t%f\t%f\t%f\n" % (atom.sym,xyz[0],xyz[1],xyz[2]) fname = filename.split('.xyz')[0] f=open(fname+'.xyz','w') f.write(ss) f.close() def writemxyz(self,mol,filename): ''' writes xyz file for 2 molecules''' ss = '' # initialize returning string ss += "%d \nXYZ structure generated by mol3D Class, rdklol\n" % (self.natoms+mol.natoms) for atom in self.atoms: xyz = atom.coords() ss += "%s \t%f\t%f\t%f\n" % (atom.sym,xyz[0],xyz[1],xyz[2]) for atom in mol.atoms: xyz = atom.coords() ss += "%s \t%f\t%f\t%f\n" % (atom.sym,xyz[0],xyz[1],xyz[2]) fname = filename.split('.xyz')[0] f=open(fname+'.xyz','w') f.write(ss) f.close() def __repr__(self): """ when calls mol3D object without attribute e.g. t """ ss = "\nClass mol3D has the following methods:\n" for method in dir(self): if callable(getattr(self, method)): ss += method +'\n' return ss
""" Title: "Special sum" function Name: Ayan A. Date: 21/07/2021 Description: A function that performs a special sum of its elements. It follows the following logic - if array equals this [5, 2, [7, -1], 3, [6, [-13, 8], 4]] for instance, then the output of the function is equal to 5 + 2 + 2 * (7 – 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4). Contents of an array inside an array are multiplied by 2. Contents of an array inside an array inside an array are multiplied by 3, and so on. """ from typing import Generator def special_sum(special_array: list, depth: int = 1): integers: Generator = (element for element in special_array if isinstance(element, int)) arrays: Generator = (element for element in special_array if isinstance(element, list)) return depth * (sum(integers) + sum(special_sum(special_array=element, depth = depth + 1) for element in arrays))
import csv import sqlite3 def create_csv(j): conn = sqlite3.connect('example.db') conn.text_factory = str cur = conn.cursor() data = cur.execute("SELECT * FROM nmea"+str(j)) with open('file'+str(j)+'.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['time', 'latitude', 'north\south','longtitude','east\west','quality','nos','hdop','altitude','hog','speed','date']) writer.writerows(data)
""" Description: This is a simple program to create a class precende list. We used the simple topological sorting algorithm which uses stacks to create the list. The only change we made is that the original algorithm considers all the nodes in the graph to order them. In our program we only start with a single node given as input and navigate through its vertices and their vertices and so on. We learned the topological sorting algorithm from our CS-202 Fundamental Structures of Computer Science course at Bilkent. We use adjency list to represent the graph. The adjency list is created using Python dictionaries. Authors: Umer Shamaan Taha Khurram Hassan Raza Muhammad Ali Khaqan """ #creating the adjacency list for part 1 adjList_dict = {} adjList_dict["ifstream"] = ["istream"] adjList_dict["istream"] = ["ios"] adjList_dict["fstream"] = ["iostream"] adjList_dict["iostream"] = ["istream", "ostream"] adjList_dict["ostream"] = ["ios"] adjList_dict["ofstream"] = ["ostream"] adjList_dict["ios"] = [] #creating the adjacency list for part 2 adjList_dict2 = {} adjList_dict2["Consultant Manager"] = ["Consultant", "Manager"] adjList_dict2["Director"] = ["Manager"] adjList_dict2["Permanent Manager"] = ["Manager", "Permanent Employee"] adjList_dict2["Consultant"] = ["Temporary Employee"] adjList_dict2["Manager"] = ["Employee"] adjList_dict2["Temporary Employee"] = ["Employee"] adjList_dict2["Permanent Employee"] = ["Employee"] adjList_dict2["Employee"] = [] #creating the adjacency list for part 3 adjList_dict3 = {} adjList_dict3["Crazy"] = ["Professors", "Hackers"] adjList_dict3["Jacque"] = ["Weightlifters", "Shotputters", "Athletes"] adjList_dict3["Professors"] = ["Eccentrics", "Teachers"] adjList_dict3["Hackers"] = ["Eccentrics", "Programmers"] adjList_dict3["Weightlifters"] = ["Athletes", "Endomorpha"] adjList_dict3["Shotputters"] = ["Athletes", "Endomorpha"] adjList_dict3["Eccentrics"] = ["Dwarfs"] adjList_dict3["Teachers"] = ["Dwarfs"] adjList_dict3["Programmers"] = ["Dwarfs"] adjList_dict3["Athletes"] = ["Dwarfs"] adjList_dict3["Endomorpha"] = ["Dwarfs"] adjList_dict3["Dwarfs"] = ["Everything"] adjList_dict3["Everything"] = [] #Used to check if all vertices adjacent to the vertex on the top of the stack (node) have been visited or not def allVisited(node, visited, adjList_dict): toCheck = adjList_dict[node] temp = len(toCheck) for i in range(0,temp): if not toCheck[i] in visited: return False return True #returns an unvisietd node adjacent to the node given as arguement def selectUnvisited(node, visited, adjList_dict): toCheck = adjList_dict[node] temp = len(toCheck) for i in range(0, temp): if not toCheck[i] in visited: return toCheck[i] else: return #the altered version of a basic topological sorting algorithm to create the class precedency list def topSort(adjList_dict, Node): my_stack = [] #the stack visited = [] #The list of nodes visited PList = [] #The precedence List my_stack.append(Node) #pushing in the child node for which the precedence list is being calculated while my_stack: if allVisited(my_stack[-1], visited, adjList_dict): #if all vertices adjacent to node at the top of the stack have been visited PList.insert(0, my_stack.pop()) else: node = selectUnvisited(my_stack[-1], visited, adjList_dict) #select an unvisited node adjacent to the node at the top of stack my_stack.append(node) visited.append(node) return PList #main starts here print("Part 1:") print("Computing the precedency list for ifstream:") print(topSort(adjList_dict, "ifstream")) print("Computing the precedency list for fstream:") print(topSort(adjList_dict, "fstream")) print("Computing the precedency list for ofstream:") print(topSort(adjList_dict, "ofstream")) print("\n--------------------------------------------------\n") print("Part 2:") print("Computing the precedency list for Consultant Manager:") print(topSort(adjList_dict2, "Consultant Manager")) print("Computing the precedency list for Director:") print(topSort(adjList_dict2, "Director")) print("Computing the precedency list for Permanent Manager:") print(topSort(adjList_dict2, "Permanent Manager")) print("\n--------------------------------------------------\n") print("Part 3:") print("Computing the precedency list for Crazy:") print(topSort(adjList_dict3, "Crazy")) print("Computing the precedency list for Jacque:") print(topSort(adjList_dict3, "Jacque"))
## 日付・時間 import datetime lvm ='*'*20 ##3.1 日付の取得 today = datetime.date.today() todaydetail = datetime.datetime.today() print(lvm) print(today) print(todaydetail) print(lvm) print(today.year) print(today.month) print(today.day) print(todaydetail.year) print(todaydetail.month) print(todaydetail.day) print(todaydetail.minute) print(todaydetail.second) print(todaydetail.microsecond) print(lvm) print(today.isoformat()) print(todaydetail.strftime("%Y%m%d %H:%M:%S")) ##3.2 日付の計算 today = datetime.datetime.today() print(today) print(today + datetime.timedelta(days=1)) newyear = datetime.datetime(2021,1,1) print(newyear + datetime.timedelta(days=7)) calc = newyear-today print(calc.days) ##3.3 閏年の判定 import calendar print(calendar.isleap(2015)) print(calendar.isleap(2016)) print(calendar.isleap(2017)) print(calendar.leapdays(2010,2020))
import redis # HostAddress=str(input()) # Port=int(input())#输入测试 # 建立连接 HostAddress = "127.0.0.1" Port = 6379 r = redis.Redis(host=HostAddress, port=Port, db=0) # 指定0号数据库 # redis-py 使用 connection pool 来管理对一个 redis server 的所有连接,避免每次建立、释放连接的开销。 # 默认,每个Redis实例都会维护一个自己的连接池。 # 可以直接建立一个连接池,然后作为参数 Redis,这样就可以实现多个 Redis 实例共享一个连接池。 pool = redis.ConnectionPool(host=HostAddress, port=Port, decode_responses=True) r = redis.Redis(connection_pool=pool) r1 = redis.StrictRedis(host=HostAddress, port=Port) # 这是主要的redis方法,redis.Redis是它的子类 # 数据库基础操作 # 查看所有键值 print(r.keys()) # 所有键 # 查看所有键 for i in r.keys(): print(r.type(i)) # 获得键值的类型 r.expire(i, 10) # 设置过期时间 print(r.ttl(i)) # 获得过期时间 r.rename(i, 'hello' + i) # 重命名 r.move(i, 1) # 转移到指定数据库 r.delete(i) # 根据键删除键值对 r.flushdb() # 删除当前数据库 r.flushall() # 删除所有数据库 # 普通键值对操作 ##set key/value r.set(1, 2) # ex是过期时间 r.set("12", "Hello") # get key print(r.get(1)) r.incr(1, 20) # 对key1自增20 r.incrbyfloat(1, 20.1) # 自增浮点型数据 # r.decr(1,1)#自减操作,这里如果这么写会有bug,是因为被转化成字符串型 r.append("12", "World") # 对字符型value增加 # list类型操作 r.rpush('list1', 1, 2, 32, 3, 4) # 插入列表,可以在表尾插入多个元素 r.lpush('list1', 1, 2, 32, 3, 4) # 插入列表,可以在表头插入多个元素 r.lset('list1', 1, 100) # 设置值 r.lrem('list1', num=1, value=2) # 删除1个值为2 listRedis = r.lrange('list1', 0, -1) # 根据范围获得列表 print(listRedis) # set类型 r.sadd("set1", 1, 2, 3, 4) # 往集合里增加元素 r.sadd("set2", 2, 3, 5) # 往集合里增加元素 setRedis = r.smembers('set1') # 获得所有元素 print(setRedis) r.srem('set1', 1) # 删除值为1的元素 r.smove('set1', 'dst', 2) # 把2从第一个集合移动到第二个集合 diffset = r.sdiff('set1', 'set2') # 求差集 print(diffset) interset = r.sinter('set1', 'set2') # 求交集 print(interset) unionset = r.sunion('set1', 'set2') # 求并集 print(unionset) # zset比set多了一个元素权值的选项 # hash数据操作,hash类似与dict r.hset("hash1", "k1", "v1") r.hset("hash1", "k2", "v2") # 添加hash散列 print(r.hkeys("hash1")) # 取hash中所有的key print(r.hvals('hash1')) # 获得所有value print(r.hget("hash1", "k1")) # 单个取hash的key对应的值 hashdict=r.hgetall('hash1')#获得该hash表 print(hashdict) r.hdel("hash1", "k1") # 删除一个键值对 r.hincrby("hash1", 'k1', amount=1) # 自增
""" DFS in Python A / \ \ B C D / / F E """ class Tree(object): def __init__(self, name='root', children=None): self.name = name self.children = [] if children is not None: for child in children: self.add_child(child) def __repr__(self): return self.name def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) tree = Tree('A', [Tree('B'), Tree('C', [Tree('F')]), Tree('D', [Tree('E')])]) def DFS(tree, node): print(tree) if tree.name == node: print(f'found node: {node} in {tree}') return tree for child in tree.children: print(child) if child.name == node: print(f'found node: {node} in {child}') return child if child.children: print(f'attempt searching {child} for {node}') match = DFS(child, node) if match: print(match) return match result = DFS(tree, 'E') print("Result:",result) ############################################################################# """ DFS with Stack and Adjacency Metrix """ def dfs_iterative(graph, start): stack, path = [start], [] while stack: vertex = stack.pop() if vertex in path: continue path.append(vertex) for neighbor in graph[vertex]: stack.append(neighbor) return path adjacency_matrix = {1: [2, 3], 2: [4, 5], 3: [5], 4: [6], 5: [6], 6: [7], 7: []} print(dfs_iterative(adjacency_matrix, 1))
import argparse def get_args(): p = argparse.ArgumentParser() p.add_argument("-i", "--input", type=str) p.add_argument("-o", "--output", type=str) return p.parse_args() args = get_args() def sort(array): for i in range(1, len(array)): k = i while k > 0 and array[k] < array[k-1]: array[k], array[k-1] = array[k-1], array[k] k -= 1 return array def get_array(input): out = [] with open(input, 'r') as fi: ln = 0 for line in fi: ln += 1 if ln == 2: out.extend(map(int, line.split())) return out values = get_array(args.input) def merge(a,b): out = [] a, b = sort(a), sort(b) #print(a,b) while a and b: if a[0] <= b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out.extend(a+b) #print(out) return out def divide(values): a = len(values) midpoint = a // 2 b = values[midpoint:] c = values[:midpoint] if len(b) + len(c) > 5: b = divide(b) c = divide(c) #print(b,c) return merge(b,c) sorted_values = divide(values) print(*sorted_values) with open(args.output, 'w') as fo: fo.write(*sorted_values) out = '' for a in sorted_values: out = out + str(a) + ' ' fo.write(out) print(out)
#!/usr/bin/env python def main(): with open('rosalind_hamm.txt', 'r') as doc: sequence = doc.read().split('\n') Hamming_distance = 0 for a in range(len(sequence[0])): if sequence[0][a] != sequence[1][a]: Hamming_distance += 1 print(Hamming_distance) if __name__ == "__main__": main()
from __future__ import print_function import os # Start of program def main(): file = open(SelectFile("prog.txt"), 'r') # Opens the file asm = file.readlines() # Gets a list of every line in file program = [] # Whats this? list for line in asm: # For every line in the asm file if line.count('#'): line = list(line) line[line.index('#'):-1] = '' line = ''.join(line) # Removes empty lines from the file if line[0] == '\n': continue line = line.replace('\n', '') # If user entered a Hex file if line.count("0x"): line = ConvertHexToBin(line) instr = line[0:] program.append(instr) # We SHALL start the simulation! # machineCode = machineTranslation(program) # Translates the english assembly code to machine code sim(program) # Starts the assembly simulation with the assembly program machine code as # FUNCTION: read input file # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: Ask user to enter the file name. If user press enter the applicaiton will take the default file. def SelectFile(defaultFile): script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in # Select file, default is prog.asm while True: cktFile = defaultFile print("\nRead asm file: use " + cktFile + "?" + " Enter to accept or type filename: ") userInput = input() if userInput == "": userInput = defaultFile return userInput else: cktFile = os.path.join(script_dir, userInput) if not os.path.isfile(cktFile): print("File does not exist. \n") else: return userInput # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: Translates the assembly to machine code and stores it back in program [] def machineTranslation(program): PC = 0 # Used to end the while loop instructionList = {'addi': 1000} # Stores the opcodes of all our assembly instructions machineCode = [] # Stores the final binary data while (PC < len(program)): # Goes through all the instructions in the program instruction = program[PC] # Sets instruction to the current instruction we are translating # This keeps track of where the opcode ends (Because there would be a space there) spaceLocation = 0 for char in instruction: if char == ' ': # print("Space location at " + str(spaceLocation)) break else: spaceLocation += 1 # Below code translates the english opcode to binary and checks for errors opcode = instruction[0:spaceLocation] # Grabs the english string of the opcode binaryOpcode = instructionList.get(opcode) # Replaces the english text opcode with the binary one if binaryOpcode == None: # Gives error if the opcode is not supported by instructionList (for debuging purposes) print("Instruction not implemented, please check!") print("Error instruction '" + opcode + "' not supported.") quit() # Grabs the english data for the 2 bits after the opcode and translates it to binary rx = instruction[spaceLocation + 2:spaceLocation + 3] # Grabs the next two bits as an english string binaryRx = "{0:2b}".format(int(rx)) # Converts to binary # Grabs the english data for the last 2 bits and translates it to binary ry = instruction[spaceLocation + 5:] # Grabs the rest of the data as a english string NOTE: ry can also be imm binaryRy = "{0:2b}".format(int(ry)) # Adds all the binary data into machineCode. NOTE: The data has spaces which need to be fixed by the for loop machineCode.append(str(binaryOpcode) + str(binaryRx) + str(binaryRy)) incompleteMachineCode = machineCode[PC] # This machine code will have spaces in it which will be fixed completeMachineCode = '' # This will contain the fixed machineCode for char in incompleteMachineCode: if char == ' ': char = '0' else: pass completeMachineCode += char print("The complete machine code for the instruction is " + completeMachineCode) machineCode[PC] = completeMachineCode # The correct final binary value is now in machineCode machineCode.append(0) # since PC increment by every cycle, machineCode.append(0) # let's align the program code by every 1 line machineCode.append(0) PC += 4 # Used to end the while loop print("The machine code for the program is ") print(machineCode) return machineCode # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: TBD def sim(program): finished = False # Is the simulation finished? PC = 0 # Program Counter register = [0] * 4 # Let's initialize 4 empty registers mem = [0] * 12288 # Let's initialize 0x3000 or 12288 spaces in memory. I know this is inefficient... # But my machine has 16GB of RAM, its ok :) DIC = 0 # Dynamic Instr Count while (not (finished)): instruction = "" instrDescription = "" if PC == len(program): finished = True if PC > len(program) and PC < len(program): break try: fetch = program[PC] except: break DIC += 1 # HERES WHERE THE INSTRUCTIONS GO! # ----------------------------------------------------------------------------------------------- addi if fetch[0:4] == '1000': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx imm = int(fetch[6:], 2) # Reads the immediate register[rx] = register[rx] + imm if register[rx] > 255: # Overflow support register[rx] = register[rx] - 255 - 1 # print out the updates instruction = "addi $" + str(rx) + ", " + str(imm) instrDescription = "Register " + str(rx) + " is now added by " + str(imm) # ----------------------------------------------------------------------------------------------- init elif fetch[0:2] == '00': # Reads the Opcode PC += 1 rx = int(fetch[2:4], 2) # Reads the next two bits which is rx imm = int(fetch[4:], 2) # Reads the immediate register[rx] = imm # print out the updates instruction = "init $" + str(rx) + ", " + str(imm) instrDescription = "Register " + str(rx) + " is now equal to " + str(imm) # ----------------------------------------------------------------------------------------------- subi elif fetch[0:4] == '0111': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx ry = int(fetch[6:], 2) # Reads the immediate register[rx] = register[rx] - ry if register[rx] <= 0: # Underflow support register[rx] = 255 - abs(register[rx] + 1) # print out the updates instruction = "sub $" + str(rx) + ", $" + str(ry) instrDescription = "Register " + str(rx) + " is now subtracted by " + str(ry) # ----------------------------------------------------------------------------------------------- bnezR0 elif fetch[0:4] == '1011': # Reads the Opcode imm = fetch[4:] # Reads the immediate if imm[0] == 0: imm = int(imm[1:4], 2) else: imm = int(imm[1:4], 2) * (-1) if register[0] != 0: PC = PC + imm else: PC += 1 # print out the updates instruction = "bezR0 " + str(imm) instrDescription = "Instruction number" + str(PC / 1) + " will run next " # ----------------------------------------------------------------------------------------------- end elif fetch[0:8] == '11111111': # Reads the Opcode instruction = "end " instrDescription = "The program stopped!! " break # ----------------------------------------------------------------------------------------------- jmp #elif fetch[0:4] == '0101': # Reads the Opcode #imm = fetch[4:] # Reads the immediate #if imm[0] == 0: #imm = int(imm[1:4], 2) #else: #imm = int(imm[1:4], 2) * (-1) #PC = PC + imm # print out the updates #instruction = "jmp " + str(imm) #instrDescription = "Instruction number" + str(PC / 1) + " will run next " # ----------------------------------------------------------------------------------------------- eq elif fetch[0:4] == '0110': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx ry = int(fetch[6:], 2) # Reads the immediate if register[rx] == register[ry]: register[rx] = 1 instrDescription = "Register " + str(rx) + " is equal to " + str(register[ry]) + ". Register " + str( rx) + " is now equal to 1." else: register[rx] = 0 instrDescription = "Register " + str(rx) + " is not equal to " + str( register[ry]) + ". Register " + str(rx) + " is now equal to 0." # print out the updates instruction = "eq $" + str(rx) + ", $" + str(ry) # ----------------------------------------------------------------------------------------------- sb elif fetch[0:4] == '1001': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx ry = int(fetch[6:], 2) # Reads the immediate mem[register[ry]] = register[rx] # print out the updates instruction = "sb $" + str(rx) + ", $" + str(ry) instrDescription = "Memory address " + str(register[ry]) + " is now equal to " + str(register[rx]) # ----------------------------------------------------------------------------------------------- minc (memory increment) elif fetch[0:4] == '1010': PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx imm = int(fetch[6:], 2) # Reads the immediate mem[register[rx]] += imm # ----------------------------------------------------------------------------------------------- hash elif fetch[0:4] == '1100': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next two bits which is rx ry = int(fetch[6:8], 2) # Reads the next two bits which is ry A = register[rx] B = register[ry] instrDescription = "Register " + str(rx) + " is now equal to hash of " + str(A) + " and " + str(B) for i in range(1, 6): C = bin(A * B).replace("0b", "") a = len(C) - 8 lo = C[a:].zfill(8) hi = C[0:a].zfill(8) xor = int(hi, 2) ^ int(lo, 2) A = xor A = bin(A).replace("0b", "").zfill(8) lo = A[4:].zfill(4) hi = A[0:4].zfill(4) C = int(hi, 2) ^ int(lo, 2) C = bin(C).replace("0b", "").zfill(4) lo = C[2:].zfill(2) hi = C[0:2].zfill(2) C = int(hi, 2) ^ int(lo, 2) register[rx] = C instruction = "hash $" + str(rx) + ", $" + str(ry) # ----------------------------------------------------------------------------------------------- saal elif fetch[0:4] == '1101': # Reads the Opcode PC += 1 rx = int(fetch[4:5], 2) # Reads the next bit which is rx (Either r0 or r1) imm = int(fetch[5:], 2) # Reads the immediate (3 bits) mem[255 + imm] = register[rx] # print out the updates instruction = "sb $" + str(rx) + ", $" + str(255 + imm) instrDescription = "Memory address " + str(255 + imm) + " is now equal to " + str(register[rx]) # ----------------------------------------------------------------------------------------------- cpy elif fetch[0:4] == '1110': # Reads the Opcode PC += 1 rx = int(fetch[4:6], 2) # Reads the next bit which is rx ry = int(fetch[6:], 2) # Reads the register ry register[rx] = register[ry] # print out the update instruction = "cpy $" + str(rx) + ", $" + str(ry) instrDescription = "Register " + str(rx) + "is now set to the value of register " + str(ry) else: # This is not implemented on purpose print('Not implemented\n') PC += 1 printInfo(register, DIC, mem[0:260], PC, instruction, instrDescription) # Finished simulations. Let's print out some stats print('***Simulation finished***\n') printInfo(register, DIC, mem[0:260], PC, instruction, instrDescription) #input() # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: to print out each instruction line is running with its updates def printInfo(_register, _DIC, _mem, _PC, instr, instrDes): num = int(_PC / 1) print('******* Instruction Number ' + str(num) + '. ' + instr + ' : *********\n') print(instrDes) print('\nRegisters $0- $4 \n', _register) print('\nDynamic Instr Count ', _DIC) print('\nMemory contents 0xff - 0x64 ', _mem) print('\nPC = ', _PC) print('\nPress enter to continue.......') #input() # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: Convert line from hex into bin def ConvertHexToBin(_line): # remove 0x then convert. _line.replace("0x", "") _line = str(bin(int(_line, 16)).zfill(8)) _line = _line.replace("0b", "") return _line # -------------------------------------------------------------------------------------------------------------------- # # ---- FUNCTION: Convert the hex into int in an asm instruction. ex: lw $t, offset($s) converts offset to int. def ConvertHexToInt(_line): i = "" for item in _line: if "0x" in item: ind = _line.index(item) if "(" in item: i = item.find("(") i = item[i:] item = item.replace(i, "") item = str(int(item, 0)) item = item + i _line[ind] = item return _line if __name__ == '__main__': main()
# Enter your code here. Read input from STDIN. Print output to STDOUT def compareList(sumArray,a,n): if(n == 1): return True sumFirstHalf = a[0] for z in xrange(1,n-1): sumSecondHalf = sumArray - sumFirstHalf - a[z] if(sumFirstHalf == sumSecondHalf): return True sumFirstHalf+=a[z] return False if __name__ == "__main__": Tests = int(raw_input().strip()) for x in xrange(0,Tests): n=int(raw_input().strip()) a= [int(y) for y in raw_input().strip().split() ] sumArray = sum(a) if(compareList(sumArray,a,n)): print "YES" else: print "NO"
def partition(array, lo, hi): pivot_index = hi pivot_value = array[pivot_index] store_index = lo for i in range(lo, hi): if array[i] <= pivot_value: array[i], array[store_index] = array[store_index], array[i] store_index += 1 array[pivot_index], array[store_index] = array[store_index], array[pivot_index] return store_index def quicksort(array, lo, hi): if lo < hi: p = partition(array, lo, hi) print(' '.join([str(i) for i in array])) quicksort(array, lo, p-1) quicksort(array, p+1, hi) if __name__ == '__main__': size = int(input()) ar = [int(i) for i in raw_input().strip().split()] quicksort(ar, 0, size-1)
''' # Function to read data from excel file # and create derived dataframe for insertion into the database ''' # %% import pandas as pd def read_angle_data(input_excel): # read complete excel file xls = pd.ExcelFile(input_excel) #xls = pd.ExcelFile('Angle_violation.xlsm') # get date from file name temp_list= input_excel.split('_')[2:] temp_list[-1]=temp_list[-1].split('.')[0] temp_list=temp_list[::-1] print(temp_list) dat='-'.join(temp_list) print("Date in called function: {0}".format(dat)) # read excel sheet final one df1 = pd.read_excel(xls, 'Final', skiprows=6, skipfooter=6) wide = ['wide', 'wide','wide', 'wide','wide', 'wide','wide', 'wide','wide', 'wide','wide'] df1['Type'] = wide df1['Unnamed: 0'] = dat # read data for adjacent angle df2 = pd.read_excel(xls, 'Final', skiprows=19, skipfooter=1) adj = ['adj','adj','adj'] df2['Type'] = adj df2['Unnamed: 0'] = dat # rename a column df1.rename(columns={'Unnamed: 0': 'Date'}, inplace=True) df2.rename(columns={'Unnamed: 0': 'Date'}, inplace=True) # drop a column df1 = df1.drop("Sr. No.", axis=1) df2 = df2.drop("Sr. No.", axis=1) return df1, df2 # %%
import matplotlib.pyplot as plt import math import random def plot_points(points, ax=None, style={'marker': 'o', 'color':'b'}, label=False): """plots a set of points, with optional arguments for axes and style""" if ax==None: ax = plt.gca() for ind, p in enumerate(points): ax.plot(p.real, p.imag, **style) if label: ax.text(p.real, p.imag, s=ind, horizontalalignment='center', verticalalignment='center') ax.set_xlim(-1.1, 1.1) ax.set_ylim(-1.1, 1.1) def create_circle_points(n): """creates a list of n points on a circle of radius one""" return [math.cos(2 * math.pi * i / float(n)) + 1j * math.sin(2 * math.pi * i / float(n)) for i in range(n)] def create_point_cloud(n): return [2 * random.random() - 1 + 1j * (2 * random.random() - 1) for _ in range(n//2)] + [1 * random.random() - 1 + 1j * (1 * random.random() - 1) for _ in range(n//2)] def distance(A, B): return abs(A - B) def incremental_farthest_search(points, k): remaining_points = points[:] solution_set = [] solution_set.append(remaining_points.pop(random.randint(0, len(remaining_points) - 1))) for _ in range(k-1): distances = [distance(p, solution_set[0]) for p in remaining_points] for i, p in enumerate(remaining_points): #i下标,p元素 for j, s in enumerate(solution_set): distances[i] = min(distances[i], distance(p, s)) solution_set.append(remaining_points.pop(distances.index(max(distances)))) return solution_set def fps(points,k): remaining_points = points[:] solution_set = [] distances = [] distance_s = [] solution_set.append(remaining_points.pop(random.randint(0, len(remaining_points) - 1))) for _ in range(k-1): for i,p in enumerate(remaining_points): for j,s in enumerate(solution_set): # print(distance(p,s)) distance_s.append(distance(p,s)) distances.append(sum(distance_s)) # print("sum = " + str(sum(distance_s))) distance_s = [] solution_set.append(remaining_points.pop(distances.index(max(distances)))) distances = [] # print(len(remaining_points),len(solution_set)) return solution_set #TODO: function distance fig = plt.figure(figsize=(5, 5)) circle100 = create_circle_points(100) cloud100 = create_point_cloud(20) plot_points(circle100) plot_points(incremental_farthest_search(circle100, 5), style={'marker': 'o', 'color':'r', 'markersize': 12}) plt.show()
""" Basic implementation of a stack in python Stack: a collection of objects insertd and removed acc. LIFO (last-in, first-out) principle hint: think PEZ dispenser (can only access pez at "top" of stack) Stack ADT formally supports: s.push() add element to the top of stack s.pop() remove and return top element from the stack; return an error if the stack is empty additional useful methods: s.top() return a reference to the top of the stack w/out removing it; return an error if stack empty s.is_empty() True if stack has no elements len(s) return # of items in stack Analysis: space usage: O(n) operation | running time ------------------------------------ push O(1) * amortized bound pop O(1) * amortized bound top O(1) is_empty O(1) len O(1) * occasionally an O(n)-time worst case, when the underlying Python list has to resize its internal array * Q: How can the design be improved? * Hint 1: what are the most expensive operations? What makes them (relatively) expensive? * Hint 2: suppose the constructor accpeted a parameter setting the value of.. """ class Empty(Exception): """Error attempting to access item from an empty container.""" pass class Stack: def __init__(self): """Create an empty stack""" self._data = [] # non-public underlying Python list as storage def is_empty(self): return len(self._data) == 0 def push(self, item): """Add item to the top of the stack.""" self._data.append(item) def pop(self): """Remove and return the top item from the stack. Raise exception if the stack is empty. """ if self.is_empty(): raise Empty('Stack is empty') return self._data.pop() # calling underlying Python list's pop method def top(self): """Return the top item from the stack (but don't remove it).""" if self.is_empty(): raise Empty('Stack is empty') return self._data[-1] def __len__(self): return len(self._data)
def checkValidString(s): characters = [["(",")"], ['(', '*'],['*', ')']] open_ = [] star=[] if len(s) == 1 and s !="*": return False for c in range(len(s)): if (s[c] == '(') : open_.append(c) elif (s[c] == '*'): star.append(c) else: if open_!=[]: open_.pop() elif star!=[]: star.pop() else: return False while open_!=[] and star != []: if star[-1] > open_[-1]: star.pop() open_.pop() if open_ == []: return True else: return False print(checkValidString("(*)"))
i=input(" ܼ Էּ:") for j in range(1,10): x=i*j print "{}*{}={}".format(i,j,x)
def hanoi(n,a,b): if n>0: hanoi(n-1,a,total[0]) print "moving plate%s from %s to %s."%(n,a,b) hanoi(n-1,total[0],b) n=int(raw_input('please input number of plates: ')) total=['a','b','c'] total.remove('a') total.remove('b') hanoi(n, 'a','b')
# Encapsulation # class Cars: def __init__(self,speed, color): self.__speed = speed self.__color = color def set_speed(self,speed): self.__speed = speed def get_speed(self): return self.__speed ford = Cars(250, 'green') nissan = Cars(300, 'red') toyota = Cars(180, 'blue') # without encapsulation we can access speed variable directly - bad # change speed to __speed from speed ford.speed = 500 # no longer works but does set a speed value print(ford.speed) # but does create and set a new speed value print(ford.get_speed()) ford.set_speed(600) print(ford.get_speed())
# -*- coding: utf-8 -*- """ Created on Fri May 1 15:07:24 2020 @author: Carlos Luco Montofré """ def validaEntero(): notValido = True while notValido: entrada =input() try: numero = int(entrada) notValido = False except ValueError: print("Error digitación. Escriba número entero") return numero def validaFlotante(): notValido = True while notValido: entrada =input() try: numero = float(entrada) notValido = False except ValueError: print("Error digitación. Escriba número flotante") return numero print("programa valida datos entrada") print("Digite un número entero") numero = validaEntero() print("El número es ", numero) print("Digite un número punto flotante") numero = validaFlotante() print("El número es ", numero)
""" Homework Assignment #3: "If" Statements Details: Create a function that accepts 3 parameters and checks for equality between any two of them. Your function should return True if 2 or more of the parameters are equal, and false is none of them are equal to any of the others. Extra Credit: Modify your function so that strings can be compared to integers if they are equivalent. For example, if the following values are passed to your function: 6,5,"5" You should modify it so that it returns true instead of false. Hint: there's a built in Python function called "int" that will help you convert strings to Integers. by: Jansen Gomez """ def Equality(a,b,c): #modification using the "int" function a = int(a) b = int(b) c = int(c) # "IF" statement applying the "or" operator and "Elif" statement if a == b or b == c: return True elif c == a: return True else: return False # User input values for the parameters with the result stored in "var" var = Equality(6,5,"5") print(var)
""" You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 That is, if you cut off the tree at node n, the two trees would be identical. note: tree mactching can be identical to string matching, 2 solutions, trade off between time and space string solution take more space and less time; tree recursion solution more time,less space note: create algo, not code,! some questions are just design, do not need to code completely the string matching solution is still wrong , only a binary search tree will be right. what if we have to check both in-order strings and pre-order strings another approach be ctti 5th: (i think it may be wrong) In this smaller, simpler problem, we could create a string representing the in-order and pre-order traversals. If T2's pre-order traversal is a substring of T l's pre-order traversal, and T2'sin-order traversalisa substring of Tl's in-order traversal,then T2 isa subtree of Tl. Substrings can be checked with suffix trees in linear time, so this algorithm is relatively efficient in terms of the worst case time. add '(' ')', and then do not need to two times traversal """ class Node(object): def __init__(self,data): self.data=data self.left=None self.right=Non def __str__(self): return str(self.data) def inorderdfs(tree, slist=['(']): """ return two list """ if tree is None: return slist.append([')']) # must have '(', else list and tree can NOT be one to one correspondence! inorderdfs(tree.left,slist) slist.append(tree.data) # hash the tree address or data hash(tree.data) inorderdfs(tree.right,slist) def treemathing(t1,t2): """ check if t2 is subtree of t1 """ l1 = [] l1 = inorderdfs(tree,l1) l2 = [] l2 = inorderdfs(tree, l2) n = len(l1) m = len(l2) # for char1 in l1[:n-m]: wrong and copy list for i in range(n-m): if l1[i:i+m] = l2: return True return False def treemathing2(t1,t2): # not match, but directly checking if t2 is subtree of t1 """ this is alternative solution,simple solution is the one above Analyzing the runtime is somewhat complex. A naive answer would be to say that it is 0(nm) time, wherenisthenumberofnodesinTlandmisthenumberofnodesinT2. When might the simple solution be better, and when might the alternative approach be better? This is a great conversation to have with your interviewer The simple solution takes 0(n + m) memory. The alternative solution takes 0(log(n) + log(m)) memory. The simple solution is 0(n + m) time and the alternative solution has a worst case time of 0(nm). """ if t1 is None and t2 is None: return True if t1 is not None and t2 is None : return True if t1.data == t2.data: return treemathing2(t1.left, t2.left) and treemathing2(t1.right, t2.right) or\ treemathing2(t1.right, t2.left) and treemathing2(t1.left, t2.right) # be careful, not bSEARCHtt, # so have to have the second check # the second depends on how you define identical """ bool match(Node* r1, Node* r2){ if(r1 == NULL && r2 == NULL) return true; else if(r1 == NULL || r2 == NULL) return false; else if(r1->key != r2->key) return false; else return match(r1->lchild, r2->lchild) && match(r1->rchild, r2->rchild); } bool subtree(Node* r1, Node* r2){ if(r1 == NULL) return false; else if(r1->key == r2->key){ if(match(r1, r2)) return true; } else return subtree(r1->lchild, r2) || subtree(r1->rchild, r2); } bool contain_tree(Node* r1, Node* r2){ if(r2 == NULL) return true; else return subtree(r1, r2); """
""" 9.6 Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3 (e.g., 3 pairs of parentheses) output: ((())), (()()), (())(), ()(()), ()()() (, left = 1, right = 0 ((, left = 2, right = 0 ((), left = 2, right = 1 (()(, left = 3, right = 1 (()(), left = 3, right = 2 (()()), left = 3, right = 3 1. Left Paren: As long as we haven't used up all the left parentheses, we can always insert a left paren. 2. Right Paren: We can insert a right paren as long as it won't lead to a syntax error. When will we get a syntax error? We will get a syntax error if there are more right parentheses than left. Because we insert left and right parentheses at each index in the string, and we never repeat an index, each string is guaranteed to be unique. """ def foo(output, open, close, pairs): """ The recursion is taking advantage of the fact that you can never add more opening brackets than the desired number of pairs, and you can never add more closing brackets than opening brackets. """ if open == pairs and close == pairs: print output else: if open<pairs: foo(output+'(', open+1, close, pairs) if close<open: foo(output+')', open, close+1, pairs) foo('$', 0, 0, 3)
"""__author__ = 'anyu' 4.3 Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. One way to implement this is to use a simple root.insertNode(int v) method This will indeed construct a tree with minimal height but it will not do so very efficiently. Each insertion will require traversing the tree, giving a total costofO(N log N) to the tree. Alternatively, we can cut out the extra traversals by recursivelyusing the createMin- imalBST method. This method is passed just a subsection of the array and returns the Although this code does not seem especially complex, it can be very easy to make little off-by-one errors. Besure to test these parts of the codevery thoroughly (But I DID NOT! ONE TIME FINISHED MASTERPIECE:) ) discuss that it automatically maintain a binary SEARCH tree here """ class Node(object): def __init__(self,data): self.data=data self.left=None self.right=None def __str__(self): return "( " + str(self.data) + " ( " + str(self.left) + " | " + str(self.right) + "))" def creat_bst(sorted_array): if len(sorted_array) == 0: return "nul array" if len(sorted_array) == 1: bst=Node(sorted_array[0]) return bst else: mid = len(sorted_array)//2 bst = Node(sorted_array[mid]) bst.left=creat_bst(sorted_array[:mid]) bst.right=creat_bst(sorted_array[mid+1:]) return bst intarray1=[1,2,3,4,5,6,7,8,9,10,12,15,18,22,43,144,515] print str(creat_bst(intarray1))
"""__author__ = 'anyu' 9.5 Write a method to compute all permutations of a string This solution takes 0(n !) time, since there are n! permutations. We cannot do better than this. """ def permurecursive(s): if len(s)<=1: return [s] result =[] for perm in permurecursive(s[1:]): result += [perm[:i]+s[0:1]+perm[i:] for i in range(len(perm)+1) ] #must be s[0:1] to allow list AND string #s=[2,3,4] s[3] is err, s[3:]=[], s[:3] == [2,3,4] return result def permuiter(s): if len(s)<=1: yield s else: # must have else, or will trouble, python's problem! when use yield generator, do not forget else! for perm in permuiter(s[1:]): for i in range(len(perm)+1): yield perm[:i]+s[0:1]+perm[i:] #nb s[0:1] works in both string and list contexts def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] result = [] # here is new list with all permutations! # here the res definition is ok, because res do not need to be recursive for i in range(len(l)): s = l[:i] + l[i+1:] result += [ [l[i:i+1]] + x for x in perm(s)] return result def permutList(l): """ only for list, if string, use another fuction to call this function, and use list("sdfaf") to convert string to chars """ if not l: return [[]] res = [] for e in l: temp = l[:] temp.remove(e) res+=[[e] + r for r in permutList(temp)] return res print permurecursive("abc") for x in permuiter("abc"):print x
# -*- coding: utf-8 -*- """ Created on Tue Nov 24 19:27:25 2020 @author: Vladimir Trotsenko """ ######################### #### ASSIGNIMENT ######## ######################### #### FIRST ############## ######################### annual_salary = float(input('Enter the starting annual salary: ')) portion_saved = float(input('Enter the portion of salary to be saved: ')) total_cost = float(input('Enter the cost of your dream home: ')) portion_down_payment = (0.25)*total_cost current_savings = 0 r = 0.04 months = 0 while current_savings < portion_down_payment: current_savings += current_savings*r/12 current_savings += portion_saved*(annual_salary/12) months += 1 if current_savings >= portion_down_payment: print('Number of months:', months) ######################### #### SECOND ############# ######################### annual_salary = float(input('Enter the starting annual salary: ')) portion_saved = float(input('Enter the portion of salary to be saved: ')) total_cost = float(input('Enter the cost of your dream home: ')) semi_annual_raise = float(input('Enter the semi-annual salary raise: ')) portion_down_payment = (0.25)*total_cost current_savings = 0 r = 0.04 months = 0 while current_savings < portion_down_payment: current_savings += current_savings*r/12 current_savings += portion_saved*(annual_salary/12) months += 1 if months > 1 and months%6 == 1: annual_salary += annual_salary*semi_annual_raise if current_savings >= portion_down_payment: print('Number of months:', months) ######################### #### THIRD ############## ######################### annual_salary = float(input('Enter the starting annual salary: ')) monthly_salary = annual_salary/12 semi_annual_raise = 0.07 r = 0.04 monthly_r = r/12 total_cost = 1000000 portion_down_payment = (0.25)*total_cost steps = 0 portion_saved = 1 epsilon = 100 low = 0 high = portion_saved ans = (low + high)/2.0 total_salary = 0 for i in range(36): if i != 1 and i%6 == 1: monthly_salary += monthly_salary*semi_annual_raise monthly_salary += monthly_salary*monthly_r total_salary += monthly_salary if total_salary < portion_down_payment - 100: print('It is not possible to pay the down payment in three years.') else: savings = total_salary*ans while abs(savings - portion_down_payment) >= epsilon: print('low =', str(low), 'high =', str(high), 'ans =', str(ans)) steps += 1 if savings < portion_down_payment: low = ans else: high = ans ans = (low + high)/2.0 savings = total_salary*ans print('Best saving rate:', "%.4f" %ans) ### print 4 digits after decimal print('Steps in bisection search:', str(steps))
# mnha solução para o desafio de um contador: # cont_plus = 0 # cont_less = 10 # while cont_plus <= 10 and cont_less >= 0: # print(cont_plus, cont_less) # cont_less -=1 # cont_plus +=1 #solução do professor para o desafio de um contador: # for p, r in enumerate(range(10,1,-1)): # print(p, r) # print(11-(195 % 11)) #Arv --> Exercicio: Validador de CPF.
#Exercicio1 #conversão em inteiro #usando: try and except, para conseguir testar o sucesso num1 = input('Digite um número: ') num2 = input('Digite outro número: ') try: num1 = int(num1) num2 = int(num2) divnum1 = num1 % 2 divnum2 = num2 % 2 if divnum1 == 0 and divnum2 == 0: print('Os dois números são pares') elif divnum1 == 0: print(f'Somente o {num1} é par') elif divnum2 == 0: print(f'Somente o {num2} é par') else: print('Nenhum número é PAR') except: print('Por favor, digite somente números inteiros.')
def conferter_numero(valor): try: valor = int(valor) return valor except ValueError: try: valor = float(valor) return valor except: pass def soma(a, b): soma = a + b print(soma) def subtr(a, b): subtracao = a - b print(subtracao) def div(a, b): div = a / b print(div) def mult(a, b): mult = a * b print(mult) print() print('para fazermos uma conta, entre com dois numeros e um operador.') print('para sair, digite break no operador') while True: print() a = input('entre com o primeiro numero: ') b = input('entre com o segundo numero:') op = input('entre com o sinal da operação: ') if not a.isnumeric() or not b.isnumeric(): print('Você precisa digitar um numero') continue a = conferter_numero(a) b = conferter_numero(b) if op == '+': soma(a, b) elif op == '-': subtr(a, b) elif op == '*': mult(a, b) elif op == '/': div(a, b) elif op == 'break': break else: print('infelizmente só sei fazer as contas básicas')
# Bubble Sort def bubblesort(alist): for i in range(0, len(alist)-1): print('Langkah ke-%d: '% (i+1), end='') for j in range(len(alist)-1, i, -1): if alist[j] < alist[j-1]: temp = alist[j] alist[j] = alist[j-1] alist[j-1] = temp print(alist) data = [9, 7, 10, 8, 12, 11, 14, 13] # showing the data print(data) # calling bubblesort() bubblesort(data) print(data) ''' we can code simpler, alist[j], alist[j-1] = alist[j-1], alist[j] '''
# Private Method class rectangle: def __init__(self, l=0, w=0): self.__length = l self.__width = w def setvalue(self, l, w): self.__length = l self.__width = w def getLength(self): return self.__length def getWidth(self): return self.__width def wide(self): return self.__length * self.__width # Make an object obj = rectangle() # set value obj.setvalue(10,8) # get the value print(obj.getLength()) print(obj.getWidth()) # get the value of wide print(obj.wide())
# Rank Number # count 2 rank 5 with ** operator print(2**5) # count 2 rank 5 with pow() print(pow(2,5)) ''' prototype: pow(x, y[, z]) -> number when we only put two parameter, this function will only process X ** y when we put three parameter, then the function will process (x ** y) % z '''
# Reading CSV file import csv with open("D:\Rizky's File\Tutorial\Coding\Python\CrashCourse\pencipta.csv", 'r', newline='', encoding='utf-8') as csvfile: r = csv.reader(csvfile, delimiter=',') for row in r: for i in range(len(row)): print('%s\t'% row[i], end='') print() # new line csvfile.close()
a = [10,20,30,40,50,60] print(a) # use del comand del a[2] print(a) # use method remove() a.remove(20) print(a) ''' remove will only delete one value which is in first data ''' #use method pop() nilai = a.pop() print(nilai) print(a) ''' pop will only take out the last value '''
# Decrement a Value Function def decrement(x, value=1): x = x - value return x b = 10 print(decrement(b)) print(decrement(b, 2))
# Searching String in certain part data = ['Akhmad Koysim', 'Akhmad Ilman', 'Anis Yuliana Phasya', 'Rizki Sadewa', 'Muhammad Ilman', 'Muhammad Rozak', 'Muhammad Yusuf'] # Searching the String which is contain the name startwith 'Muhammad' for name in data: if name.startswith('Muhammad'): print(name) print() # Searching the String whcih is contain the name with endswith 'Ilmand' for name in data: if name.endswith('Ilman'): print(name) ''' Prototype: s.startswith(prefix[, start[, end]]) -> bool means the method will return True if the string s started substring prefix, otherwise return false. start and end will spcify the start or end position of the prefix that will be checked ''' nama = 'Muhammad Ilman' print(nama.startswith('Muhammad')) print(nama.startswith('Akmal')) print(nama.startswith('uha', 1, 4)) # will return True due to uha still contained in string of nama variable from index number 1 until 4 ''' Prototype: s.endswith(prefix[, start[, end]]) -> bool means the method will return True if the string s started substring suffix, otherwise return false. start and end will spcify the start or end position of the suffix that will be checked ''' print(nama.endswith('Ilman')) # will return True print(nama.endswith('n')) # will return True print(nama.endswith('mad', 0, 8)) # will return True
# function for return a few of value def getvalues(): return 1, 2, 3 # call the value a, b, c = getvalues() print(a) print(b) print(c) ''' getvalues() will return the tuple object, remember we can also make the tuple without () '''
# Overloading class aritmatika: def tambah(self, *daftarnilai): total = 0 for i in daftarnilai: total += 1 return total # Make an object from class aritmatika obj = aritmatika() # call method addition with 2 parameter print(obj.tambah(2, 3)) # call method addition with 3 parameter print(obj.tambah(2, 3, 4)) # call method addition with 4 parameter print(obj.tambah(2, 3, 4, 8)) # call method addition with 5 parameter print(obj.tambah(2, 3, 4, 8, 9)) ''' Python does not allow to have two or more methods with the same name, therefore we need to make the Overloading method for the alternative '''
# Editing Dictionary d = {'one':100, 'two':200, 'three':300} print(d) d['two'] = 900 print(d) ''' Dictionary is sensitive case, especially in key list '''