text
stringlengths
37
1.41M
#Realizar un programa que cumpla el siguiente algoritmo utilizando siempre que sea posible operadores #de asignación numero_magico = 12345679 #numeros enteros entre el 0 al 65.535 numero_usuario = int(input("Ingrese un numero entre el 1 al 9: ")) numero_usuario *= 9 numero_magico *= numero_usuario print(f"El número mágico es {numero_magico} ")
#Realiza un programa que sume todos los números enteros pares desde el 0 hasta el 100. num_par=list(range(0,101,2)) print(num_par) print(f"La suma de los numeros pares de la lista {num_par} = ", sum(num_par) )
'''Realiza un programa que pida al usuario un número entero del 0 al 9, y que mientras el número no sea correcto se repita el proceso. Luego debe comprobar si el número se encuentra en la lista de números y notificarlo: Concepto útil La sintaxis [valor] in [lista] permite comprobar si un valor se encuentra en una lista (devuelve True o False). ''' lista = [1, 3, 6, 9, 4, 11] while True: numero = int(input("Ingrese un numero entero entre el 0 al 9 \n")) if numero >= 0 and numero <= 9: break if numero in lista: print(f"El numero {numero} existe en la lista {lista} ") else: print(f"El numero {numero} no existe en la lista {lista} ")
'''Dadas dos listas, debes generar una tercera con todos los elementos que se repitan en ellas, pero no debe repetirse ningún elemento en la nueva lista:''' l_1 = ['E', 'l', ' ', 'a', 'm', 'o', 'r', ' ', 'e', 't', 'i', 'e', 'm', 'p', 'o', 's', ' ', 'd', 'e', ' ', 'c', 'l', 'e', 'r', 'a'] l_2 = ['H', 'o', 'l', 'a', ' ', 'm', 'u', 'n', 'd', 'o'] l_3 = [] for i in l_1: if i in l_2 and i not in l_3: l_3.append(i) print(l_3)
# Simple Snake Game in Python 3 import turtle import time import random delay = 0.1 # Score Pontuacao = 0 Pontuacao_maxima = 0 # Set up da tela wn = turtle.Screen() wn.title("Snake Game by Luan Jesus") wn.bgcolor("purple") wn.setup(width=600, height=600) wn.tracer(0) # Snakehead head = turtle.Turtle() head.speed(0) head.shape("square") head.color("black") head.penup() head.goto(0,0) head.direction = "stop" # Snake food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0,100) segments = [] pen = turtle.Turtle() pen.speed(0) pen.shape("square") pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Pontuacao:0 Pontuacao maxima:0", align="center", font=("Courier", 22, "normal")) # Functions def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) # Keyboard bindings wn.listen() wn.onkeypress(go_up, "w") wn.onkeypress(go_down, "s") wn.onkeypress(go_left, "a") wn.onkeypress(go_right, "d") # Main game loop while True: wn.update() if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290: time.sleep(1) head.goto(0,0) head.direction = "stop" for segment in segments: segment.goto(1000, 1000) segments.clear() Pontuacao = 0 delay = 0.1 pen.clear() pen.write("Pontuacao: {} Pontuacao maxima: {}".format(Pontuacao, Pontuacao_maxima), align="center", font=("Courier", 22, "normal")) if head.distance(food) < 20: x = random.randint(-290, 290) y = random.randint(-290, 290) food.goto(x,y) new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape("square") new_segment.color("grey") new_segment.penup() segments.append(new_segment) delay -= 0.001 Pontuacao += 10 if Pontuacao > Pontuacao_maxima: Pontuacao_maxima = Pontuacao pen.clear() pen.write("Pontuacao: {} Pontuacao maxima: {}".format(Pontuacao, Pontuacao_maxima), align="center", font=("Courier", 22, "normal")) for index in range(len(segments)-1, 0, -1): x = segments[index-1].xcor() y = segments[index-1].ycor() segments[index].goto(x, y) if len(segments) > 0: x = head.xcor() y = head.ycor() segments[0].goto(x,y) move() for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" for segment in segments: segment.goto(1000, 1000) segments.clear() Pontuacao = 0 delay = 0.1 pen.clear() pen.write("Pontuacao: {} Pontuacao maxima: {}".format(Pontuacao, Pontuacao_maxima), align="center", font=("Couriaer", 22, "normal")) time.sleep(delay) wn.mainloop()
choice = input("""Type 1 for a Gift, Type 2 for a surprise, Type for free fortnite Vbucks link: """) if choice == '1': print("here take a gift") elif choice == '2': print("Surprise!") elif choice == '3': print("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab")
products = []#products是大火車,裝大清單,裝一組一組的小p;p小火車裝小清單,一個商品一個清單 while True:#while迴圈通常用在不確定幾次的迴圈 name = input('請輸入商品名稱: ') if name == 'q': break price = input('請輸入商品價格: ') products.append([name, price])#將每1小組的p清單裝入products大清單中 print(products )#會印出[['01','02'], ['11', '12']]有2個[] for p in products: print(p[0], '的價格是', p[1]) #print(p[1])==>印出清單中的第2個欄位-價格 products[0][1]#找出第1節車節中的第2個小座位的值 # p = []#產生1個價格+1個商品的小清單 # p.append(name)#將名稱裝入p清單中 # p.append(price)#將價格裝入p清單中 # p = [name, price]這一行可以取代上面三行 # p = [name, price] # products.append([name, price])這行可以取代上一行,就不用p了
from Registration import Registration def GetVehicleDetails(): from Vehicle import Vehicle print("1. Enter Car details: ") print("Make: ") make = input() print("Model: ") model = input() print("Price: ") price = input() print("Color: ") color = input() vehicle = Vehicle(make, model, price, color) return vehicle def MainMenu(): print("Welcome to Vehicle Registration System") print("Please Select") print("1- Vehicle Registration") print("2- Find Registered Vehicle by Number") userInput = input() if userInput: if userInput == "1": return GetVehicleDetails() elif userInput == "2": print("Enter Vehicle Number:") registrationNumber = input() return Registration().getVehicleDetails(int(registrationNumber)) else: print("Invalid Input") else: print("Invalid Input")
from core.src import admin, student, teacher view_map = { "1": student, "2": teacher, "3": admin } def run(): while 1: choice = input(''' 1:学生视图 2:老师视图 3:管理视图 (输入q退出) >>> ''') if choice == "q": print("已退出,结束程序") break if choice in view_map: view_map[choice].run() else: print("错误输入,请重输")
import random import NEMO print random.randrange(1,5) def main(): ans = random.randrange(1,11) keepGoing = True while keepGoing: guess = NEMO.userInt("Enter a guess from 1 to 10:") if guess == ans: print "You win!" keepGoing = False main()
import NEMO import random #------------------------------------------------------------------------------- # selects a random word from a file and returns it #------------------------------------------------------------------------------- def pickWord(): words = [] # read the file and place each word in out list f = open('hangmanWords.txt') for w in f: w = w.strip() words.append(w) #select a word at random r = random.randrange(0, len(words)) return words[r] #------------------------------------------------------------------------------- # displays the cutrent board showing where letters have been guessed #------------------------------------------------------------------------------- def displayBoard(board): for ch in board: print "%s "% ch, print #------------------------------------------------------------------------------- # asks the user to guess a ltter and reutns the letter #------------------------------------------------------------------------------- def askUserForLetter(): l = NEMO.userString("Please select a letter:") return l #------------------------------------------------------------------------------- # given the board, the word and the chosen letter, this function checks to see # if the letter is in the word and then updates the board accordingly, if the # letter is in the word, this returns false, otherwise the user guessed wrong # and true is returned #------------------------------------------------------------------------------- def updateBoard(board, word, letter): # check to see if the letter is in the word # if it is not, then missed is true missed = letter not in word # check each letter in word to see if it is the letter the user entered for i in range(0, len(word)): if word[i] == letter: board[i] = letter return missed #------------------------------------------------------------------------------- #returns true if teh board no longer has any * in it. - means the word is guessed #------------------------------------------------------------------------------- def testForGameOver(board): return "*" not in board #------------------------------------------------------------------------------- # ... ... ... #------------------------------------------------------------------------------- def main(): # pick a random word word = pickWord() # initialize a board board = [] for ch in word: board.append('*'); # initialize the game misses = 0 gameOver = False # start main game loop... while gameOver != True: # display the board displayBoard(board) # let the user guess a letter letter = askUserForLetter() if updateBoard(board, word, letter) == True: misses = misses + 1 print "The word does not contain %s! You have %i misses." %(letter, misses) gameOver = testForGameOver(board) # print end of game message print "You did it!" print "The word is %s" % word print "You had %s wrong quesses." % misses main()
from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score import re import pandas as pd import sklearn import matplotlib.pyplot as plt import time #Import and read the dataset df = pd.read_csv(r'data/Corona_NLP_train.csv') # Monitor the time start = time.time() # Possible sentiments a tweet may have df_sentiment = df.Sentiment.unique() # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.tolist.html # Gets the values of how many times each sentiment value appeared and puts in # order of list secondCom = df[r'Sentiment'].value_counts().index.tolist() print('The possible Sentiments a tweet has are:',secondCom) print(" ") # Prints second value of most common sentiment print('The second most common sentiment in tweets is:',secondCom[1]) print("") # https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html # https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html # Keeps all Extremely Positive tweets df1 = df[df['Sentiment'].str.contains('^Extremely Positive', na=False)] # Groups the Sentiment and TweetAt together # Counts how frequently they appear new = df1.groupby(['Sentiment','TweetAt']).size().reset_index(name='count') # Sort the values positive = (new.sort_index(axis=0).sort_values(['count'], ascending=False)) print("Display the amount of Extremely poisitive tweets and the date of which" " there was the highest number of them") print(positive.head(1)) print(" ") # https://stackoverflow.com/questions/22588316/pandas-applying-regex-to-replace-values # https://docs.python.org/3/howto/regex.html # Converts messages of tweets to lower case # Replaces all non-alphabetic lettering with whitespaces df['CharChange']= df["OriginalTweet"].str.lower().replace(r'[^a-z]+',' ', regex=True) print('Leterring is now lower case and all non-alphabetic letters are converted ' 'into white space:') print(df[r'CharChange']) print(" ") # https://www.programcreek.com/python/example/106181/sklearn.feature_extraction.stop_words.ENGLISH_STOP_WORDS # Words are tokenized and counted stop_words = set(sklearn.feature_extraction.text.ENGLISH_STOP_WORDS) print('Total number of words including repetitions:', df['CharChange'].str.split().str.len().sum()) print(" ") # Total unique words are calculated word_amount = CountVectorizer(token_pattern=r"(?u)\b\w+\b") X_train_counts = word_amount.fit_transform(df[r'CharChange']) print('Number of Distinct words:',X_train_counts.shape[1]) print("") # Display the top 10 most frequent words used in the tweets test = df['CharChange'].str.split(expand=True).stack().value_counts() print('Top 10 Most frequent words are:') print(test.T.sort_values(ascending=False).head(10)) print("") # https://stackoverflow.com/questions/52421610/how-to-replace-all-words-of-length-less-than-3-in-a-string-with-space-in-j # https://docs.python.org/3/library/re.html # StopWords and Words with less than two characters are removed. less_than_two = re.compile(r'\b\w{,2}\b') df['new'] = df['CharChange'].apply(lambda s: less_than_two.sub('',s)) escaped = map(re.escape, stop_words) pattern = re.compile(r'\b(' + r'|'.join(escaped) + r')\b') df['removal'] = df['new'].apply(lambda s: pattern.sub('',s)) # Total number of words after removal are recalculated print('Number of words (after removal):',df['removal'].str.split() .str.len().sum()) print("") # Top 10 words are recalculated and displayed again remove_stop1 = df['removal'].str.split(expand=True).stack().value_counts() print("After removal of words ") print(remove_stop1.T.sort_values(ascending=False).head(10)) print("") # Multinomial Naive Bayes classifier is implemented for the # Coronavirus NLP semantics to predict the classification of tweets. # Corpus is stored in a numpy array # Trained on training set vectorizer = CountVectorizer() clf = MultinomialNB() X = vectorizer.fit_transform(df['removal']) y = df['Sentiment'] clf.fit(X, y) x = clf.predict(X) acc = accuracy_score(x, y) error_rate = 1 - acc print('The error rate is',error_rate) print("") # Display the frequency of words in histogram which will be shown in the outputs # folder. Log is used to improve the readability. # Plots word frequencies using log to improve readability new = pd.DataFrame(df['removal'].str.split().apply(set).tolist()).stack().\ value_counts(ascending = True) plt.yscale("log") plt.plot(range(len(new)),new) plt.savefig('outputs/word frequency.jpg') plt.show() print('The total time taken',time.time()-start)
from Projectile import Projectile from time import sleep startingVelocity = float(input("What is the initial velocity of the projective? ")) angle = float(input("What angle was the projectile launched at? ")) starting_height = float(input("What was the starting height of the object? ")) myProjectile = Projectile(startingVelocity, angle, starting_height, 1) y_displacement = starting_height seconds = 0 while myProjectile.secondly_motion(seconds)["y"] >= 0: myProjectile.secondly_motion(seconds) print("At t =", str(round(seconds, 2)), "seconds, x =", str(round(myProjectile.secondly_motion(seconds)["x"], 2)),"and y =", str(round(myProjectile.secondly_motion(seconds)["y"], 2))) seconds += 1 sleep(1) print("The ball hit the ground again at x =", round(myProjectile.find_delta_x(myProjectile.find_zero()), 2), "after", myProjectile.find_zero(), "seconds.")
rivers = { 'nile' : 'egypt', 'mississippi' : 'usa', 'red' : 'somewhere' } for river, location in rivers.items(): print("The {} river is located in {}".format(river, location)) print(river) print(location)
class User: def __init__(self, first, last, age): self.first_name = first self.last_name = last self.age = age def describe_user(self): print("{} {} is {} years of age.".format(self.first_name, self.last_name, self.age)) def greet_user(self): print("Hello {}, welcome.".format(self.first_name.title())) class Admin(User): def __init__(self, first, last, age): super().__init__(first, last, age) self.privileges = Privileges('text message') class Privileges: def __init__(self, privilege): self.privileges = [privilege] def show_privileges(self): for privilege in self.privileges: print(privilege) user1 = Admin('donald', 'glover', 22) user2 = User('pikachu', 'ketchum', 1992) user3 = User('sonic', 'hedghog', 1982) user1.describe_user() user1.greet_user() user1.privileges.show_privileges() user2.describe_user() user2.greet_user() user3.describe_user() user3.greet_user()
pizza = ['supreme', 'meat', 'pineapple'] for choice in pizza: print(choice) print("Nothing else compares to {}".format(choice)) print("I really, really like pizza")
names = ['nicki minaj', 'sabrina claudio', '6lack'] print('{} you are invited.\n{} you are invited.\n{} you are invited.'.format(names[0], names[1], names[2])) print(len(names))
vacation = {} poll_active = True number = 1 user = None while poll_active: print("If you can visit one place in the world, where?") user = input("> ") vacation[str(number)] = user number += 1 print(vacation) if user == 'q': poll_active = False print("Exiting")
#!/usr/bin/python # -*- coding: UTF-8 -*- '''题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。 程序分析:关键是计算出每一项的值。 程序源代码:''' a=input('输入要相加的数是:') n=input('相加的数个数为:') s=a end=0 for i in range(n) : a=a*10+s print a end =end +a print end
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。 最后问第一个人,他说是10岁。请问第五个人多大? 程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10岁),再往回推。 程序源代码: ''' s=8 for i in range(1,6): s=s+2 print ('第%d个人的岁数是%d'%(i,s))
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:求1+2!+3!+...+20!的和。 程序分析:此程序只是把累加变成了累乘。 ''' def sum(n): w=0 all=0 for i in range (1,n+1): s=1 for j in range(1,i+1): s=s*j w =s print 'w',w all =all+w print 'all',all sum(20)
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数 程序分析:无。 程序源代码: ''' from collections import deque m = 3 a = [1,2,3,4,5,6,7] # 7 个数 f = deque(a) f.rotate(m) print list(f) ######方法2 m = 3 a = [1,2,3,4,5,6,7] def rot(a,n): l = len(a) n = l-n return a[n:l]+a[0:n] b = rot(a,m) print a print b
#!/usr/bin/python # -*- coding: UTF-8 -*-\ ''' 题目:列表排序及连接。 程序分析:排序可使用 sort() 方法,连接可以使用 + 号或 extend() 方法。 程序源代码: ''' if __name__=="__main__": str1=[1,3,2,7,6,5] str2=[3,3,3] str1.sort() print str1 str3=str1+str2 str1.extend(str2) print str3 print str1
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。 程序分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。 程序源代码: ''' import numpy as np a=([1,3,4,5,7]) y=input('输入一个数字:') a.append(y) a.sort() print a
#!/usr/bin/python # -*- coding: UTF-8 -*- '''题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 程序分析:无。 程序源代码:''' sting= raw_input('please input 5 string:') x=len(sting) w=[] for i in range(x): w.append(sting[x-i-1]) print w
name = 'steven' result ='eve' in name print(result) #not in result = 'tv' not in name print(result) #r 保留原格式 有r就不转义,没有r则转义 name = 'jason' print(r'%s: \'hahaha!\''%name) filename = 'picture.png' print(filename[5]) #通共【】结合位置获取字母,只能一个 #包前不包后 print(filename[0:7])#0123456 print(filename[3:])#省略后面就一直到结尾 print(filename[:7])#省略前面就是从0开始取 #f i l e n a m e . p n g #0 1 2 3 4 5 6 7 8 9 10 11 print(filename[8:-1]) #一直到n,把倒数第二位 print(filename[:-2]) #一直到倒数第二位
#字符串的格式化输出 #format 也是一种格式化输出,用{}占位然后 .format调用,不管type age = 2 s = 'already' message = ' George said: I am {} years old,{} go to school'.format(age,s) print(message) name = 'George' age = 3 hobby = 'Game' money = 5.89 message = '{} is {} years old, love {}, and have {} dollars'.format(name, age, hobby, money) print(message)
# Question 3 print("What is your number:") num_str = str(input()) num_list = [] sum = 0 # Loop through the numbers for i in num_str: if i == "2": continue elif i == "9": i = int(i) i *= 2 # create a list of numbers with each number as a string num_list.append(str(i)) # sum the elements sum += int(i) else: # create a list of numbers with each number as a string num_list.append(i) # sum the elements sum += int(i) # join all items into one string seperated by " + " a = " + ".join(num_list) # print the output print(f"{a} = {sum}")
# Question 2 print("What is your number:") num_str = str(input()) num_list = [] sum = 0 # Loop through the numbers for i in num_str: # create a list of numbers with each number as a string num_list.append(i) # sum the elements sum += int(i) # join all items into one string seperated by " + " a = " + ".join(num_list) # print the output print(f"{a} = {sum}")
class Binary: # Binary Class | used for converting binary to other 3 formats def toDecimal(self, binary): # Converts binary to decimal remainder = 0; maxlength = len(str(binary)); length = 0; decimal = 0 while length <= maxlength: remainder = binary % 10 decimal += (remainder * (2 ** length)) binary /= 10 length += 1 return decimal def toOctal(self, binary): # Converts binary to octal decimal = self.toDecimal(binary); base = 1; remainder = 0; octal = 0 while decimal > 0: remainder = decimal % 8 decimal /= 8 octal += (remainder * base) base *= 10 return octal def toHexadecimal(self, binary): # Converts binary to hexadecimal decimal = self.toDecimal(binary); remainder = 0; hexadecimal = "" while (decimal > 0): remainder = decimal % 16 decimal /= 16 hexadecimal = str(remainder) + hexadecimal if (remainder < 10) else str(chr(55 + remainder)) + hexadecimal return hexadecimal
""" open file """ import csv def copy_book_list(): with open("BooksRead.csv") as infile: csv_reader = csv.reader(infile) with open("new_book_list.csv", "w") as new_file: new_csv = csv.writer(new_file, delimiter='\t') for line in csv_reader: new_csv.writerow(line) #%% def read_csv_file(): with open("BooksRead.csv", "r") as new_file: new_csv = csv.reader(new_file, delimiter='\t') for line in new_csv: print(line) #%% def csv_book_list(): """This is Function use for Normal people """ """return to Dictionary""" with open("BooksRead.csv") as infile: csv_reader = csv.DictReader(infile) for line in csv_reader: print(line["WRITHER"]) csv_book_list() #%% import csv with open("BooksRead.csv", "r") as infile: csv_reader = csv.DictReader(infile) with open("new_book_list.csv", "w") as new_file: fielname = ["WRITHER", "NAME BOOK", "CATEGOURY"] new_csv = csv.DictWriter(new_csv, fieldnames = fielname, delimiter = "\t") new_csv.writeheader() for line in csv_reader: new_csv.writerow(line)
"""Merge Sort Algorithm. The Merge Sort is a recursive sort of order n*log(n). It is notable for having a worst case and average complexity of O(n*log(n)), and a best case complexity of O(n) (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups).Then merge the groups back together so that their elements are in order. This is how the algorithm gets its "divide and conquer" description. """ def merge(left, right): """Takes two sorted lists and returns a single sorted list by comparing the elements one at a time. >>> left = [1, 5, 6] >>> right = [2, 3, 4] >>> merge(left, right) [1, 2, 3, 4, 5, 6] """ # Check if any list is empty if len(left) * len(right) == 0: return left + right # Merge keeping the order merge_list = (left[0] < right[0] and left or right).pop(0) return [merge_list] + merge(left, right) def mergesort(unsorted_list): """Sorts the input list using the merge sort algorithm. >>> lst = [4, 5, 1, 6, 3] >>> merge_sort(lst) [1, 3, 4, 5, 6] """ # Lists of 1 elements are already sorted if len(unsorted_list) < 2: return unsorted_list # Set the split point mid = len(unsorted_list) / 2 # Divide left_part = mergesort(unsorted_list[:int(mid)]) right_part = mergesort(unsorted_list[int(mid):]) return merge(left_part, right_part)
# -*- coding: utf-8 -*- #Lesson: while structure x = 1 y = 5 def compare_values(x, y): if x > y: #print("x is higher than y") return "x is higher than y" else: if x == y: #print ("x is the same than y") return "x is the same than y" else: #print("x is less than y") return "x is less than y" while x < 10: print (x,": ",compare_values(x, y)) compare_values(x, y) x += 1 print("\n") #Lesson: for structure list_of_king_books = ["It", "The Stand", "The Shining", "The Institute", "The Outsider", "Doctor Sleep", "November 63", "Joyland"] for book in list_of_king_books: print(book)
''' Some calcs for analog filters. ''' import all_pass def rc_f(r, c): ''' Calculate the cutoff frequency of a simple RC filter. r = resistance (ohms) c = capacitance (F) ''' from math import pi return 1.0/(2.0*pi*r*c) def rc_r(f, c): ''' Calulate the resistance required for a simple RC filter. f = cutoff frequency (Hz) c = capacitance (F) ''' from math import pi return 1.0/(2.0*pi*f*c) def rc_c(f, r): ''' Calulate the resistance required for a simple RC filter. f = cutoff frequency (Hz) r = resistance (ohms) ''' from math import pi return 1.0/(2.0*pi*f*r) def lc_f(l, c): ''' Calulate the cutoff frequency of a simple LC filter. l = inductance (H) c = capacitance (F) ''' from math import pi, sqrt return 1.0/(2.0*pi*sqrt(l*c)) def lc_l(f, c): ''' Calulate the inductance required for a simple LC filter. f = cutoff frequency (Hz) c = capacitance (F) ''' from math import pi w = 2.0*pi*f return 1.0/(w**2*c) def lc_c(f, l): ''' Calulate the capacitance required for a simple LC filter. f = cutoff frequency (Hz) l = inductance (H) ''' from math import pi w = 2.0*pi*f return 1.0/(w**2*l)
from collections import OrderedDict class LRUCache(OrderedDict): def __init__(self, limit=10): self.maxsize = limit """ Retrieves the value associated with the given key. Also needs to move the key-value pair to the top of the order such that the pair is considered most-recently used. Returns the value associated with the key or None if the key-value pair doesn't exist in the cache. """ def get(self, key): try: value = super().__getitem__(key) self.move_to_end(key) return value except KeyError: return None """ Adds the given key-value pair to the cache. The newly- added pair should be considered the most-recently used entry in the cache. If the cache is already at max capacity before this entry is added, then the oldest entry in the cache needs to be removed to make room. Additionally, in the case that the key already exists in the cache, we simply want to overwrite the old value associated with the key with the newly-specified value. """ def set(self, key, value): super().__setitem__(key, value) if len(self) > self.maxsize: oldest = next(iter(self)) del self[oldest]
import sys import ast def perceptron(A, w, b, x): sum = 0 for f, o in zip(w, x): sum+=int(f)*int(o) return A(sum+float(b)) def step(num): if num>0: return 1 else: return 0 #XOR HAPPENS HERE def perceptron_network(input_val): o3 = perceptron(step, (2, 2), -1, input_val) o4 = perceptron(step, (-1, -1), 2, input_val) o5 = perceptron(step, (1, 1), -1, (o3, o4)) return o5 x = ast.literal_eval(sys.argv[1]) output = perceptron_network(x) print(output)
def PairsofSum(arr, n, k): count = 0 list = [] # Pick all elements one by one for i in range(0, n): # See if there is a pair of this picked element for j in range(i+1, n) : if arr[i] + arr[j] == k or arr[j] + arr[i] == k: count += 1 list.append((arr[i],arr[j])) return count ,list arr = [1, 9, 4, 6, 7,8,0] n = len(arr) k = 10 count, list = PairsofSum(arr, n, k) print ("Count of pairs with given diff is ", count, "\tThe list of pairs is: ", list)
import sys import re __book = {} def add(): """Function adds a name (str) and a number (int) in the dict. Name and number need to be entered. Function checks if the amount of digits in number are 6 or 11. :raises: ValueError """ key = input("Enter a name: ") if not key.isalpha(): print("Name should be alphabetic.") else: try: number = int(input("Type phone number. It should contain 6 or 11 integers.\n")) low = re.search('^[1-9][0-9]{5}$', str(number)) high = re.search('^[1-9][0-9]{10}$', str(number)) if low or high: if key in __book: __book[key].append(number) else: __book[key] = [number] print('Contact added.') else: print("Number should contain 6 or 11 integers.") except ValueError: print("Number should contain integers only") def help(): """Function prints all commands user can input in the program.""" print("Commands you may use:") for t in func_list: print(t) def get(): """Function asks user to enter a name and prints this name and number associated with it from the dict. If there is no such name in dict.keys, prints str.""" name = input("Who are you looking for?\n") if name in __book.keys(): for i in range(len(__book[name])): print('{}\t{}'.format(name, __book[name][i])) else: print("You don't have this contact yet.") def exit(): """Function calls built-in function exit()""" print("Terminating work..") sys.exit() def delete(): """Function deletes number from the phonebook.""" name = input("Who's number would you like to delete?\n") if name in __book: del(__book[name]) print("Contact deleted.") else: print("You don't have this contact.") # creating a tuple of functions in the program func_list = dir() func_list = tuple(i for i in func_list if '__' not in i and i != 'sys' and i != 're') while True: print("Enter a command or type 'help' for information: ") command = input() if command in func_list: f = globals()[command] f() else: print("It seems that you've made a mistake... I'll give you another chance :)")
#!/usr/bin/env python def validate(low_bound=0, upper_bound=256): """Estimates function parameters (there should be three of them between low_bound and upper_bound). If they aren't, prints "Function call is not valid!". :param low_bound: int. 0 by default :param upper_bound: int. 256 by default :return: the result of calling function """ def decorator(func): @functools.wraps(func) def inner(*args): if len(args) == 3: for arg in args: if low_bound <= arg <= upper_bound: return func(*args) else: print('Function call is not valid!') break else: print('Function call is not valid!') return inner return decorator @validate() def set_pixel(*pixel_values): """Creates a pixel.""" print('Pixel created!') set_pixel(31, 40, 34) set_pixel(2598, -20, 47)
class Price: """Checks parameters (0-100).""" def __init__(self, label): self.label = label def __get__(self, instance, owner): print("Descr.__get__") return self.__dict__[self.label] def __set__(self, instance, value): print("Descr.__set__") if value < 0 or value > 100: raise ValueError("Price must be between 0 and 100.") else: self.__dict__[self.label] = value class Book: """Represent a book. :param author: author's name. Contains letters only :param title: book's heading :param price: book's price :type price: int between 0 and 100. """ price = Price("price") def __init__(self, author, title, price): if author.isalpha: self.author = author else: raise ValueError("Author's name should contain letters only.") self.title = title self.price = price if __name__ == '__main__': chelinger = Book("William Faulkner", "The Sound and the Fury", 12) # chelinger.price = -12 chelinger.price = 100 print(chelinger.price)
#Richard Burke #9/17/18 #Programming in Python #HW 2-3 #initialize i = 0 NUM_DAYS = 7 highest = 0 #loop through for each day, comparing highest to each input while (i < NUM_DAYS): numBugs = int(input("Enter score: ")) if numBugs > highest: highest = numBugs i+=1 #print highest print("The highest number of bugs collected this week is", highest)
def cubic_algorithm(array): global_max_sum = 0; index_i = 0; """for each element of the array""" for i in array: local_max_sum = 0; #print("\n ******************************************************* value i:", i) #print("\n i to end array", array[index_i:len(array)]) index_j = index_i +1 """from index i to end of array""" for j in array[index_i:len(array)]: #print("\n i to j array:", array[index_i:index_j]) local_max_sum = 0; """from index i to index j""" if index_j == index_i: """do nothing""" # print("\n j and i are the same index") else: for k in array[index_i:index_j]: #print("\n k loop ********************") local_max_sum += k #print("\n sum:", local_max_sum) if local_max_sum > global_max_sum: global_max_sum = local_max_sum index_j+=1 index_i+=1 return global_max_sum def quadratic_algorithm_1(array): global_max_sum = 0; index_i = 0; for i in array: local_max_sum = 0; #print("\n ******************************************************* value i:", i) for j in array[index_i:len(array)]: # print("\n", array[index_i:len(array)]) local_max_sum += j if local_max_sum > global_max_sum: global_max_sum = local_max_sum index_i+=1 return global_max_sum def quadratic_algorithm_2(array): global_max_sum = 0 local_sum = 0 """Preprocess the cumulative sums of the array in linear time""" cumulative_sums_array = [0] * len(array) for i in range(1, len(array)): cumulative_sums_array[i] = cumulative_sums_array[i-1] + array[i] for i in range(len(array)): for j in range(i,len(array)): #print("\n", j) local_sum = cumulative_sums_array[j] - cumulative_sums_array[i-1] #print("\n local sum", local_sum) if local_sum > global_max_sum: global_max_sum = local_sum return global_max_sum def divide_and_conquer_algorithm(array): global_max_sum = 0 global_max_sum = subarray_max_sum(array, 0, len(array)-1) return global_max_sum def subarray_max_sum(subarray, start, end): if start == end: return subarray[start] mid = (start+end)//2 #recursive calls on left, right, and middle possible subarrays left_max_sum = subarray_max_sum(subarray, start, mid) right_max_sum = subarray_max_sum(subarray, mid+1, end) middle_max_sum = middle_subarray_max_sum(subarray, start, mid, end) return max(left_max_sum, right_max_sum, middle_max_sum) def middle_subarray_max_sum(subarray, start, mid, end): left_sum = 0 left_max_sum = 0 right_sum = 0 right_max_sum = 0 #recursively go from mid to left/start for i in range(mid, start-1, -1): left_sum += subarray[i] if left_max_sum < left_sum: left_max_sum = left_sum #recursively go from mid to right/end for i in range(mid+1, end+1) : right_sum += subarray[i] if right_max_sum < right_sum: right_max_sum = right_sum #sum is max for all subarrays that 'cross' the middle return left_max_sum + right_max_sum def linear_algorithm(array): local_max_sum = 0 global_max_sum = 0 for i in array: local_max_sum += i if local_max_sum < 0: local_max_sum = 0 elif global_max_sum < local_max_sum: global_max_sum = local_max_sum return global_max_sum #result = quadratic_algorithm_1([ 5, -3, -7, -2, 4, 2, 9, -6, -4, 8, 3]) #result = cubic_algorithm([ 5, -3, -7, -2, 4, 2, 9, -6, -4, 8, 3]) #result = linear_algorithm([ 5, -3, -7, -2, 4, 2, 9, -6, -4, 8, 3]) #result = divide_and_conquer_algorithm([ 5, -3, -7, -2, 4, 2, 9, -6, -4, 8, 3]) #result = quadratic_algorithm_2([ 5, -3, -7, -2, 4, 2, 9, -6, -4, 8, 3]) #print(result)
def primeChecker(num, printPrime = False): isPrime = True factors = [1] for x in range(2,(num-1)): if num % x == 0: factors.append(x) isPrime = False factors.append(num) if printPrime == True: if isPrime == True: print(str(num) + ' is Prime!!!') print(factors) return True elif isPrime == False: print(str(num) + ' is Not Prime') print(factors) return False elif printPrime == False: if isPrime == True: return True elif isPrime == False: return False for x in range(2,num): if primeChecker(x,True) == True: print(x) factors = [1] for x in range(2,(num-1)): if num % x == 0: factors.append(x) factors.append(num) if isEven(len(factors)) == True: pass elif isEven(len(factors)) == False: factors.append(statistics.median(factors)) factors = sorted(factors) factors = list(chunks(factors,(int(len(factors)/2)))) fac1 = factors[0] fac2 = list(reversed(factors[1])) mulFac = dict(zip(fac1,fac2)) pprint.pprint(mulFac)
# Autor: Roberto Emmanuel González Muñoz A01376803 # Programa que combina letras checa si tiene vocales, # forma un nombre de usuario y checa si un nombre esta escrito correctamente. def combinarLetras(cadena): counter = 0 cadenaB = [] for i in range(len(cadena)): counter += 1 if counter % 2 == 0: letra = cadena[i].lower() cadenaB.append(letra) else: letra = cadena[i].upper() cadenaB.append(letra) cadenaS = (cadenaB[0]+cadenaB[1]+cadenaB[2]+cadenaB[3]+cadenaB[4]+cadenaB[5]+cadenaB[6] +cadenaB[7]+cadenaB[8]+cadenaB[9]) print(cadenaS) return cadenaS def contieneLasVocales(cadena): cadena = cadena.lower() a = cadena.find("a") e = cadena.find("e") i = cadena.find("i") o = cadena.find("o") u = cadena.find("u") if (a != -1) and (e != -1) and (i != -1) and (o != -1) and (u != -1): return True else: return False def formarNombreUsuario(nombre): n = nombre.lower() nombreUsuario = n.split() nombre = nombreUsuario[0] apellido = nombreUsuario[1] matricula = nombreUsuario[2] usuario = (nombre[0:3])+(apellido[0:3])+(matricula[5:8]) return usuario def esCorrecto(cadenaNombre): cadenaSplit =cadenaNombre.split() nombre = cadenaSplit[0] apellido1 = cadenaSplit[1] apellido2 = cadenaSplit[2] n = nombre[0].isupper() ap1 = apellido1[0].isupper() ap2 = apellido2[0].isupper() if (n == True) and (ap1 == True) and (ap2 == True): return True else: return False def traducirTelefono(numeroFormato): numero = numeroFormato.split("-") numeroSinFormato = [] for palabra in range(1, len(numero[1])): numeroSinFormato.append("-") for letra in numero[palabra]: if (letra == "A") or (letra == "B") or (letra == "C"): numeroSinFormato.append("2") elif (letra == "D") or (letra == "E") or (letra == "F"): numeroSinFormato.append("3") elif (letra == "G") or (letra == "H") or (letra == "I"): numeroSinFormato.append("4") elif (letra == "J") or (letra == "K") or (letra == "L"): numeroSinFormato.append("5") elif (letra == "M") or (letra == "N") or (letra == "O"): numeroSinFormato.append("6") elif (letra == "P") or (letra == "Q") or (letra == "R") or (letra == "S"): numeroSinFormato.append("7") elif (letra == "T") or (letra == "U") or (letra == "V"): numeroSinFormato.append("8") elif (letra == "W") or (letra == "X") or (letra == "Y") or (letra == "Z"): numeroSinFormato.append("9") numeroFinal = numero[0]+numeroSinFormato[0] + numeroSinFormato[1] + numeroSinFormato[2] + numeroSinFormato[3] + numeroSinFormato[4] + numeroSinFormato[5] + numeroSinFormato[6] + numeroSinFormato[7]+ numeroSinFormato[8] print(numeroFinal) return numeroFinal def esValido(password): if len(password) >= 8: if password.isupper() and password.islower() and password.isalpha() and password.startswith(str): for i in range(160, 255): if password.count(chr(i)) >= 1: return True else: return False def main(): cadena = "Hola mundo" nombreUsuario = "Roberto González 01376803" cadenaNombre2Apellidos = "Roberto González Muñoz" numeroTelefonico = "01800-VOY-BIEN" password = "Abcd-7635" # True, if abcd1936 False. combinarLetras(cadena) vocales = contieneLasVocales(cadena) usuario = formarNombreUsuario(nombreUsuario) es = esCorrecto(cadenaNombre2Apellidos) traducirTelefono(numeroTelefonico) # Formato "01800-XXX-XXXX" X = son letras esValido(password) print(vocales) print(usuario) print(es) main()
# Import the necessary package to process data in JSON format try: import json except ImportError: import simplejson as json # We use the file saved from last step as example tweets_filename = raw_input("file name: ") tweets_file = open(tweets_filename, "r") #output_file = open("test_converted.txt", "w") #total_counts = 0 count = 0 for line in tweets_file: #total_counts += 1 try: # Read in one line of the file, convert it into a json object tweet = json.loads(line.strip()) #output_file.write(str(count)) #output_file.write("\n") # output a new line if ('text' in tweet) and (tweet['lang'] == 'en'): # only messages contains 'text' field is a tweet count += 1 #output_file.write(str(tweet['id'])) # This is the tweet's id #output_file.write(str(tweet['created_at'])) # when the tweet posted #output_file.write(str(tweet['text'])) # content of the tweet #output_file.write(str(tweet['user']['id'])) # id of the user who posted the tweet #output_file.write(str(tweet['user']['name'])) # name of the user, e.g. "Wei Xu" #output_file.write(str(tweet['user']['screen_name'])) # name of the user account, e.g. "cocoweixu" print count print tweet['user']['screen_name'] print tweet['created_at'] print tweet['text'] hashtags = [] for hashtag in tweet['entities']['hashtags']: hashtags.append(hashtag['text']) #output_file.write(str(hashtags)) if hastags != []: print hashtags except: # read in a line is not in JSON format (sometimes error occured) continue #output_file.write("\n") #output_file.close() tweets_file.close() print "Total tweets processed: %s"%(count) #print "Total tweets processed: %s"%(total_counts)
def RepresentsInt(s): try: int(s) return True except ValueError: return False n=input() for i in range(n): s=raw_input() s=raw_input() s=s.split() # print s if RepresentsInt(s[0]) and RepresentsInt(s[2]): print s[0]+' + '+s[2]+' = '+str(int(s[0])+int(s[2])) elif RepresentsInt(s[0]) and RepresentsInt(s[4]): t=int(s[4])-int(s[0]) print s[0]+' + '+str(t)+' = '+s[4] else: t=int(s[4])-int(s[2]) print str(t)+' + '+s[2]+' = '+s[4] # s=raw_input()
def cnt(n,i,l): if i==n: return 1 else: if l==1: return cnt(n,i+1,3) elif l==3: return cnt(n,i+1,1)+cnt(n,i+1,5) elif l==5: return cnt(n,i+1,7) elif l==7: return cnt(n,i+1,5)+cnt(n,i+1,3) t=input() while t: t-=1 a=input() print cnt(a,1,1)+cnt(a,1,3)+cnt(a,1,5)+cnt(a,1,7)
s = "Ola Mundo"; print(s) num1 = 10 num2 = 20 if num1 > num2: print("Número 1 é > que Número 2") else: print("N2 > que N1")
neerslag = input("Geef de hoeveelheid neerslag (overvloed, veel, matig, geen): ") dagen = 7 templist = [] neerslagen = [] laagste = 50 som = 0 veel = False while dagen != 0 and neerslag != "overvloed": dagen -= 1 temperatuur = int(input("Geef de temperatuur (gehele getallen): ")) templist.append(temperatuur) neerslagen.append(neerslag) if temperatuur < laagste: laagste = temperatuur som += temperatuur if neerslag == "veel": veel = True neerslag = input("Geef de hoeveelheid neerslag (overvloed, veel, matig, geen): ") print("dag\ttemperatuur\tneerslag") for i in range(len(templist)): print(i+1,"\t\t", templist[i], "\t", neerslagen[i]) if neerslag == "overvloed": print("We blijven thuis.") else: gemiddelde = som/len(templist) if not veel and laagste >= 15 and laagste > 0.2 * gemiddelde: print("we gaan op 2daagse") else: print("We gaan op daguitstap")
fahrenheit = float(input("Geef het aantal graden fahrenheit: ")) celcius = (fahrenheit -32) / (9/5) print(int(celcius*10 + 0.5) / 10)
list = [] text = input("Geef een tekst: ") text = text.lower() for letter in text: if ord(letter) >= ord("a") and ord(letter) <= ord("z"): list.append(letter) list.sort() teller = 1 for letter in list: while list.count(letter) > 1: list.remove(letter) teller += 1 print(letter,"komt", teller, "keer voor") teller = 1
afstand = 36 inschrijvingsnummer = int(input("geef het inschrijvingsnummer: ")) tijd = int(input("tijd in seconden: ")) langer_dan_uur = 0 snelste_tijd = tijd teller = 0 while inschrijvingsnummer >= 0: teller += 1 if tijd >=3600: langer_dan_uur += 1 if tijd < snelste_tijd: snelste = inschrijvingsnummer inschrijvingsnummer = int(input("geef het inschrijvingsnummer: ")) tijd = int(input("tijd in seconden: ")) print("De snelste renner is de renner met inschrijvingsnummer: ", snelste, "in", snelste_tijd, "seconden") print("Het percentage van de renners dat er langer dan 1 uur over doet is",langer_dan_uur/teller*100 )
def betpaal_vervoer(code): if code == 1: vervoer = "met de bus" elif code == 2: vervoer = "te voet" elif code == 3: vervoer = "met de trein" else: vervoer = "met de auto" return vervoer teller_auto = 0 minumum = 3600 #Hoog getal omdat het altijd lager gaat zijn, Grote waarde om kleinste getal zeker te vinden. teller = 0 som = 0 code = int(input("Geef de code in, code:1 = met de bus, 2 = te voet, 3 = met de trein, 4 = met de auto en 0 om te eindigen ")) while code != 0: if code >= 1 and code <= 4: tijd = int(input("Geef de tijd in minuten ")) som = som + tijd teller +=1 if tijd < minumum: minumum = tijd minimum_vervoer = code if code == 4: teller_auto += 1 else: print("Foute code! opnieuw") code = int(input("Geef de code in, code:1 = met de bus, 2 = te voet, 3 = met de trein, 4 = met de auto en 0 om te eindigen ")) if teller == 0: #als je het allereerste cijfer een nul geeft print("Geen gegevens ingegeven") else: gemiddelde = som / teller print("De gemiddelde duur is ", gemiddelde) print("De kleinste tijd is ", minimum, "minuten") print("de kleinste tijd is ", minumum, "minuten") print("Dit was ", vervoer(minimum_vervoer)) percentage = teller_auto / teller * 100 print("Het percentage dat met de auto komt is ", percentage)
brutoloon = int(input("Geef het brutoloon: ")) jaarlijks_vakantiegeld = 0.05*brutoloon if jaarlijks_vakantiegeld >= 350: jaarlijkse_bijdrage = 0.08*350 else: jaarlijkse_bijdrage = 0.08 * jaarlijks_vakantiegeld print("Brutoloon = ",brutoloon, "vakantiegeld = ",jaarlijks_vakantiegeld, "jaarlijkse bijdrage = ",jaarlijkse_bijdrage)
tekst = input("Geef een tekst: ") positie = tekst.lower().find("t") if positie == -1: print("geen letter T in tekst") else: if len(tekst) % 2 != 0: tekst = tekst[:positie] + tekst[positie:].upper() else: tekst = tekst[:positie] + tekst[positie:].lower() print(tekst)
for i in range(-10, 11, 1): if i > 0: print("+" + (str(i))) else: print(i) #efficienter: for i in range(-10,1): print(i) for i in range(1,11): print("+"+str(i))
getallenlijst = [] getal = int(input("geef getal, 0 om te stoppen: ")) while getal != 0: if getal not in getallenlijst: getallenlijst.append(getal) else: print(getal, "komt voor op plaats", getallenlijst.index(getal)) getallenlijst.remove(getal) getal = int(input("Geef een getal, 0 om te stoppen: ")) print(getallenlijst)
def ZetOmNaarRomeinsCijfer(getal, romeins, cijfer): uitkomst = 0 for i in range(len(waarde)): aantal = getal // waarde[i] getal = getal % cijfer[i] uitkomst += aantal * romeins[i] return uitkomst from random import randint roman = ["XL", "X", "IX", "V", "IV", "I"] waarde = [40, 10, 9, 5, 4, 1] tekst = ["minder dan 50", "tussen 50 en 70", "tussen 70 en 90", "van 90 of meer"] letter = input("Geef letter: ").lower() for ascii in range(ord("a"), ord(letter) + 1): print("Reeks", chr(ascii)) getal1 = randint(1, 49) print("Het romeinse cijfer voor", getal1, "is", ZetOmNaarRomeinsCijfer(getal1,roman,waarde)) getal2 = randint(1, 49) while getal2 > getal1: getal1 = getal2 print("Het romeinse cijfer voor", getal1, "is", ZetOmNaarRomeinsCijfer(getal1, roman, waarde)) getal2 = randint(1, 49)
# Exercises from book chapter 3 # 1. List of diary products dairy_section = ['Cheese', 'Milk', 'Butter', 'Cream'] # 2. Print first and last element first = dairy_section[0] last = dairy_section[len(dairy_section)-1] print("First is %s, Last is %s" % (first, last)) # 3. Tuple with expiration date parts milk_expiration = (12, 10, 2009) # 4. Print values from the tuple print("This milk carton will expire on %d/%d/%d" % (milk_expiration[0], milk_expiration[1], milk_expiration[2])) # 5. Create dictionary milk_carton = { "expiration_date" : milk_expiration, "fl_oz" : 12, "cost" : 2, "brand_name" : "unknown" } # 6. Print values of all dictionary elements for i in milk_carton: print("%s: %s" % (i, milk_carton[i])) # 7. Calculate cost of six cartons of milk number = 6 print("Cost of six cartons of milk is %d" % (number*milk_carton["cost"])) # 8. Create list of cheeses and append to dairy_section cheeses = ["Emmentaler", "Gouda", "Edam"] dairy_section.extend(cheeses) print(dairy_section) for i in cheeses: dairy_section.remove(i) print(dairy_section) # 9. Count number of cheeses in the list print("Number of cheeses is %d" % len(cheeses)) # 10. First five letters of first cheese first_cheese = cheeses[0] print("First five letters of first cheese are: %s" % first_cheese[0:5])
''' Three parts to list comprehension 1. the loop 2. the transformation 3. filtering ''' mylist = [1, 2, 3, 4, 5] modlist = [] for i in mylist: j = i * 2 modlist.append(j) print(modlist) mylist = [100, 200, 300, 400, 500] r, t = 10, 1 #modlist = [lambda p: p*t*r/100 for p in mylist] #print(modlist) line = [line.strip() for line in open('listComp-1.py') if not line.startswith('#')] print(line)
import re text_to_search = ''' Regular Expressions Basics 1. Always safer to use raw strings (r'' | r""). Tells Python not to handle special characters in any way And rather pass the string as it is to the objects r'' on patterns doesn't have any impact 2. re.match() matches starting at the beginning of a string and upto \n. It does not go to next lines in the string. 3. re.search() matches first occurance of the pattern anywhere in the string. Even \n in the string will result in the search 4. match and search returns None if no match else Objects. 5. Retrieve captured matches via group method on the match object. 6. re.findall() all matches to a pattern. Returns list of match objects. Outputs the group captures. If multiple then as tuples. 7. With captured expressions re.findall() returns list of tuples, the tuples being the captures. 8. re.sub(). Replaces all instances of a pattern by default. Use max parameter to specify number of instance to replace. 9. To make re.search() case insensitive re.I as final argument. 10. re.compile(); Convert patters into a variable and reuse it across many times. 11. re.finditer(), Good tool for finding matches and gets more information 12. re.compile(pattern, re.IGNORECASE|re.MULTILINE) . \d, \D, \w, \W, \s, \S - Metachars \b, \B, ^, $ - Boundary [], [^], Characters in the bracket; ^ inverse and - between characters. * ,+, ? {3} {3,4} are quantifiers MetaCharacters: . ^ $ * + ? {} [] | \ () Mr. Tab Mr Shah Mr. B Mrs. Kelly Woll Mrs Taara Ms Rita Raf 800-666-2222 900-666-2222 https://www.google.com http://coreyms.com https://youtube.com https://www.nasa.gov ''' sentence = "Start a sentence and then bring it to an end" re.search('Start', sentence).group() re.match('Start', sentence).group() bool(re.match('Start', sentence).group()) ;#None when match is fail. #pattern = re.compile(r'(\w+)(se)(?:\w+)?') #pattern = re.compile(r'(^Start)') #pattern = re.compile(r'(\d{3})[-.](\d{3})[-.](\d{4})') #pattern = re.compile(r'[89]00[-.](\d{3})[-.](\d{4})') #pattern = re.compile(r'(Mr|Mrs|Ms)\.?\s[A-Z]\w*( [A-Z]\w*)') pattern = re.compile(r'https?://(www.)?([A-Za-z0-9_.-]+)(\.(com|gov))') subbed_urls = pattern.sub(r'\2\3', text_to_search) print(subbed_urls) #print(text_to_search) matches = pattern.finditer(text_to_search) #matches = pattern.finditer(sentence) for match in matches: #print(type(match)) #print(dir(match)) #print(len(match.groups())) #print(match.group(2)) print(f'{match.group(2)}{match.group(3)}') ''' with open('data.txt', 'r') as f: contents = f.read() matches = pattern.finditer(contents) for match in matches: print(match) a, b = match.span() print(contents[a:b]) '''
""" File: Sqr_mult_logic Name: Matt Robinson Description: This file is going to just be a test to see if I can successful write a program to do SQR and MULT for me Language: Python """ def square_and_multiply(base, exponent, modulo): """ Function: square_and_multiply Description: The main logic for the Square and Multiply Algorithm. Prints out the final value to the console :param base: The base of the number :param exponent: The exponent that the base is raised to :param modulo: The modulo for reduction :return: None """ binary_exponent = convert_to_binary(exponent) value = base # 1 - Square and Multiply # 0 - Square only for step in binary_exponent: if step == '1': value = multiply(square(value), base) else: value = square(value) value = value % modulo print(value) def convert_to_binary(exponent): """ Function: convert_to_binary Description: Takes in a number and returns its binary representation :param exponent: The number to be converted to binary :return: The binary representation of the exponent parameter """ binary = bin(exponent).split("b")[1][1:] return binary def square(number): """ Function: square Description: Takes in a number and squares it :param number: The number to be squared :return: The result of squaring the number parameter """ return number**2 def multiply(value, base): """ Function: multiply Description: Multiplies the current value by the base number :param value: The current value of the number at the given step :param base: The original base for the number :return: The result of value multiplied by base """ return value * base if __name__ == '__main__': square_and_multiply(12345, 6789, 143)
import sys def read_file(file): item_list = [] with open(file) as f: for line in f: line_lst = [int(x) for x in line.split(' ')] item_list.append(line_lst) return item_list def return_max_value_knapsack(items, weight): n = len(items) w = weight + 1 a = [0 for i in range(w)] for i in range(1, n): temp = [] for j in range(w): ci_w = items[i][1] ci_v = items[i][0] pv_at_w = a[j] cv_w_item = a[j-ci_w] + ci_v if ci_w <= j else 0 max_value = max(pv_at_w,cv_w_item) temp.append(max_value) a = list(temp) return a[w-1] if __name__ == '__main__': items = read_file(sys.argv[1]) result = return_max_value_knapsack(items, items[0][0]) print(result)
str = input('Enter the string:- ') new_str = str[::-1] print(new_str)
from random import randrange n = int(input('Enter no of times the coin should be tossed: ')) h = 0 t = 0 for i in range (1, n+1): s = randrange(2) if s == 0: h += 1 else: t += 1 print('Head:- ',h) print('Tail:- ',t)
print("factorial(!)") print("enter a number") x=int(input()) product=1 if x==0: product=1 if x==1: product=1 while x>1: product=product*x x=x-1 print("factorial is ",product) m=input("\n press the enter key to exit")
import os import yaml import logging def yaml_file_to_dict(config_file, base_config=None): """ Adds extra configuration information to given base_config """ # validate input base_config = base_config or {} if not os.path.exists(config_file): raise SystemExit("Extra config file not found: {}".format(config_file)) # load config from yaml extra_config = yaml.load(open(config_file, 'r')) # return base config enriched (and overriden) with yaml config return {**base_config, **extra_config} def yaml_include(): """ Defining necessary to allow usage of "!include" in YAML files. Given path to include file can be relative to : - Python script location - YAML file from which "include" is done This can be use to include a value for a key. This value can be just a string or a complex (hiearchical) YAML file. Ex: my_key: !include file/with/value.yml """ def _yaml_loader(loader, node): local_file = os.path.join(os.path.dirname(loader.stream.name), node.value) # if file to include exists with given valu if os.path.exists(node.value): include_file = node.value # if file exists with relative path to current YAML file elif os.path.exists(local_file): include_file = local_file else: error_message = "YAML include in '{}' - file to include doesn't exists: {}".format( loader.stream.name, node.value) logging.error(error_message) raise ValueError(error_message) with open(include_file) as inputfile: return yaml.load(inputfile) return _yaml_loader def yaml_from_csv(csv_dict): """ Defining necessary to retrieve a value (given by field name) from a dict Ex (in YAML file): my_key: !from_csv field_name """ def _yaml_loader(loader, node, csv_dict=csv_dict): # If value not exists, store the error if csv_dict.get(node.value, None) is None: logging.error( "YAML file CSV reference '%s' missing. Can be given with option \ '--extra-config=<YAML>'. YAML content example: '%s: <value>'", node.value, node.value) # We don't replace value because we can't... return node.value else: # No error, we return the value return csv_dict[node.value] return _yaml_loader
# -*- coding: utf-8 -*- """ Created on Wed Oct 7 20:25:41 2020 @author: JOliv """ #PANDAS #Instalacion de Pandas #!pip install pandas #!pip install numpy import pandas as pd import numpy as np """ NOTA IMPORTANTE: si alguna linea no hace nada aparentemente, correr con f9 """ #%% """ SERIES Las series son arreglos de una sola dimension, y se pueden crea a partir de objetos como tuplas, listas, diccionarios o arrays. La caracteristica fundamental de las series es que las observaciones las acomoda con un indice o un vector de posicion. """ serie1 = pd.Series(np.random.rand(8)) print(serie1) #Construye un cuadro con 8 numeros aleatorios indexados serie2 = pd.Series(np.random.rand(8), name = 'mi primer serie') print(serie2) #Le damos un nombre a la columna #%% Acceder a los indices print(serie1[5]) print(serie2[7]) #Se puede modificar la numeracion de los indices para mayor comodidad serie2 = pd.Series(np.random.rand(8), index=range(1,9), name='mi segunda serie') print(serie2) #De esta forma los indices ya no comienzan desde 0 sino desde 1 #Se tiene total control sobre los indices serie3 = pd.Series(np.random.rand(5), index = [3,6,2,8,5]) print(serie3) print(serie3[2]) #De hecho podemos hacer que los indices sean strings serie4 = pd.Series(np.random.rand(5), index = ['a', 'b', 'c', 'd', 'e']) print(serie4) print(serie4['d']) #Creando un serie a partir de un diccionario diccionario = {'Nombre':['Jorge', 'Oliver'], 'Apellido' :['Perez', 'Espinoza']} seriedic = pd.Series(diccionario) print(seriedic) #La estructura de las series son la base de los Dataframes #%% """ DATAFRAMES Los dataframes son una estructura nativa de R, muy util para el analisis de datos Una de sus caracteristicas más importantes y utiles es que no es necesario que sus columnas sean del mismo type. A las columnas se les llama campos A las filas se les llama registros Otra caracteristica fundamental es que todos los campos deben tener el mismo numero de registros. Se puede contruir df a partir de dict, tuples, arrays . Por default, tanto el nombre de los campos como los registros python los construye con valores numericos empezando desde el 0 De manera técnica, cada columna de un df es una serie """ pd.DataFrame(data = [(0,1,2),(1,2,3),(2,3,4),(3,4,5)]) #Construyendo un df a partir de un dict estudiantes = {'Nombre':['Pedro', 'Pablo', 'Hugo','Paco','Luis','Juan'], 'Apellido':['Lopez','Rodriguez','Ramirez','Perez','Oca', np.nan], 'Matricula':['123456','629834','789012','345678','901234','567890'], 'Edad':[20,45,np.nan,23,10,18] } print(estudiantes) df = pd.DataFrame(data = estudiantes, index= range(1,7)) print(df) #Ademas podemos darle un nombre a cada registro en lugar de un numero registro = ["Persona1", 'Persona2','Persona3','Persona4','Persona5','Persona6'] df = pd.DataFrame(data = estudiantes, index= registro) print(df) #%% #Construyendo un df a partir de una matriz matriz = np.arange(9).reshape(3,3) df1 = pd.DataFrame(matriz) print(df1) #Reenombrando columnas e indices df1 = pd.DataFrame(matriz, index = ['uno','dos','tres'], columns=('a','b','c')) print(df1) """En el caso de diccionarios no se puede modificar el nombre de las colmnas, pues ya toma el nombre asignado en el diccionario, por lo que se debe modificar directamente el diccionario""" #%% Construyendo un df a partir de una lista de listas df3 = pd.DataFrame([['Hugo','Molina',123,20],['Mario','Lopez',234,18], ['Pablo','Carmona',345,23],['Luis','Oca',456]], index = ['Alumn1','Alumn2','Alumn3','Alumn4'], columns=['Nombre','Apellido','Matricula','Edad']) print(df3) #%%ACCEDIENDO A LOS ELEMENTOS DE UN DF #Accediendo a una columna print(df3['Nombre']) print(df3['Edad']) #Accediendo a más de una columna print(df3[['Nombre', 'Matricula']]) #Accediendo a registros df3.loc[['Alumn1','Alumn3']] #Accediendo a un registro mediante su indice df3.iloc[0] df3.iloc[1] #Accediendo a valores puntuales print(df3.loc[['Alumn2']] [['Matricula']]) print(df3.loc[['Alumn1','Alumn4']] [['Matricula','Edad']]) #%% OPERACIONES con DF #Creando un nuevo campo a partir de otros ya existentes df3['NombreCompleto'] = df3['Nombre'] + " " + df3["Apellido"] print(df3) #%% Eliminar columnas df3.drop("NombreCompleto", axis=1, inplace=False) print(df3) df3.drop("NombreCompleto", axis=1, inplace= True) print(df3) """ axis indica donde debe buscar NombreCompleto: 0 = filas 1 = columnas inplace indica si se desea modificar el df original o no: False = no modifica el original True = si modifica el original Por default el inplace está en False para no perder los valores """ #%% Indexar numericamente los registros df3.reset_index(inplace = True) print(df3) """ Lo que hace es indexar de nuevo el df desde 0, sin embargo no borra el nombre de los registros anteriores, sino que los convierte en una nueva columna. Recordar la funcion inplace """ #Accediendo a valores puntuales despues del reset_index df3.loc[[0,3],['Nombre','Matricula']] #%%FILTROS """ Muy util a la hora de trabajar con grandes bases de datos """ df3['Edad'] > 20 #Nos devuelve un bool, sin embargo parece más util la sig linea df3[df3['Edad'] > 20] #Este si nos devuelve el registro completo #Si solo necesitamos ciertos campos podemos utilizar lo siguiente df3[df3['Edad'] >20 ][['Nombre','Matricula','Edad']] print(df3) #%%Cambiar el nombre de las columnas print(df3) df3.columns = ['Campo1','Campo2','Campo3','Campo4', 'Campo5'] print(df3) #%%Utilizar un campo como ID #En nuestro ejemplo el unico campo que nos sirve como ID es la matricula df3.index = df3['Campo4'] print(df3) #%%Agregar un registro #Separar los datos NuevoRegistro = "Alumn5, Helena, Gonzales, 888, 22" NuevoRegistro.split(",") df3.loc[888]=NuevoRegistro.split(",") print(df3) """ split actua como un separador, en este ejemplo separa todo el str en partes cuando encuentra una coma y cada parte es el valor de cada una de las columnas Cabe resaltar que tanto la edad como la Matricula son datos str por lo que más adelante se pueden complicar algunas operaciones.Son str porque asi agregamos el ultimo registro. Más adelante se verá como corregirlo """ print(df3.iloc[-1]) #%%VISUALIZANDO df #Encabezado df3.head() #Por default muestra los primeros 5 registros df3.head(3) #Tambien puede mostrar los ultimos df3.tail(2) df3.head() #Por default muestra los ultimos 5 #%% Resolucion de problemas comunes con los dataframe #MODIFICANDO EL type #Si quisieramos calcular el promedio de la edad df3['Campo5'].mean() #Marca un error porque la edad del ultimo registo es un str y no un float """ ahora si, si queremos hacer operaciones con la edad debemos modificar el tipo de dato """ #Verificamos que evidentemente es un str type(df3.iloc[4]['Campo5']) #Modificando el tipo de dato df3['Campo5'] = pd.to_numeric(df3['Campo5'], downcast='float') #Comprobamos se haya cambiado type(df3.iloc[4]['Campo5']) #Entonces ahora si podemos calcular la media de la edad df3['Campo5'].mean() #%% Espacios de más a la hora de agregar registros df3['Campo5'].value_counts() #Muestra la frecuencia de las edades #Agregamos un nuevo registro (Esta es una forma más comun de agregar registros) df3.loc[777] = ['Alumn6','Jose','Lopez','777',30] print(df3) df3['Campo3'].value_counts() #Observar que Gonzales tiene una sangría distinta, eso se debe a que lo agregamos #Con ese espacio de más, para eso debemos volver desde que agregamos el registro y eliminarlo #%% SUSTITUCION DE NaN #Ordenar el df por valores print(df3) df3.sort_values(by = 'Campo5', inplace = True, ascending = False) print(df3) """ En ocaciones nuestras bases de datos contienen varios NaN con los que se complica trabajar, cuando es un campo numerico es comun es sustituirlos por el valor promedio del campo """ #Calculamos y guardamos el valor promedio de la edad edadMedia = df3['Campo5'].mean() float(edadMedia) #Sustituimos df3['Campo5'].fillna(float(edadMedia), inplace = True) print(df3) #%%ORDENAR DF #Si ahora quisieramos ordenar el df por indices df3.sort_index(ascending = True, inplace = True) print(df3) #Ordenando el df con dos parametros df3.sort_values(by = ['Campo3', 'Campo5'], ascending= [True,False], inplace= True) print(df3) #Ordena primero por campo3, si hay repetidos entonces toma el segundo criterio de ordenamiento #%% Metodos varios #Filtrar los Registros de los estudiantes que se apelliden Lopez df3[df3['Campo3'] == 'Lopez'] #Convertir a mayuscular los valores de una columna df3['Campo2'] = df3['Campo2'].str.upper() print(df3) #Mostrar la longitud de un determinado campo df3['Campo3'].str.len() #%%AÑADIR REGISTROS Y COLUMNAS #Agregamos un nuevo registro df3.loc[999] = ['Alumn7', 'Luisa', 'Gonzales', '999', 23] #Agregamos un nuevo campo y sus respectivos valores df3['Estado']= ['Activo', 'Baja', 'Baja','Graduado', 'Activo', 'Activo', 'Baja'] print(df3) #%% COLUMNAS DUMMIES """ Las variables dummies son variables categoricas y toman valores unicamente 0 y 1 0 = No cumple con la condicion 1 = Cumple con la condicion """ #Creamos la columna dummie pd.get_dummies(df3['Estado']) #POdemos PEGAR o agregarla a nuestro Dataframe Frame = pd.concat([df3,pd.get_dummies(df3['Estado'])], axis=1) print(Frame) #Agregamos una nueva colmna a nuestro df Frame['Fac'] = [4,3,1,4,5,1,8] Frame['Sexo']= ['0','1','1','1','1','1','0'] print(Frame) #%% #Agrupando """ No me queda claro la interpretacion del Factor o Fac, sin embargo, se sabe que es de vital importancia para la Ciencia de Datos """ Frame.groupby('Estado')['Fac'].sum() Frame.groupby(['Estado', 'Sexo'])['Fac'].sum() Frame.groupby(['Estado', 'Sexo'])['Fac'].sum()['Activo', '0'] #Resumen Frame.describe() Frame['Sexo'].describe() Frame.info() #%% #LECTURA Y ESCRITURA DE CSV """ Un archivo CSV (Comma separated values)es un tipo de documento en forma de tabla cuyos valores estan separados por comas (,) como su nombre lo indica. Pueden contener valores de diferente type. """ #Lectura ejemplo = pd.read_csv("https://raw.githubusercontent.com/AAProgramand/datasets/master/degrees.csv") ejemplo.head() #Escritura #creamos un df df = pd.DataFrame({'Nombre':['a','b','c'], 'Número': [1,2,3]}) #Convertimos nuestro df en un csv df.to_csv("C:/Users/JOliv/OneDrive/Documentos/Python/SciData/DS/primercsv.csv",index=True,header=True,encoding='latin') #Aqui se agrega la direccion y el nombre con que guardaremos nuestro csv """ index es un booleano para saber si imprimir o no los índices header es un booleano para saber si imprimir o no los nombres de los campos encoding es un string que permite usar la codificación del "idioma" que se usaré. Por default es "UTF-8"; se recomienda tenerlo en "latin" para poder usar acentos. """ #%% #CONCATENACION df1 = pd.DataFrame({'A':['A0','A1','A2','A3'], 'B':['B0','B1','B2','B3'], 'C':['C0','C1','C2','C3'], 'D':['D0','D1','D2','D3']}) print(df1) df2 = pd.DataFrame({'A':['A4','A5','A6','A7'], 'B':['B4','B5','B6','B7'], 'C':['C4','C5','C6','C7'], 'D':['D4','D5','D6','D7']}) print(df2) df3 = pd.DataFrame({'A':['A8','A9','A10','A11','A12'], 'B':['B8','B9','B10','B11','B12'], 'C':['C8','C9','C10','C11','C12']}) print(df3) #Concatenado vertical df_columnas = pd.concat([df1,df2,df3], axis=0) df_columnas # df_columnas = pd.concat([df1,df2,df3], axis=0, keys=['df1','df2','df3']) df_columnas df_columnas.loc['df2'] df_columnas.loc['df2'].iloc[1] #Concatenacion Horizontal dfHorizontal = pd.concat([df1,df2,df3], axis = 1, keys=['df1','df2','df3']) print(dfHorizontal) #Si queremos modificar los indices de una tabla df3.index=[2,5,3,4,10] print(df3) #Sin embargo eso modificaria nuestro df a la hora de pegarlo dfHorizontal = pd.concat([df1,df2,df3], axis = 1, keys=['df1','df2','df3']) print(dfHorizontal) #%% JOINS izquierda = pd.DataFrame({'A':['A0','A1','A2','A3'], 'B':['B0','B1','B2','B3'], 'C':['C0','C1','C2','C3'], }, index=['clv0','clv1','clv2','clv3']) print(izquierda) derecha = pd.DataFrame({'D':['D0','D1','D2','D3','D4'], 'E':['E0','E1','E2','E3','E4']}, index=['clv0','clv2','clv1','clv5','clv6']) print(derecha) #Creamos una nueva columna en cada uno de los df izquierda['col_joinIzq']= izquierda.index derecha['col_joinDer']= derecha.index #%% # METODOS de los JOINS #Inner Join (intercepcion) joinInt= izquierda.join(derecha.set_index(['col_joinDer']), on=['col_joinIzq'], how='inner') print(joinInt) #Nos muestra los registros de los id (col_join) que coinciden en ambos df #Lo podemos ver como conjuntos o sets de la siguiente forma set(izquierda['col_joinIzq']).intersection(set(derecha['col_joinDer'])) #Modificamos el df derecha derecha = pd.DataFrame({'D':['D0','D1','D2','D3','D4','F4'], 'E':['E0','E1','E2','E3','E4','G5']}, index=['clv0','clv2','clv1','clv5','clv6', 'clv1']) #Con la modificacion a derecha, podemos notar que el id clv1 está repetido.¿que sucede aqui? joinInt_modif= izquierda.join(derecha.set_index(['col_joinDer']), on=['col_joinIzq'], how='inner') print(joinInt_modif) #Muestra ambos registros de clv1 #Ahora que pasaría si tuvieramos columnas de nombres iguales #Modificamos izquierda izquierda = pd.DataFrame({'D':['A0','A1','A2','A3'], 'B':['B0','B1','B2','B3'], 'C':['C0','C1','C2','C3'], }, index=['clv0','clv1','clv2','clv3']) print(izquierda) join0 = izquierda.join(derecha.set_index(['col_joinDer']),on=['col_joinIzq'],how='inner' ) print(join0) #Nos marca un error por que no pueden haber dos columnas del mismo nombre #Se puede corregir con suffix, el cual añade un sufijo a la columna repetida join0 = izquierda.join(derecha.set_index(['col_joinDer']),on=['col_joinIzq'],how='inner',rsuffix='der' ) print(join0) #%% join_izquierdo = izquierda.join(derecha.set_index(['col_joinDer']), on=['col_joinIzq'], how='left', rsuffix='der') print(join_izquierdo) join_derecho = derecha.join(izquierda.set_index(['col_joinIzq']),on=['col_joinDer'], how='right', rsuffix='izq') print(join_derecho) join_completo=izquierda.join(derecha.set_index(['col_joinDer']),on=['col_joinIzq'],how='outer',lsuffix='der') print(join_completo)
import numpy as np import cv2 ## Black Image and displaying it ## black = np.zeros([200,200,1], "uint8") cv2.imshow("Black Image", black) print("pixel value in black image is", black[0,0]) ## Black Image with three channels and displaying it ## ones = np.ones([200,200,3], "uint8") cv2.imshow("Ones", ones) print("pixel value in ones image is", ones[0,0]) ## White Image and displaying it ## white = np.ones([200,200,3],"uint8") white *= (2**16-1) cv2.imshow("White", white) print("Pixel value in white image is", white[0,0]) ## Blue Image and displaying it ## blue = np.ones([200,200,3], "uint8") blue[:,:] = (255,0,0) cv2.imshow("Blue", blue) print("Pixel value in Blue Image is", blue[0,0]) cv2.waitKey(0) cv2.destroyAllWindows()
import cv2 import numpy as np image = np.ones((512,512,3), np.uint8) print(image) image[:] = 255,0,255 ################ RECTANGLE ##################### ## Deifne Rectangle with points ## cv2.rectangle(image,(0,0),(255,255),(255,255,0),3) ## Cv2.FILLED is used to fill the space of the shape ## cv2.rectangle(image,(155,155),(512,412),(255,0,0),cv2.FILLED) ############### CIRCLES ###################### ## Define Circles with origin, radius, color, thickness ## cv2.circle(image,(345,456),100,(0,0,255),5) cv2.circle(image,(112,321),250,(0,255,255),cv2.FILLED) cv2.imshow("Image", image) cv2.waitKey(0)
import cv2 cap = cv2.VideoCapture(0) color = (255,0,234) line_width = 3 radius = 100 point = (0,0) ### Initialize the Event Click ### def click (event, x, y, flags, param): global point, pressed if event == cv2.EVENT_LBUTTONDOWN: print("pressed", x,y) point = (x,y) ### Name the Window and Call the Click ## cv2.namedWindow("frame") cv2.setMouseCallback("frame", click) ### Read frame by frame ### while (True): ret, frame = cap.read() ### Draw the Circle where point is ### cv2.circle(frame, point, radius, color, line_width) cv2.imshow("frame", frame) ### Wait for the key press and "s" for Exit ### ch = cv2.waitKey(1) if ch & 0xFF == ord("s"): break cap.release() cv2.destroyAllWindows()
''' Esteban Camarillo ID#: 1636095 ''' team={} i=1 count=1 for i in range(1,6): jersey = int(input('Enter player {}\'s jersey number:\n' .format(i))) rating = int(input('Enter player {}\'s rating:\n\n' .format(i))) if jersey < 0 and jersey > 99 and rating < 0 and rating > 9: print('invalid entry') break else: team[jersey] = rating print("ROSTER") for jersey,rating in sorted(team.items()): print("Jersey number: %d, Rating: %d" % (jersey,rating)) menu_option='' #looping until user quits, your code didn't have a loop for continously displaying menu while menu_option.upper()!='Q': print('\nMENU\na - Add player\nd - Remove player\nu - Update player rating\nr - Output players above a rating\no - Output roster\nq - Quit\n') menu_option = input('Choose an option:\n') if menu_option == 'a': jersey = int(input('Enter a new player\'s jersey number:\n' .format(i))) rating = int(input('Enter the players\'s rating:' .format(i))) team[jersey] = rating elif menu_option == 'd': jersey = int(input('Enter a jersey number:')) if jersey in team.keys(): del team[jersey] elif menu_option == 'u': jersey = int(input('Enter a jersey number: ')) if jersey in team.keys(): rating = int(input('Enter a new rating for player: ')) team[jersey] = rating #completed the below two options as needed, your code for the below options were incorrect/empty elif menu_option == 'r': rating_input=int(input('Enter a rating')) print('ABOVE {}'.format(rating_input)) for jersey,rating in sorted(team.items()): if rating > rating_input: print("Jersey number: %d, Rating: %d" % (jersey,rating)) elif menu_option == 'o': #printing the entire Roster print("ROSTER") for jersey,rating in sorted(team.items()): print("Jersey number: %d, Rating: %d" % (jersey,rating))
def nama_function(name, job): print("Hi {}, your job is {}".format(name, job)) def tambah(a, b): """tambah untuk menambahkan dua bilangan a dan b""" return a + b kali = lambda x, y: x * y nama_function("Budi", "Security Consultant") print("tambah(2,5) = {}".format(tambah(2, 5))) print(tambah.__doc__) print("kali(2,5) = {}".format(kali(2, 5)))
import copy n = int(input()) a = list(map(str,input().split())) a_b = copy.deepcopy(a) a_s = copy.deepcopy(a) # バブルソート def bubble(a_b, n): for i in range(n): for j in range(n-1,i,-1): if int(a_b[j][1]) < int(a_b[j-1][1]): tmp = a_b[j] a_b[j] = a_b[j-1] a_b[j-1] = tmp return a_b # 選択ソート def selection(a, n): for i in range(n): minj = i for j in range(i, n): if int(a[j][1]) < int(a[minj][1]): minj = j tmp = a[i] a[i] = a[minj] a[minj] = tmp return a # 安定性判定 def stable(in_a, out_a, n): for i in range(n): for j in range(i+1, n): for a in range(n): for b in range(a+1,n): if in_a[i][1] == in_a[j][1] and in_a[i] == out_a[b] and in_a[j] == out_a[a]: return "Not stable" return "Stable" print(' '.join(bubble(a_b,n))) print(stable(a, bubble(a_b,n), n)) print(' '.join(selection(a_s,n))) print(stable(a, selection(a_s,n), n))
n = int(input()) ans_list = list() for i in range(1,n+1): if i % 3 == 0: ans_list.append(str(i)) elif i % 10 == 3: ans_list.append(str(i)) elif '3' in str(i): ans_list.append(str(i)) print('', ' '.join(ans_list))
''' Created on Feb 24, 2017 @author: BhavinSoni ''' ''' def fastED(S1, S2): '''''' Returns the edit distance between the strings first and second.'''''' def fastEDhelper(S1, S2, memo): if (S1, S2) in memo: return memo [(S1, S2)] if S1 == '': result = len(S2) elif S2 == '': result = len(S1) elif S1[0] == S2[0]: result = fastEDhelper(S1[1:], S2[1:], memo) else: substitution = 1 + fastEDhelper(S1[1:], S2[1:],memo) deletion = 1 + fastEDhelper(S1[1:], S2, memo) insertion = 1 + fastEDhelper(S1, S2[1:],memo) result = min(substitution, deletion, insertion) memo[(S1,S2)] = result return result return fastEDhelper(S1, S2, {}) print (fastED("xylophone", "yellow")) ''' student_scores = {} student_scores['Brian'] = 76 student_scores['Brian'] = 56 student_scores['brian'] = student_scores['Brian'] class_scores = [ 96, 76, 56 ] print(student_scores['brian'])
''' Created on Apr 13, 2015 Last modified on April 7, 2016 @author: Brian Borowski CS115 - Functions that merge lists ''' def num_matches(list1, list2): '''Returns the number of elements that the two lists have in common.''' list1.sort() list2.sort() matches = 0 i = 0 j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: matches += 1 i += 1 j += 1 elif list1[i] < list2[j]: i += 1 else: j += 1 return matches def merge(list1, list2): '''Returns the elements of the two lists merged into one, eliminating duplicates.''' list1.sort() list2.sort() result = [] i = 0 j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: result.append(list1[i]) i += 1 j += 1 elif list1[i] < list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 while i < len(list1): result.append(list1[i]) i += 1 while j < len(list2): result.append(list2[j]) j += 1 return result def keep_matches(list1, list2): '''Returns a list of the elements that the two lists have in common.''' list1.sort() list2.sort() result = [] i = 0 j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: result.append(list1[i]) i += 1 j += 1 elif list1[i] < list2[j]: i += 1 else: j += 1 return result def drop_matches(list1, list2): '''Returns a list that contains no matches between elements of list1 and list2.''' list1.sort() list2.sort() result = [] i = 0 j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: i += 1 j += 1 elif list1[i] < list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 while i < len(list1): result.append(list1[i]) i += 1 while j < len(list2): result.append(list2[j]) j += 1 return result if __name__ == '__main__': A = [2, 3, 5, 7, 9, 11, 13, 17, 23] B = [11, 13, 15, 17, 19, 21, 23, 25, 27] print('List A: %s' % A) print('List B: %s' % B) print('Merged lists: %s' % merge(A, B)) print('Total matches: %d' % num_matches(A, B)) print('Matches: %s' % keep_matches(A, B)) print('Unique: %s' % drop_matches(A, B))
''' Created on Apr 11, 2017 @author: BhavinSoni ''' import sys '''a class is a blueprint for something you wish to represent. classes contain attributes and methods. attributes are variables that represent the state of the object''' '''methods are functions inside the class that allows you to change the state of an object. __ini__ is the constructor of special method of specializing the attributes of the object''' '''private member variables begin with self.__(variable name) private member variables cannot be referenced outside the class ''' '''instantiation means to create instance of an object''' '''you cannot have a setter without first having the corresponding property. another name for a setter = mutator''' '''inheritance represents an 'is-a' relationship that is objects of the sub class are instances of the superclass and attributes of the superclass are inherited in the subclass''' ''' animal /\ / \ Dog Cat 'has-a' relationship describes composition. instances of the object have those attributes''' class Student(object): def __init__(self, first_name, last_name, sid, gpa): self.__first_name = first_name self.__last_name = last_name self.__sid = sid try: self.__gpa = float(gpa) except: raise TypeError('gpa must be a float') @property def first_name(self): return self.__first_name @first_name.setter def first_name(self, first_name): self.__first_name = first_name @property def last_name(self): return self.__last_name @last_name.setter def last_name(self, last_name): self.__last_name = last_name @property def sid(self): return self.__sid @sid.setter def sid(self, sid): self.__sid = sid @property def gpa(self): '''this is an accessor or getter method. if you have a reference s1, to a student object, simply read the value of the gpa by referencing s1.gpa''' return self.__gpa @gpa.setter def gpa(self, gpa): try: local_gpa = float(gpa) except: raise TypeError('gpa must be a float') if local_gpa < 0.0 or local_gpa > 4.0: raise ValueError('gpa must be between 0.0 and 4.0') self.__gpa = local_gpa def __str__(self): return self.__first_name + ' ' + self.__last_name + ' (SID: ' + \ self.__sid + ', GPA: ' + str(self.__gpa) + ')' if __name__ == '__main__': try: s1 = Student('john', 'doe', '123456' , '5.0') except TypeError as error: print('error:',error ) sys.exit(1) print (s1.first_name) s1.first_name = 'brian' print(s1.first_name) print(s1.last_name) s1.last_name = 'soni' print(s1.last_name) s1.gpa = 100.3 print(s1.gpa)
''' Program Title A Programmer 01/01/1970 A brief description of what the program does ''' student = [] student.append(input('Please enter name: ')) student.append(int(input('Please enter age: '))) while student[1] < 1 or student[1] > 150: student[1] = int(input('Between 1 and 150: ')) student.append(float(input('Please enter height: '))) while student[2] < 1 or student[2] > 2.5: student[2] = float(input('Between 1 and 2.5: ')) student.append(input('What is your home town?: ')) print(student)
#!/usr/bin/env python # encoding: utf-8 """ @description: 迭代器模式 @author: BaoQiang @time: 2017/6/19 14:03 """ import re import reprlib import itertools RE_WORD = re.compile('\w+') class Sentence: def __init__(self, text): self.text = text def __repr__(self): return 'Sentence(%s)' % reprlib.repr(self.text) def __iter__(self): for match in RE_WORD.finditer(self.text): yield match.group() def sentence_lazyiter(): sen = Sentence('i am good') for item in sen: print(item) def while_iter(): s = 'abc' it = iter(s) while True: try: print(next(it)) except StopIteration as e: del it break def aritprog_gen(begin, step, end=None): result = type(begin + step)(begin) forever = end is None index = 0 while forever or result < end: yield result index += 1 result = begin + step * index def main(): # while_iter() # sentence_lazyiter() # print(list(aritprog_gen(0, 1, 3))) itertools_run() if __name__ == '__main__': main()
import pandas from matplotlib import pyplot from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split, cross_val_score, ShuffleSplit data_file = '../data/cali_housing.csv' data = pandas.read_csv(data_file) #------------------------------------------------------------------------ def evaluate(model, X, y): print(model) scores = cross_val_score(model, X, y, cv=ShuffleSplit(100, train_size=0.9)) print('R:', round(scores.mean(), 2)) #------------------------------------------------------------------------ data.info() data.sum() data.sample(10) data.median_income.hist() pyplot.show() # 1. Deal with missing data data = data.dropna() # data.hist(bins=50, figsize=(10,7)) # pyplot.show() # 2. Discretize some variables (e.g. median income) a = numpy.ceil( data.median_income / 1.5 ) data['income_cat'] = a.where( a < 5, 5 ) # 3. Deal with categorical variables. data = pandas.get_dummies(data, columns=['ocean_proximity']) # 4. Build linear regression model and fit y = df.median_house_value Xincome = df[['income_cat']] Xall = df.drop('median_house_value', axis=1) model = LinearRegression() # X_train, X_test, y_train, y_test = train_test_split(Xincome,y,train_size=0.9) # model.fit(X_train, y_train) # print(model.score(X_test, y_test)) # 5. Cross validate (define this into a separate function) evaluate(model, Xincome, y) evaluate(model, Xall, y) model = LinearRegression() # fit and predict # model.fit(Xincome,y) # print( model.predict([ [5], [2] ])) model.fit(Xall, y) # 6. Save model joblib.dump(model, 'CAhouses.model')
import sys import os import random from nltk import ngrams def weighted_choice(choices): total = sum(w for c, w in choices.items()) r = random.uniform(0, total) upto = 0 for c, w in choices.items(): if upto + w > r: return c upto += w def ngram_init(): # N Gram value n = 5 counts = {} directory = "../input/" for filename in os.listdir(directory): filename = os.path.join(directory, filename) text = open(filename).read().split() n_grams = ngrams(text, n) for gram in n_grams: if gram in counts: counts[gram] += 1 else: counts[gram] = 1 return counts def ngram(counts, word, num_words): if num_words <= 0: num_words = random.randint(5,15) result = "" for i in range(num_words): result = result + " " + word choices = {k:v for k,v in counts.items() if k[0] == word} word = weighted_choice(choices)[1] return result
from game_master import GameMaster from read import * from util import * import pdb class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Returns: A Fact object that could be used to query the currently available moves """ return parse_input('fact: (movable ?disk ?init ?target)') def getGameState(self): """ Returns a representation of the game in the current state. The output should be a Tuple of three Tuples. Each inner tuple should represent a peg, and its content the disks on the peg. Disks should be represented by integers, with the smallest disk represented by 1, and the second smallest 2, etc. Within each inner Tuple, the integers should be sorted in ascending order, indicating the smallest disk stacked on top of the larger ones. For example, the output should adopt the following format: ((1,2,5),(),(3, 4)) Returns: A Tuple of Tuples that represent the game state """ ### student code goes here PEG1 = self.kb.kb_ask(parse_input('fact: (on ?disk peg1)')) PEG2 = self.kb.kb_ask(parse_input('fact: (on ?disk peg2)')) PEG3 = self.kb.kb_ask(parse_input('fact: (on ?disk peg3)')) peg1 = [] if PEG1: for x in PEG1: disk = int(str(x.bindings[0].constant)[-1]) peg1.append(disk) peg1.sort() peg1 = tuple(peg1) else: peg1 = tuple() peg2 = [] if PEG2: for x in PEG2: disk = int(str(x.bindings[0].constant)[-1]) peg2.append(disk) peg2.sort() peg2 = tuple(peg2) else: peg2 = tuple() peg3 = [] if PEG3: for x in PEG3: disk = int(str(x.bindings[0].constant)[-1]) peg3.append(disk) peg3.sort() peg3 = tuple(peg3) else: peg3 = tuple() game = (peg1, peg2, peg3) return game pass def makeMove(self, movable_statement): """ Takes a MOVABLE statement and makes the corresponding move. This will result in a change of the game state, and therefore requires updating the KB in the Game Master. The statement should come directly from the result of the MOVABLE query issued to the KB, in the following format: (movable disk1 peg1 peg3) Args: movable_statement: A Statement object that contains one of the currently viable moves Returns: None """ ### Student code goes here disk = movable_statement.terms[0] fPeg = movable_statement.terms[1] tPeg = movable_statement.terms[2] if self.isMovableLegal(movable_statement): # Update From-Peg query = self.kb.kb_ask(parse_input(f'fact: (onTopOf {str(disk)} ?d')) self.kb.kb_retract(parse_input(f'fact: (top {str(disk)} {str(fPeg)})')) self.kb.kb_retract(parse_input(f'fact: (on {str(disk)} {str(fPeg)})')) if query: underDisk = query[0].bindings[0].constant self.kb.kb_assert(parse_input(f'fact: (top {str(underDisk)} {str(fPeg)}')) else: self.kb.kb_assert(parse_input(f'fact: (empty {str(fPeg)})')) # Update To-Peg self.kb.kb_retract(parse_input(f'fact: (empty {str(tPeg)})')) top = self.kb.kb_ask(parse_input(f'fact: (top ?d {str(tPeg)})')) if top: topDisk = top[0].bindings[0].constant self.kb.kb_retract(parse_input(f'fact: (top {str(topDisk)} {str(tPeg)})')) self.kb.kb_assert(parse_input(f'fact: (on {str(disk)} {str(tPeg)})')) self.kb.kb_assert(parse_input(f'fact: (top {str(disk)} {str(tPeg)})')) pass def reverseMove(self, movable_statement): """ See overridden parent class method for more information. Args: movable_statement: A Statement object that contains one of the previously viable moves Returns: None """ pred = movable_statement.predicate sl = movable_statement.terms newList = [pred, sl[0], sl[2], sl[1]] self.makeMove(Statement(newList)) class Puzzle8Game(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ Create the Fact object that could be used to query the KB of the presently available moves. This function is called once per game. Returns: A Fact object that could be used to query the currently available moves """ return parse_input('fact: (movable ?piece ?initX ?initY ?targetX ?targetY)') def getGameState(self): """ Returns a representation of the the game board in the current state. The output should be a Tuple of Three Tuples. Each inner tuple should represent a row of tiles on the board. Each tile should be represented with an integer; the empty space should be represented with -1. For example, the output should adopt the following format: ((1, 2, 3), (4, 5, 6), (7, 8, -1)) Returns: A Tuple of Tuples that represent the game state """ ### Student code goes here ROW1 = self.kb.kb_ask(parse_input('fact: (row1 ?t)')) ROW2 = self.kb.kb_ask(parse_input('fact: (row2 ?t)')) ROW3 = self.kb.kb_ask(parse_input('fact: (row3 ?t)')) row1 = ['x', 'x', 'x'] for x in ROW1: findXPosn = self.kb.kb_ask(parse_input(f'fact: (inst {str(x.bindings[0].constant)} ?posx ?posy)')) posn = int(str(findXPosn[0].bindings[0].constant)[-1]) tile = x.bindings[0].constant if str(tile) == 'empty': tileNum = -1 else: tileNum = int(str(tile)[-1]) row1[posn-1] = tileNum row1 = [x for x in row1 if x != 'x'] row1 = tuple(row1) row2 = ['x', 'x', 'x'] for x in ROW2: findXPosn = self.kb.kb_ask(parse_input(f'fact: (inst {str(x.bindings[0].constant)} ?posx ?posy)')) posn = int(str(findXPosn[0].bindings[0].constant)[-1]) tile = x.bindings[0].constant if str(tile) == 'empty': tileNum = -1 else: tileNum = int(str(tile)[-1]) row2[posn-1] = tileNum row2 = [x for x in row2 if x != 'x'] row2 = tuple(row2) row3 = ['x', 'x', 'x'] for x in ROW3: findXPosn = self.kb.kb_ask(parse_input(f'fact: (inst {str(x.bindings[0].constant)} ?posx ?posy)')) posn = int(str(findXPosn[0].bindings[0].constant)[-1]) tile = x.bindings[0].constant if str(tile) == 'empty': tileNum = -1 else: tileNum = int(str(tile)[-1]) row3[posn-1] = tileNum row3 = [x for x in row3 if x != 'x'] row3 = tuple(row3) game = (row1, row2, row3) return game pass def makeMove(self, movable_statement): """ Takes a MOVABLE statement and makes the corresponding move. This will result in a change of the game state, and therefore requires updating the KB in the Game Master. The statement should come directly from the result of the MOVABLE query issued to the KB, in the following format: (movable tile3 pos1 pos3 pos2 pos3) Args: movable_statement: A Statement object that contains one of the currently viable moves Returns: None """ ### Student code goes here tile = movable_statement.terms[0] fPosx = movable_statement.terms[1] fPosy = movable_statement.terms[2] tPosx = movable_statement.terms[3] tPosy = movable_statement.terms[4] if self.isMovableLegal(movable_statement): self.kb.kb_retract(parse_input(f'fact: (inst {str(tile)} {str(fPosx)} {str(fPosy)})')) self.kb.kb_retract(parse_input(f'fact: (inst empty {str(tPosx)} {str(tPosy)})')) self.kb.kb_assert(parse_input(f'fact: (inst {str(tile)} {str(tPosx)} {str(tPosy)})')) self.kb.kb_assert(parse_input(f'fact: (inst empty {str(fPosx)} {str(fPosy)})')) self.kb.kb_remove(parse_input(f'fact: (movable empty {str(fPosx)} {str(fPosy)} {str(fPosx)} {str(fPosy)})')) pass def reverseMove(self, movable_statement): """ See overridden parent class method for more information. Args: movable_statement: A Statement object that contains one of the previously viable moves Returns: None """ pred = movable_statement.predicate sl = movable_statement.terms newList = [pred, sl[0], sl[3], sl[4], sl[1], sl[2]] self.makeMove(Statement(newList))
file = open('10_input.txt', 'r') lines = file.readlines() nums = [int(l.strip()) for l in lines] nums.sort() nums = [0] + nums count_3 = 1 # device is 3 over last one count_1 = 0 for n in range (1, len(nums)): if (nums[n] - nums[n-1]) == 1: count_1 = count_1 + 1 elif (nums[n] - nums[n-1]) == 3: count_3 = count_3 + 1 print (count_3) print (count_1) print (count_3 * count_1)
number = int(input("I am thinking of a number between 1 and 10. What's the number? ")) import random my_random_number = random.randint(1, 10) while number != my_random_number: if number < my_random_number: print("{} is too low. ".format(number)) number = int(input("What's the number? ")) if number == my_random_number: print("{}. Yes! You win!".format(number)) number = int(input("Yes! You win!")) if number > my_random_number: print("{} is too high. ".format(number)) number = int(input("What's the number? "))
# Напишите функцию которая принимает число 'N' и # возвращает квадраты всех натуральных чисел кроме числа 'N', в порядке возрастания # например если число 'N' = 4 ,то должен выйти список из чисел: 0,1,4,9 def Number_N(): a = int(input()) new_list = [] for num in range(a): new_list.append(num**2) print(new_list) Number_N()
import math import random def mean(n): """ Computes the mean value of a list of parameter n """ total = 0 for i in n: total += i return total/len(n) def median(n): """ Computes the median value of a list of parameter n """ n.sort() length_of_n = len(n) if length_of_n%2==0: after = length_of_n//2 average = n[after-1] + n[after] return average/2 else: return n[length_of_n//2] def mode(n): """ Computes the most occuring value of a list of parameter n """ nSet = set(n) modeVal = 0 modeNum = n[0] for i in nSet: if(modeVal < n.count(i)): modeNum = i modeVal = n.count(i) return modeNum def standard_deviation(n): """ Computes the standard deviation of a list of parameter n """ top = 0 average = mean(n) for i in n: top += pow(i-average, 2) return(math.sqrt(top/(len(n)))) def percentile(nth, n): position = len(n) return (nth/100) * position ############# This is the rock scissor player game ############# userGuess = input("Pick your game. Select 1 for rock, 2 for scissor, 3 for paper: ") outcomesDic = {1:'rock', 2:'scissor', 3:'paper'} outcomesList = ['rock', 'scissor', 'paper'] try: userGuess = outcomesDic[eval(userGuess)] except Exception as e: # Randomly choosing an option for the user because he went out of box val = random.randint(1,3) print("You have chosen out of the options and {} have been selected for you".format(val)) userLive = 3 userPoint = 0 gameSwitch = True computerGuess = random.choice(outcomesList) while gameSwitch: if(userGuess=='rock' and computerGuess=='scissor'): userPoint += 1 print("You win because computer plays scissor") elif(userGuess=='scissor' and computerGuess=='rock'): userLive -= 1 print("You lost to the computer because it plays rock") print("You have {} live remaining".format(userLive)) elif(userGuess=='paper' and computerGuess=='rock'): userPoint += 1 print("You win because computer plays rock") elif(userGuess=='rock' and computerGuess=='paper'): userLive -= 1 print("You lost to the computer because it plays paper") print("You have {} live remaining".format(userLive)) elif(userGuess=='scissor' and computerGuess=='paper'): userPoint += 1 print("You win because computer plays paper") elif(userGuess=='paper' and computerGuess=='scissor'): userLive -= 1 print("You lost to the computer because it plays scissor") print("You have {} live remaining".format(userLive)) else: print("This round is a draw because you guessed same thing as the computer") if(userLive<1): print("Game over! You scored {}".format(userPoint)) break; print() # Creating a space between rounds of the game userGuess = input("Pick your game. Select 1 for rock, 2 for scissor, 3 for paper: ") try: userGuess = outcomesDic[eval(userGuess)] except Exception as e: # Randomly choosing an option for the user because he went out of box val = random.randint(1,3) print("You have chosen out of the options and {} have been selected for you".format(val)) computerGuess = random.choice(outcomesList)
# Count XML Tags in Text def tag_count(tokens): count = 0 for token in tokens: if token[0] == '<' and token[-1] == '>': count += 1 return count # Create an HTML List def html_list(list_items): HTML_string = "<ul>\\n" for item in list_items: HTML_string += "<li>{}</li>\\n".format(item) HTML_string += "</ul>" return HTML_string # Create Nearest Square Function def nearest_square(limit): answer = 0 while (answer+1)**2 < limit: answer += 1 return answer**2 print(nearest_square(100)) def top_two(input_list): #Write your code in the white space here top1 = max(input_list) input_list.remove(max(input_list)) top2 = max(input_list) top_two = [top1, top2] return top_two
# condiciones del scrip para juego de dados: # 1)Simular el lanzamiento de dos dados de seis caras. # 2)Para ganar la mano, la suma entre ambos dados debe ser igual a cuatro. # 3)Si la suma entre ambos dados es menor a cuatro, entonces se pierde esta mano. # 4)Si la suma entre ambos dados es mayor a cuatro, debe volver a tirar. from random import randint def juego_de_dados(): dado1 = randint(1, 6) dado2 = randint(1, 6) suma_dado = dado1 + dado2 print("Su resultado en esta mano es :", suma_dado) if suma_dado == 4: print(" *** HAS GANADO ESTA MANO! ***") elif suma_dado <= 4: print(" Pierdes esta mano, suerte en la proxima! ") else: while suma_dado > 4: print(" (vuelves a tirar nuevamente) ") dado1 = randint(1, 6) dado2 = randint(1, 6) suma_dado = dado1 + dado2 print("Su resultado en esta mano es :", suma_dado) if suma_dado == 4: print(" *** HAS GANADO ESTA MANO! *** ") elif suma_dado <= 4: print("Pierdes esta mano, suerte en la proxima! ") juego_de_dados()
import time # welcome the user user_name = input("Hello Player enter your name") print("Hello "+user_name+" Let's play Hangman ") time.sleep(1) print("Start Guessing ......") time.sleep(0.5) # Guessing word word = "apple" guesses = '' turns = 10 # Create a while loop while turns > 0: failed= 0 for char in word: if char in guesses: print(char) else: print("_") failed += 1 guess = input("Enter character to guess") guesses += guess if guess not in word: turns -= 1 print("Wrong Guess! Please Try Again") print("You have", turns, "left ") if turns == 0: print("You Lose")
import sys import unicodedata #creating dictionairies globals enAlphabet = "abcdefghijklmnopqrstuvwxyz" letToNumber= dict(zip(enAlphabet, range(len(enAlphabet)))) numberToLetter = {v:k for k, v in letToNumber.items()} def chooseLanguage(): print("Portugues(1) English(2)") lang = input() return lang def escolhaModo(): print("Escolha: Encriptar(1) Decriptar(2)") choice = input() return choice def chooseMode(): print("Please Choose: Encrypt(1) Decrypt(2)") choice = input() return choice def closethis(): print("option doesn't exist / opçao nao encontrada") sys.exit(0) def changeLetter(fraglist, key): result='' for element in fraglist: keyPos= 0 for letter in element: #find the number of actual letter myLetterNumber = letToNumber[letter] #find number of keyword letter keyNumber = letToNumber[key[keyPos]] newletterByNumber = (myLetterNumber + keyNumber) %(26) letterEncrypted = numberToLetter[newletterByNumber] result+= letterEncrypted keyPos+=1 return result pass def changeback(fraglist, key): result='' for element in fraglist: keyPos= 0 for letter in element: #find the number of actual letter myLetterNumber = letToNumber[letter] #find number of keyword letter keyNumber = letToNumber[key[keyPos]] newletterByNumber = (myLetterNumber - keyNumber) %(26) letterEncrypted = numberToLetter[newletterByNumber] result+= letterEncrypted keyPos+=1 return result def removeSpecialChar(message): m2= unicodedata.normalize("NFD", message) m2 = m2.encode("ascii","ignore") m2= m2.decode("utf-8") return m2 def encrypt(message, key): print("encript") endMessage= len(message) sizeKey = len(key) fragList=[] #quebra a minha mensagem no tamanho da key for f in range(0, endMessage, sizeKey): fragList.append(message[f:f + sizeKey]) result= changeLetter(fragList, key) return result def decrypt(text, key): print("decript") endMessage= len(text) sizeKey = len(key) fragList=[] #quebra a minha mensagem no tamanho da key for f in range(0, endMessage, sizeKey): fragList.append(text[f:f + sizeKey]) message = changeback(fragList, key) print("Sua mensagem decripada é:") print("\n"+ message) def enContinue(choice): if(choice=="1"): print("Escreva a mensagem a ser cifrada no arquivo messageEnglish\n Agora, escreva no terminal sua chave:") key= input() f = open("messageEnglish.txt",'r', encoding='utf-8') text= f.read() f.close() lowertext = removeSpecialChar(text).lower() message='' #remove graphic signs and spaces for char in lowertext: if char in enAlphabet: message+=char finalMessage = encrypt(message, key) print("sua mensagem encriptada é: ") print(finalMessage) elif(choice=="2"): print("Escreva a mensagem a ser decifrada no arquivo cypher.txt \n Escreva no terminal a chave para decifrar:") key= input() f = open("cypher.txt",'r', encoding='utf-8') text= f.read() f.close() decrypt(text, key) else: closethis() #Main: print("Ola, esse é o programa cifrador/decifrador\n") choice = escolhaModo() print(choice) enContinue(choice) #language = chooseLanguage() #print(language) # if(language == 1): # escolhaModo() # elif(language==2): # choice= chooseMode() # enContinue(choice) # else: # closethis() #for english #for port #for port it is important to clear the message from graphic signals
################## #Set game to be on or off from random import randint import time import sys game = True newnames = 1 def printcleanspace(howmanyyouwant = 1): print('\n'*howmanyyouwant) def cointoss(): cointossresult = "" cointoss = randint(0, 100) for i in range(0,2): if cointoss%2==0: return("heads") if cointoss%2==1: return("tails") if cointoss.lower() == "heads": return("heads") if cointoss.lower() == "tails": return("tails") def onerCalc(one): if one == 1: oner = "one" return(oner) elif one == "X" or one == "x": oner = "X" return(oner) elif one == "O" or one == "o": oner = "O" return(oner) else: return False def board(one = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9): winner = 0 def boardface(): print(f" | | ") print(f" {one} | {two} | {three} ") print(f"|||||||||||||||||") print(f" {four} | {five} | {six} ") print(f"|||||||||||||||||") print(f" {seven} | {eight} | {nine} ") print(f" | | ") boardface() def win(one = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9): PlayerX = 0 PlayerO = 0 onerOne = onerCalc(one) onerTwo = onerCalc(two) onerThree = onerCalc(three) onerFour = onerCalc(four) onerFive = onerCalc(five) onerSix = onerCalc(six) onerSeven = onerCalc(seven) onerEight = onerCalc(eight) onerNine = onerCalc(nine) if (onerOne == "X" and onerFour == "X" and onerSeven == "X") or (onerFour == "X" and onerFive == "X" and onerSix == "X") or (onerOne == "X" and onerTwo == "X" and onerThree == "X") or (onerOne == "X" and onerFive == "X" and onerNine == "X") or (onerThree == "X" and onerSix == "X" and onerNine == "X") or (onerThree == "X" and onerFive == "X" and onerSeven == "X") or (onerSeven == "X" and onerEight== "X" and onerNine == "X") or(onerTwo == "X" and onerFive == "X" and onerEight == "X"): return(1) if (onerOne == "O" and onerFour == "O" and onerSeven == "O") or (onerFour == "O" and onerFive == "O" and onerSix == "O") or (onerOne == "O" and onerTwo == "O" and onerThree == "O") or (onerOne == "O" and onerFive == "O" and onerNine == "O") or (onerThree == "O" and onerSix == "O" and onerNine == "O") or (onerThree == "O" and onerFive == "O" and onerSeven == "O") or (onerSeven == "O" and onerEight== "O" and onerNine == "O") or(onerTwo == "O" and onerFive == "O" and onerEight == "O"): return(2) def cointosswinner(cointossresult, fplayer, fname): print(f"Flipping Coin in ") time.sleep(.75) print(f"\n 3 . . . ") time.sleep(.75) print(f"\n 2 . . . ") time.sleep(.75) print(f"\n 1 . . . \n") time.sleep(.75) print(f"{cointossresult}. Congrats {fname} you're first!") time.sleep(1.5) #printcleanspace(1) def gameturn(fplayer, splayer, themove, gameonORoff, fname, sname): countturn = 0 one = 1 two = 2 three = 3 four = 4 five = 5 six = 6 seven = 7 eight = 8 nine = 9 while gameonORoff == 1: WINNER = win(one, two, three, four, five, six, seven, eight, nine) if countturn%2==0: countturn += 1 if countturn == 10: break if WINNER == 1: break printcleanspace(10) board(one, two, three, four, five, six, seven, eight, nine) themove = int(input(f'Enter the number of your move {fname}: ')) if themove == 1: if one == "X" or one == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: one = "X" if themove == 2: if two == "X" or two == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: two = "X" if themove == 3: if three == "X" or three == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: three = "X" if themove == 4: if four == "O" or four == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: four = "X" if themove == 5: if five == "O" or five == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: five = "X" if themove == 6: if six == "O" or six == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: six = "X" if themove == 7: if seven == "O" or seven == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: seven = "X" if themove == 8: if eight == "O" or eight == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: eight = "X" if themove == 9: if nine == "X" or nine == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: nine = "X" WINNER = win(one, two, three, four, five, six, seven, eight, nine) if WINNER == 1: printcleanspace(10) if WINNER == 1: print("X's is the Winner!") if WINNER == 2: print("O's is the Winner!") board(one, two, three, four, five, six, seven, eight, nine) break if countturn % 2 == 1: countturn += 1 if countturn == 10: break if WINNER == 1: break printcleanspace(10) board(one, two, three, four, five, six, seven, eight, nine) themove = int(input(f'Enter the number of your move {sname}: ')) if themove == 1: if one == "X" or one == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: one = "O" if themove == 2: if two == "X" or two == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: two = "O" if themove == 3: if three == "X" or three == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: three = "O" if themove == 4: if four == "O" or four == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: four = "O" if themove == 5: if five == "O" or five == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: five = "O" if themove == 6: if six == "O" or six == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: six = "O" if themove == 7: if seven == "O" or seven == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: seven = "O" if themove == 8: if eight == "O" or eight == "X": countturn -= 1 print("Another player has played in this space. Please select another") continue else: eight = "O" if themove == 9: if nine == "X" or nine == "O": countturn -= 1 print("Another player has played in this space. Please select another") continue else: nine = "O" WINNER = win(one, two, three, four, five, six, seven, eight, nine) if WINNER == 1: printcleanspace(10) if WINNER == 1: print("X's is the Winner!") if WINNER == 2: print("O's is the Winner!") board(one, two, three, four, five, six, seven, eight, nine) break while game == True: ###This is the main menu where you welcome players, they pick names, and then they pick who goes first. ### or do a coin flip thingie to pick who goes first game = True if newnames == 1: player1 = input("Hey player 1 welcome to Tic Tac Toe! Please Input your name: ") printcleanspace() player2 = input("Alrighty player 2 you know the drill! Name please.: ") printcleanspace() print("Do you want to flip for who gets X's " "and goes first or do you want to simply pick who goes first?") printcleanspace() decide_for_cointoss = input("Press Enter to Continue with the coin flip. " f"Or enter 1 for ({player1}) or 2 for ({player2}) to select which player goes first and gets X's: ") cointoss_result_to_pick_coin = cointoss() print(cointoss_result_to_pick_coin) if decide_for_cointoss == "": if cointoss_result_to_pick_coin == "tails": cointoss_to_decide_the_game = input(f"{player1}, please select if you'd like heads or tails: ") fplayer = 1 fnameActual = player1 splayer = 2 snameActual = player2 if cointoss_result_to_pick_coin == "heads": cointoss_to_decide_the_game = input(f"{player2}, please select if you'd like heads or tails: ") fplayer = 2 fnameActual = player2 splayer = 1 snameActual = player1 #if decide_for_cointoss.lower() == "1" or decide_for_cointoss.lower() == "2": # if int(decide_for_cointoss) == 1: #add game func second part to finish # first_turn = input("Player 1, you're first!: ") # fplayer = 1 #splayer = 2 #cointoss() #if (decide_for_cointoss) == 2: # call_for_the_coin = input("Player 2, you're first! ") # fplayer = 2 # splayer = 1 #else: # call_for_the_coin = input("Player 1, you're first!: \n" # "you know since the both of you can't follow directions... ") # fplayer = 1 # splayer = 2 if decide_for_cointoss == "1": gameon = 1 fplayer = 1 fnameActual = player1 splayer = 2 snameActual = player2 gameturn(fplayer, splayer, "", gameon, fnameActual, snameActual) elif decide_for_cointoss == "2": gameon = 1 fplayer = 2 fnameActual = player2 splayer = 1 snameActual = player1 gameturn(fplayer, splayer, "", gameon, fnameActual, snameActual) elif cointoss_result_to_pick_coin.lower() == cointoss_to_decide_the_game.lower(): cointosswinner(cointoss_result_to_pick_coin, fplayer, fnameActual) #finish this out first gameon = 1 gameturn(fplayer, splayer, "", gameon, fnameActual, snameActual) #print("Game over") elif cointoss_result_to_pick_coin.lower() != cointoss_to_decide_the_game.lower(): cointosswinner(cointoss_result_to_pick_coin, splayer, snameActual) #finish this out first gameon = 1 gameturn(fplayer, splayer, "", gameon, snameActual, fnameActual) #print("Game over") quit = int(input("Would you like to play another round or quit, enter (1 for Yes or 2 for No) for another round: ")) if quit == 1: newnames = int(input("Do you new names? (1 for Yes or 2 for No): ")) printcleanspace(100) if quit == 2: print("Good Bye!") game = False break
import random def Start(): board=["-" for i in range(0,9)] possible_places = [i for i in range(0,9)] def pr_board(): print(*board[0:3]) print(*board[3:6]) print(*board[6:9]) if "-" not in board: if check_winner("X"): print("X has Won") Start() if check_winner("O"): print("O has Won") Start() print("tie") Start() def check_winner(c): if board[0:3] == [c,c,c] or board[3:6] == [c,c,c] or board[6:9]== [c,c,c] or board[0:7:3] == [c,c,c]: return True if board[1:8:3] == [c,c,c] or board[2:9:3]==[c,c,c]: return True if board[0:9:4]==[c,c,c] or board[2:7:2]==[c,c,c]: return True else: return False while True: selector = input("X or O: ") possible_places = [i for i in range(0,9)] board=["-" for i in range(0,9)] while selector == "X" or selector=="x": spot = input("Where you want to place it ?") spot = int(spot) if spot-1 in possible_places: spot = spot-1 possible_places.remove(spot) board[spot]="X" if check_winner("X"): print("X has Won") pr_board() Start() try: bot = int(random.choice(possible_places))+1 possible_places.remove(bot-1) board[bot-1]="O" if check_winner("O"): print("O has Won") pr_board() Start() pr_board() except IndexError: pr_board() else: pass while selector =="O" or selector=="o": bot = random.choice(possible_places) possible_places.remove(bot) board[bot]="X" pr_board() if check_winner("X"): print("X has Won") pr_board() Start() spot = input("Where you want to place it ?") spot = int(spot) if spot-1 in possible_places: spot = spot-1 possible_places.remove(spot) board[spot]="O" if check_winner("O"): print("O has Won") pr_board() Start() Start()
import pandas as pd # Create a dictionary of sales data #course_sales = {'course':['Python','Ruby','Excel','C++'], #'day':['Mon','Tue','Wed','Tue'], #'price':[5,10,15,20], #'sale':[2,3,5,7] #} # Convert sales data into a DataFrame #df_sales = pd.DataFrame(course_sales) #print(df_sales) # Create indidivdual lists from sales data course = ['Python','Ruby','Excel','C++'] day = ['Mon', 'Tue', 'Tue', 'Wed'] price = [5,10,15,20] sale = [2,3,5,7] # Create a list of column labels column_labels = ['Course', 'Day', 'Price', 'Sale'] # Add a list of column entries for each column column_names = [course,day,price,sale] # Combine list of column labels and column names above to create a new single list master_list = list(zip(column_labels,column_names)) #master_list = list(zip(column_labels)) #print(master_list) # Convert master list to a dictionary sales_data = dict(master_list) # Convert master list dictionary to a DataFrame df_sales = pd.DataFrame(sales_data) #df_master_list = pd.DataFrame(master_list) print(df_sales) #print(df_master_list)
""" bittrex.client returns balances as a list of dictionaries with: Currency, Balance, CryptoAddress, Pending, Requested, Uuid A portfolio is the type and amount of each cryptocurrency held along with some basic operations. . There is a desired 'state' and due to fluctuations some currencies will have more (or less) total_value than their desired target 'state'. We'll rebalance them periodically. To avoid spending too much in commissions when rebalancing we have a 'threshold' and we only 'rebalance cryptocurrencies that increased (or decreased) more than 'threshold' (as a percentage) from desired 'state'. For example is the desired state is 100 and the threshold is 0.1 we'll sell only if the current total_value is at or above 110 (and buy if the current total_value is at or below 90) To prevent from buying too much of a sinking currency we are going to put bounds on either the price and/or the quantities (not clear yet). One idea is to compute the ratio between the current balance and the initial balance per currency and then say that no currency can have a ratio that is N times bigger than the average ratio. """ import os import tempfile import time import numpy as np import pandas as pd from exchanges import exchange import config import s3_utils import state if os.environ['LOGNAME'] == 'aws': print('Finished loading', __file__) COMMISION = 0.25/100 SATOSHI = 10**-8 # in BTC MINIMUM_TRADE = exchange.MINIMUM_TRADE # in SAT (satohis) class Portfolio(object): def __init__(self, values, timestamp): """ Read portfolio from API """ self.values = values self.timestamp = timestamp @classmethod def from_state(cls, market, state, base, value): p = cls._start_portfolio(market, state, base, value) return p @classmethod def from_simulation_index(cls, sim_index): params_df = pd.read_csv(config.PARAMS, index_col=0) sim_params = params_df.loc[sim_index] p = cls.from_simulation_params(0, sim_params) return p @classmethod def from_simulation_params(cls, market, sim_params): base = sim_params['base'] value = sim_params['value'] state = sim_params.to_frame() for key in config.PARAMS_INDEX_THAT_ARE_NOT_CURRENCIES: if key in state.index: state.drop(key, inplace=True, axis=0) state.columns = ['Weight'] p = cls._start_portfolio(market, state, base, value) return p @classmethod def from_exchange(cls): return cls(exchange.get_balances(), int(time.time())) @classmethod def from_first_buy_order(cls): """ return the portfolio first traded after the 'state' was last updated. (We are actually trying to load the portfolio from the first 'buy' order, some currencies might not have been executed at the requested limit buy/sell) In case the Buy order does not exist, try to load the portfolio from config.PORTFOLIOS_BUCKET """ orders_bucket = config.s3_client.Bucket(config.BUY_ORDERS_BUCKET) # get the timestamp corresponding to the 'state' definition. # IF there is a csv in bittrex-buy-orders bucket matching <account>/<time_stamp>_buy_df.csv. Load # portfolio from this key time_stamp, _ = state.current() all_summaries = orders_bucket.objects.filter(Prefix=os.environ['EXCHANGE_ACCOUNT']) keys = [summary.key for summary in all_summaries] def time_from_key(key): """ key is of the form <acount>/<timestamp>_buy_df.csv. Return the number associated with <timestamp> :param key: :return: """ num_str = key.split('/')[1].split('_')[0] return int(num_str) summaries_times = [time_from_key(k) for k in keys] # get the 1st summary with time >= time_stamp distance = np.inf best_time = None best_key = None for key, time in zip(keys, summaries_times): if time >= time_stamp and distance > time - time_stamp: distance = time - time_stamp best_key = key best_time = time buy_order_df = s3_utils.get_df(orders_bucket.name, best_key, comment='#', index_col=0) #buy_order_df.loc[:, 'Available'] = buy_order_df['target_currency'] buy_order_df.loc[:, 'Balance'] = buy_order_df['target_currency'] buy_order_df = buy_order_df[buy_order_df['Balance'] > 0] return cls(buy_order_df['Balance'], best_time) @classmethod def from_csv(cls, csv): # Old csvs were DataFrames, new ones might be just series but we can still load them as dataframes to make # it backwards compatible df = pd.read_csv(csv, index_col=0) return cls(0, df['Balance']) @classmethod def from_s3_key(cls, s3_key): """ s3_key is of the form <path>/<timestamp>.csv :param s3_key: :return: """ timestamp = int(rsplit('/', 1)[0].replace('.csv', '')) _, temp = tempfile.mkstemp() config.s3_client.Bucket(config.PORTFOLIOS_BUCKET).download_file(s3_key, temp) df = pd.read_csv(temp, index_col=0, comment='#') return cls(df, timestamp) @classmethod def at_time(cls, timestamp, max_time_difference): bucket = config.s3_client.Bucket(config.PORTFOLIOS_BUCKET) for summary in bucket.objects.filter(Prefix=os.environ['EXCHANGE_ACCOUNT']): time = int(summary.key.split('/')[-1].rstrip('.csv')) if abs(time - timestamp) < max_time_difference: return cls.from_s3_key(summary.key) @classmethod def after_time(cls, timestamp): max_time_difference = np.inf best_key = None bucket = config.s3_client.Bucket(config.PORTFOLIOS_BUCKET) for summary in bucket.objects.filter(Prefix=os.environ['EXCHANGE_ACCOUNT']): time = int(summary.key.split('/')[-1].rstrip('.csv')) if time >= timestamp and time - timestamp < max_time_difference: max_time_difference = time - timestamp best_key = summary.key if best_key: return cls.from_s3_key(best_key) @classmethod def before_time(cls, timestamp): max_time_difference = np.inf best_key = None bucket = config.s3_client.Bucket(config.PORTFOLIOS_BUCKET) for summary in bucket.objects.filter(Prefix=os.environ['EXCHANGE_ACCOUNT']): time = int(summary.key.split('/')[-1].rstrip('.csv')) if time <= timestamp and timestamp - time < max_time_difference: max_time_difference = timestamp - time best_key = summary.key if best_key: return cls.from_s3_key(best_key) @classmethod def last_logged(cls): bucket = config.s3_client.Bucket(config.PORTFOLIOS_BUCKET) all_object_summaries = bucket.objects.filter(Prefix=os.environ['EXCHANGE_ACCOUNT']) all_keys = [aos.key for aos in all_object_summaries] # each key is of the form <account>/timestamp.csv. Keep only timestamp and convert it to an int timestamps = [int(key.rstrip('.csv').split('/')[1]) for key in all_keys] # find the key corresponding to the last timestamp last_index = np.argmax(timestamps) last_key = all_keys[last_index] return cls.from_s3_key(last_key) def copy(self): cls = self.__class__ new_df = self.values.copy() return cls(new_df) @staticmethod def _start_portfolio(market, state, base, value): """ We first start a portfolio that has just 'value' in 'base' and then execute ideal_rebalance on it :param market: :param state: :param base: :param value: :return: """ intermediate_currencies = ['BTC'] series = pd.Series(value, index=base) series.name = 'Balance' portfolio = Portfolio(series, market.time) portfolio.rebalance(market, state, intermediate_currencies, 0) return portfolio def total_value(self, market, intermediate_currencies): """ Compute the total amount of the portfolio param: intermediate_currendcies: list of str for each currency in self.values.index intermdiate_currencies + [currency] has to be a valid currency chain [A, B, C] (c trades with B and B trades with A and A is the base price to return in) """ return self.value_per_currency(market, intermediate_currencies).sum() def value_per_currency(self, market, intermediate_currencies): # since now self.values is a series, to minimize changes I convert to DataFrame, compute and convert back to # series portfolio = self.values.to_frame() answer = portfolio.apply(lambda x: market.currency_chain_value(intermediate_currencies + [x.name]) * x['Balance'], axis=1) # But since now it is a series return answer def ideal_rebalance(self, market, state, intermediate_currencies): """ Given market, state and intermediate_currencies return the amount to buy (+) or sell (-) for each currency to achieve perfect balance. At this point we don't look at trading costs, sinking currencies, etc returned dataframe has columns: target_base: the value in 'base' we should have in each currency after rebalancing target_currency: the ideal amount of each currency that achieves this ideal rebalancing Buy: the amount of currency that we have to buy (if > 0) or sell (if < 0) to obtain target_currency Buy (base): Amount of base needed for the transaction (not taking transactions costs into account) intermediate_currencies: each currency in 'state' will be converted to values in 'base' where base is intermediate_currencies[0] and the conversion is done by traversing from currency in state to intermediate_currencies[-1], then to intermediate_currencies[-2], ..., ending in intermediate_currencies[0] most likely this is going to be either: ['USDT', 'BTC'] ['USDT', 'ETH'] ['BTC'] ['ETH'] """ total_value = self.total_value(market, intermediate_currencies) buy_df = pd.merge(self.values.to_frame(), state, left_index=True, right_index=True, how='outer') # if state has new cryptocurrencies there will be NaNs buy_df.fillna(0, inplace=True) base = intermediate_currencies[0] buy_df.loc[:, 'target_base'] = buy_df['Weight'] * total_value buy_df.loc[:, 'currency_in_base'] = buy_df.apply( lambda x: market.currency_chain_value([base] + intermediate_currencies + [x.name]), axis=1) buy_df.loc[:, 'target_currency'] = buy_df['target_base'] / buy_df['currency_in_base'] buy_df.loc[:, 'Buy'] = buy_df['target_currency'] - buy_df['Balance'] buy_df.loc[:, 'Buy ({base})'.format(base=intermediate_currencies[0])] = buy_df.apply( lambda x: x.Buy * market.currency_chain_value([base] + intermediate_currencies + [x.name]), axis=1 ) return buy_df def rebalance(self, market, state, intermediate_currencies, min_percentage_change=0, by_currency=False): """ Given a state, buy/sell positions to approximate target_portfolio base_currency: base currency to do computations min_percentage_change: currencies are only balanced if difference with target is above/below this threshold (express as a percentage) by_currency: bool, when computing percentage_change we can do so by currency or in intermediate_currencies[0] """ buy_df = self.ideal_rebalance(market, state, intermediate_currencies) if os.environ['PORTFOLIO_SIMULATING'] == 'True': # apply transaction costs buy_df.loc[:, 'Buy'] = buy_df['Buy'].apply(apply_transaction_cost) base = intermediate_currencies[0] # we only buy/sell if movement is above 'min_percentage_change'. However, this movement could be in the # amount of cryptocurrency we own (by_currency=True) or in the amount of 'base' it represents (by_currency=False) if min_percentage_change > 0: for currency in buy_df.index: if by_currency: # if 'buy_df['Buy'] represents less than 'min_percentage_change' from 'position' don't do anything percentage_change = np.abs(buy_df.loc[currency, 'Buy']) / buy_df.loc[currency, 'Balance'] else: # if 'buy_df['Buy (base)'] represents less than 'min_percentage_change' from 'position' don't do anything percentage_change = np.abs(buy_df.loc[currency, 'Buy ({})'.format(base)]) / \ buy_df.loc[currency, 'target_base'] buy_df.loc[currency, "change"] = percentage_change if percentage_change < min_percentage_change: buy_df.loc[currency, 'Buy'] = 0 # if 'base' is in self.values, remove it. Each transaction is done/simulated against 'base'. We don't # buy/sell 'base' directly. Not doing this will lead to problems and double counting if base in buy_df.index: remove_transaction(buy_df, base) # As of 01/28/2017 this was 100K Satoshi's for Bittrex apply_min_transaction_size(market, buy_df, base) msg = '' if os.environ['PORTFOLIO_SIMULATING'] == 'True': self.mock_buy(buy_df[['Buy', 'Buy ({})'.format(base), 'change']]) else: self.buy(market, buy_df, base) def mock_buy(self, buy_df): """ This is a method that mocks sending a buy/sell order to the client and its execution. After this method executes, we'll assume that we buy/sell whatever we requested at the requested prices I don't understand if bittrex client talks in usdt, base or currency when placing orders. I'm just mocking the result here, not the call :param buy_df: :return: """ # There is 0.25% cost on each buy/sell transaction. Although exchanging ETH for BTC shows as two transactions # in 'buy' and should pay 0.25% only once, most transactions in 'buy' should pay the 0.25%. I'm going to # overestimate the transaction cost by paying the 0.25% for every transaction in buy # when we want to buy X, we end up with x * (1 - cost) # when we want to sell X, we end up with x * (1 - cost) base. I'm modeling this as we actuall sold # x * (1 + cost) # get 'base' name from the column named 'Buy (base)' column = [c for c in buy_df.columns if c.startswith("Buy (")][0] base = column[5:-1] # the 'index' in buy_df might not be the same as in self.values. That's why we start merging based on # index and we use 'outer'. self.values = pd.merge(self.values, buy_df, left_index=True, right_index=True, how='outer') # If new values are added to index there will be NaN self.values.fillna(0, inplace=True) self.values['Balance'] += self.values['Buy'] self.values.loc[base, 'Balance'] -= self.values[column].sum() self.values.drop(['Buy', column, 'change'], inplace=True, axis=1) def buy(self, market, buy_df, base_currency): """ Send buy/sell requests for all rows in buy_df :param buy_df: :param base_currency: :return: """ # Poloniex has a problem if we don't have enough BTC to place a buy order. # Maybe sort buy_df, execute all sell orders first, wait and execute buy? for currency, row in buy_df.iterrows(): print('*' * 80) market_name = _market_name(base_currency, currency) if market_name is None: continue amount_to_buy_in_base = row['Buy ({})'.format(base_currency)] amount_to_buy_in_currency = row['Buy'] if amount_to_buy_in_currency == 0: continue rate = amount_to_buy_in_base / amount_to_buy_in_currency satoshis = row['SAT'] if amount_to_buy_in_base > 0: msg_order = 'send BUY order' trade = exchange.buy_limit if os.environ['EXCHANGE'] == 'POLONIEX': print('Decreasing buy price by 0.995') rate *= 0.997 else: msg_order = 'send SELL order' trade = exchange.sell_limit amount_to_buy_in_currency *= -1 if os.environ['EXCHANGE'] == 'POLONIEX': print('Increasing sell price by 1.005') rate *= 1.003 # Do not change next "if" condition. The environmental variable is a string, not a bool if not os.environ['PORTFOLIO_TRADE'] == 'True': print("PORTFOLIO_TRADE: False\n") print(msg_order) print('Market_name: {}, amount: {}, rate: {} ({} SAT)\n'.format(market_name, amount_to_buy_in_currency, rate, satoshis)) if os.environ['PORTFOLIO_TRADE'] == 'True': try: trade(market_name, amount_to_buy_in_currency, rate) except: print('Previous trade Failed') # log the requested portfolio s3_key = '{account}/{time}_buy_df.csv'.format(account=os.environ['EXCHANGE_ACCOUNT'], time=int(market.time)) s3_utils.log_df(config.BUY_ORDERS_BUCKET, s3_key, buy_df) def limit_to(self, limit_df): """ limit self.values to the given limit_df If a currency is in both self.values and limit_df, the and 'Balance' fields of self.values are updated to the minimum between self.values['Balance'] and limit_df['Limit'] for example if self.values looks like: Balance Pending CryptoAddress BTC 2.3 0 xxx ETH 53.1 0 yyy XRP 1200.0 0 zzz and limit_df is: Limit BTC 1.2 XRP 600 Then self.values becomes Balance Pending CryptoAddress BTC 1.2 0 xxx ETH 53.1 0 yyy XRP 600.0 0 zzz :param currencies_df: :return: None, operates in self.values in place """ for currency, limit in limit_df.iteritems(): if currency in self.values.index: new_value = min(self.values.loc[currency, 'Balance'], limit) if new_value == 0: print('Removing {} from portfolio'.format(currency)) self.values.drop(currency, inplace=True) else: print('new limit for {} is {}'.format(currency, new_value)) self.values.loc[currency, 'Balance'] = new_value self.values.loc[currency, 'Balance'] = new_value def to_s3(self, time_sec): """ Store self.values in the given key """ if os.environ['PORTFOLIO_REPORT'] == 'True': assert self.values.index.name == 'Currency' bucket = config.s3_client.Bucket(config.PORTFOLIOS_BUCKET) s3_key = '{account}/{time}.csv'.format(account=os.environ['EXCHANGE_ACCOUNT'], time=time_sec) _, temp = tempfile.mkstemp() self.values.to_csv(temp) bucket.upload_file(temp, s3_key) def remove_transaction(buy_df, currency): columns = [c for c in buy_df.columns if c.startswith('Buy')] buy_df.loc[currency, columns] = 0 def apply_min_transaction_size(market, buy_df, base): """ Minimum transaction size is 50K Satoshis or 0.0005 BTC""" # add a column to buy_df that is the amount of the transaction in SATOSHI column = 'Buy ({base})'.format(base=base) buy_df.loc[:, 'SAT'] = buy_df[column] * market.currency_chain_value(['BTC', base]) / SATOSHI below_min_transaction = np.abs(buy_df['SAT']) < MINIMUM_TRADE for currency, remove_flag in below_min_transaction.iteritems(): if remove_flag: satoshis = buy_df.loc[currency, 'SAT'] btc = buy_df.loc[currency, 'Buy (BTC)'] print("Removing {} from transactions. Amount in satoshis is {}, ({}BTC)".format(currency, satoshis, btc)) remove_transaction(buy_df, currency) def _market_name(base, currency): name = base + '-' + currency if name in exchange.market_names(): return name return None def apply_transaction_cost(buy): """ buy is a float, the amount of either currency or dollars to buy (if positive) or sell (if negative) """ try: buy *= 1.0 except: raise IOError('buy should be numeric') if buy > 0: buy -= buy * COMMISION else: buy += buy * COMMISION return buy if os.environ['LOGNAME'] == 'aws': print('Finished loading', __file__)
class Bruch(object): """ Class Bruch is the equivalent to a mathematical fraction. You can create a fraction by passing another fraction to the :func:`__init__` constructor, or by providing a nominator and a denominator. You can also use a static method called :func:`_Bruch_makeBruch` to create a fraction simply from a nominator. """ zaehler = 0 nenner = 0 def __init__(self, fractionOrNominator, denom=1): """ The Basic Constructor. Checks which type of arguments if has received (only var or var and standard) and calls the equivalent method for procession. :param fractionOrNominator: Is either a nominator integer or a Bruch object. :param denom: The optional denominator as kwargs, Standart value is one, because you can also create a fraction from just one value. """ if type(fractionOrNominator) is Bruch: self.is_fraction(fractionOrNominator) else: self.is_two_values(fractionOrNominator, denom) def is_two_values(self, nomi, denom): """ Gets called when there are two parameters given to the constructor. :param nomi: The nomincator for the fraction. :param denom: The denominator for the fraction. """ if type(nomi) is not int or type(denom) is not int: raise TypeError("You cannot create a fraction with floats!") if denom == 0: raise ZeroDivisionError("You cannot divide through zero!") self.zaehler = nomi self.nenner = denom def is_fraction(self, fraction): """ Gets called when the paramter of the constructor is a Bruchh object. :param fraction: The fraction that should be written to this object. """ if type(fraction.nenner) is float or type(fraction.zaehler) is float: raise TypeError("You cannot create a fraction with floats!") if fraction.nenner == 0: raise ZeroDivisionError("You cannot divide through zero!") self.zaehler = fraction.zaehler self.nenner = fraction.nenner def __eq__(self, other): """ Checks if two fractions are equal in their value, meaning that the nominator and denominator match. :param other: The fraction that is compared to this object. :return: Returns a boolean value which is set true, if both fractions match. """ if type(other) is int: return int(self) == other return self.zaehler == other.zaehler and self.nenner == other.nenner def __gt__(self, other): """ Checks if the objects value in float is greater than the given fractions. :param other: The fraction that is compared to this object. :return: Returns a boolean value that is true if this objects value is greater. """ return float(self) > float(other) def __lt__(self, other): """ Checks if the objects value in float is less than the given fractions. :param other: The fraction that is compared to this object. :return: Returns a boolean value that is true if this objects value is less. """ return float(self) < float(other) def __ge__(self, other): """ Checks if this object is NOT less than the given fraction. :param other: The fraction that is compared to this object. :return: Returns a boolean value that is true if this objects is not less. """ return not (self > other) def __le__(self, other): """ Checks if this object is not greater than the given fraction. :param other: The fraction that is compared to this object. :return: Returns a boolean value that is true if this object is not greater. """ return not (self > other) def __float__(self): """ Show this objects value in float value. :return: Returns the equivalent float value for the fraction. """ return self.zaehler / self.nenner def __int__(self): """ Show this objects value in int value. :return: Returns the rounded equivalent int value for the fraction. """ return round(self.zaehler / self.nenner) def __complex__(self): """ Shows the objects value in complex value. :return: Returns the equivalent complex value for the fraction. """ return complex(self.zaehler / self.nenner) def __invert__(self): """ Creates a fraction that contains the reciprocal value of this object. :return: Returns a fraction that hast the reciprocal values of this object. """ return Bruch(self.nenner, self.zaehler) def __repr__(self): """ Shows the objects value in string with the format ( integer value of fraction ). :return: Returns a string containing the equivalent of the int value of this object. """ return '('+str(round(self.zaehler / self.nenner))+')' def __abs__(self): """ Shows this objects absolute values. :return: Returns a fraction with the absolute equivalent of this object. """ return Bruch(abs(self.zaehler), abs(self.nenner)) def __neg__(self): """ Shows this objects negation. :return: Returns a fraction with the equivalent values of this objects negation. """ return Bruch(-self.zaehler, self.nenner) def __str__(self): """ Shows this object as a string. Whole fraction will be displayed in their int equivalent. Other fractions will be schon in (nominator/denominator) like format. :return: Returns a string with this objects equivalent sting values. """ if self.nenner == 1: return '(%s)' % self.zaehler elif self.zaehler < 0 and self.nenner < 0: return '(%s/%s)' % (abs(self.zaehler), abs(self.nenner)) else: return '(%s/%s)' % (self.zaehler, self.nenner) def __iter__(self): """ Generates a iterable object from this object (list, tuple, ...). :return: Returns a iterable object from containing this objects values. """ yield self.zaehler yield self.nenner @staticmethod def _Bruch__makeBruch(value): """ Generates a simple fraction with a the given value as nominator. :param value: The nominator for the fraction. :return: Returns a fraction with the given value as denominator. """ if type(value) is int: return Bruch(value, 1) else: raise TypeError("You cannot create a fraction with this value!") def __pow__(self, power, modulo=None): """ Returns this objects to the power of the given value. :param power: The power that this object should be empowered with. :param modulo: The modulo value, standard value is none :return: Returns a fraction that is empowered to power, with the equivalent values of this object. """ if type(power) is not int: raise TypeError("Cannot power the fraction with this value!") else: z = self.zaehler ** power n = self.nenner ** power return Bruch(z, n) def __add__(self, other): """ Checks if the parameter is an int or a fraction and processes it accordingly, meaning it adds them to this object. For this, the least common factor has to be found. :param other: Can be either an int value or a fraction. :return: Returns the value of the parameter added to this object """ if type(other) is Bruch: newnenner = self.nenner * other.nenner zaehlers = self.zaehler * other.nenner zaehlero = self.nenner * other.zaehler return Bruch(zaehlers + zaehlero, newnenner) if type(other) == int: newz = other * self.nenner + self.zaehler return Bruch(newz, self.nenner) else: raise TypeError("No floats allowed!") def __iadd__(self, other): """ Called when the incremental operator for + is used (+=). Add given parameter to this object. :param other: The value that should be added to this object. :return: Returns the addition of this object and the parameter. """ return self + other def __radd__(self, other): """ Called when reverse addition is used, meaning and int value plus a fraction. :param other: The value that should be added to this object. :return: Returns the added value of this object and the parameter. """ return self + other def __sub__(self, other): """ Utilizes the negated addition to subtract the given parameter from this object. :param other: The value that should be subtracted from this object. :return: Returns the subtracted value of this object and the parameter. """ return self + (-other) def __rsub__(self, other): """ Called when reverse subtraction is used, meaning and int value minus a fraction. :param other: The value to be subtracted from this object. :return: Returns the subtracted value of this object and the parameter. """ return Bruch(other) - self def __isub__(self, other): """ Called when the incremental paramter for - is used (-=). Subtracts given parameter from this objects. :param other: The value that should be subtracted from this object. :return: Returns the subtracted value of this object and the parameter. """ return self - other def __mul__(self, other): """ Checks if the parameter is an int or a fraction and processes the outcome accordingly. :param other: The value with which this object should be multiplied with. :return: Returns the multiplied values of this object and the parameter. """ if type(other) is Bruch: return Bruch(self.zaehler * other.zaehler, self.nenner * other.nenner) elif type(other) is int: return Bruch(self.zaehler * other, self.nenner) else: raise TypeError("No other than int allowed!") def __rmul__(self, other): """ Called when reverse multiplication is used, meaning a int times a fraction. :param other: The value that this object should be multiplied with. :return: Returns the multiplied value of this object and the parameter. """ return self * other def __imul__(self, other): """ Called when the incremental parameter for * is used (*=). Multiplies given parameter with this object. :param other: The value with which this object should be multiplied with. :return: Retuns the multiplied value of this object and the parameter. """ return self * other def __truediv__(self, other): """ Checks if the parameter is an int or a fraction and processes the outcome accordingly. :param other: The value that this object should be divided with. :return: """ if self.zaehler == 0: raise ZeroDivisionError("Cannot use the cross product when nominator is zero!") elif type(other) is Bruch: return self * ~other else: return Bruch(self.zaehler, self.nenner * other) def __rtruediv__(self, other): """ Called when reverse division is used, meaning a int divided by a fraction. :param other: The value with which this object should be divided with. :return: Returns the divided value of this object and the parameter. """ return self/other def __itruediv__(self, other): """ Called when the incremental parameter for / is used (/=). Divides this object by the given parameter. :param other: The value with which this object should be divided with. :return: Returns the divided value of this object and the parameter. """ return self/other
""" The main driver module for the code =================================== This module contains the main driver function for the code, which should be called by the executable of the program. """ import argparse from .renderdriver import render_driver def main(): """The main driver function""" parser = argparse.ArgumentParser( description='Plotting the molecule from an input file', epilog='by Tschijnmo TSCHAU <[email protected]>' ) parser.add_argument('INPUT', metavar='FILE', type=str, nargs=1, help='The name of the input file') parser.add_argument('-r', '--reader', type=str, default='gjf', choices=['gjf', ], help='The reader for the input file') parser.add_argument('-o', '--output', type=str, help='The output file, default to input file name' 'with extension changed to png') parser.add_argument('-k', '--keep', action='store_true', help='Keep the pov-ray input file') parser.add_argument('-p', '--project-option', type=str, help='The project level JSON/YAML configuration file') parser.add_argument('-m', '--molecule-option', type=str, help='The molecule level JSON/YAML configuration file' ', can be set to `input-title` to use the title of' ' the input file') args = parser.parse_args() render_driver( args.INPUT[0], args.reader, args.molecule_option, args.project_option, args.output, args.keep ) return 0
# 1. Определение количества различных подстрок с использованием хеш-функции. Пусть на вход функции дана строка. Требуется вернуть количество различных подстрок в этой строке. # # Примечания: # # * в сумму не включаем пустую строку и строку целиком; # # * без использования функций для вычисления хэша (hash(), sha1() или любой другой из модуля hashlib задача считается не решённой. def count_substring(s: str): set_hash = set() for i in range(len(s) - 1): for j in range(i + 1, len(s) + 1): set_hash.add(hash(s[i:j])) counter = len(set_hash) - 1 return counter my_string = input('Введите строку:') count = count_substring(my_string) print(f'В строке "{my_string}" есть {count} подстрок')
# print(10 + 20) # print(int(10).__add__(int(20))) # print.__call__(int.__add__(int(10), int(20))) # bob = { "name": "Bob", "last": "the Builder", "age": 42 } # bob = object.__new__(dict).__init__(...) # print("Hello world!") # print.__call__(str("Hello world")) # print(bob.name) # print.__call__(Person.__getattribute__(bob, "name")) class Car: def __init__(self, acceleration=5): self.max_speed = 100 self.curr_speed = 0 self.acceleration = acceleration def drive(self): self.curr_speed += self.acceleration if self.curr_speed > self.max_speed: self.curr_speed = self.max_speed print("Car currently driving at", self.curr_speed, "kph") toyota = Car(5) toyota = object.__new__(Car) Car.__init__(toyota, 5) toyota.drive() toyota = Car.drive(toyota)
#Python3 program to implement Leetcode 74. Search a 2D Matrix #Problem statememt: ''' Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true Example 2: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false ''' #linear serach algorithm that would just go through the matrix 2D array linearly and search for the target def searchMatrix_LINEAR_SEARCH(matrix, target): #base case: if not matrix: return False #search through the array linearly: for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == target: return True return False #Binary search approach: #Time complexity: o(logn x logn) #we will perform two binary search, one for the outer layer to look for the element that matches the target #The other one would be for comparing the last element of each row with the target value to pick which row that the target would be potentially be stored in def searchMatrix_BINARY_SEARCH(matrix, target): #base case: if not matrix or not matrix[0]: return False #variable intialization: left = 0 right = len(matrix[0]) - 1 #row that would contain the target value row = targetRow(matrix, target) #bianry search: while left < right: mid = (left + right) // 2 #THE TARGET IS GREATER THAN THE VALUE WE ARE LOOKING AT!!!! if(matrix[row][mid] < target): left = mid + 1 else: right = mid return matrix[row][left] == target #Helper method to perform the second binary search to look for the row that would contain the target value def targetRow(matrix, target): m = len(matrix) n = len(matrix[0]) left = 0 right = m - 1 #binary search algorithm: while left < right: mid = (left + right) // 2 print(mid) # print(matrix[mid][n-1]) #comapre the last element in each row with the target if(matrix[mid][n-1] < target): left = mid + 1 else: right = mid return left #driver code to run the program: def main(): print("TESTING SEARCH A 2D MATRIX...") test_matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 test_matrix_01 = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target01 = 13 print(searchMatrix_LINEAR_SEARCH(test_matrix, target)) print(searchMatrix_LINEAR_SEARCH(test_matrix_01, target01)) print("") print(searchMatrix_BINARY_SEARCH(test_matrix, target)) print(searchMatrix_BINARY_SEARCH(test_matrix_01, target01)) print("END OF TESTING...") main()