text
stringlengths
37
1.41M
def function1(): """simple function""" return 5 def function2(x): """square a number""" return x*x-3 def function5(x,y,z): """multiply and subtract""" return x*y*z-3 def main(): "print linear combination" print function1() - function2(5) + function5(1,2,3)
from colorama import * init() class Bank: """Bank class with method and attributes to use with different bank instances""" def __init__(self, bankname, ifcs_code, branch, location): self.bankname = bankname self.ifcs_code = ifcs_code self.branch = branch self.location = location def bankinfo(self): print(Fore.RED + "*" * 65 +Fore.RESET) print("Thank you for choosing " + self.bankname, "\nIFSC Code: " + self.ifcs_code, "\nBranch: " + self.branch, "\nLocation: " + self.location) print (Fore.RED + "*" * 65 + Fore.RESET) class Customer(Bank): """Customer class that inherits bank attributes, also has method and attributes to use with different customer instances""" def __init__(self, bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact): super ().__init__ (bankname, ifcs_code, branch, location) self.customer_ID = customer_ID self.customer_name = customer_name self.customer_address = customer_address self.contact = contact def getaccountinfo(self): """method and attributes to use with different customer account instances""" print ("\nHi " + self.customer_name + ", Welcome to your Account - your customer information is:\nCustomer ID: " + self.customer_ID, "\nCustomer Address: " + self.customer_address, "\nContact: " + self.contact) r1 = Customer("Bank of Singapore", "xddg789", "Singapore Main", "123 Singapore Circle", "", "John Smith", "324 Confluence St, East Singapore, Singapore", "+88987765454") r1.bankinfo() class Account(Customer): """Account class that inherits from Customer class with method and attributes to use with different account instances""" def __init__(self, bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact, accountID, balance=0): super ().__init__ (bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact) self.accountID = accountID self.balance = balance def deposit(self, amount): """make a deposit""" if amount > 0: self.balance += amount return True return False def withdraw(self, amount): """make a withdraw""" if amount > self.balance or amount < 0: try: raise ValueError except ValueError: print(Fore.RED + "insufficient funds" + Fore.RESET) else: self.balance -= amount def get_balance(self): """check the balance""" print(Fore.RED + "Your current account balance is $" + str(self.balance) + Fore.RESET) r2 = Account ("Bank of Singapore", "xddg789", "Singapore Main", "123 Singapore Circle", "", "John Smith", "324 Confluence St, East Singapore, Singapore", "+88987765454", "ACCT87678") class SavingsAccount(Account): """SavingsAccount class that inherits from Account class, with method and attributes to use with different account instances""" def __init__(self, bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact, accountID, balance, minbalance=0): super ().__init__ (bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact, accountID, balance) self.minbalance = minbalance def getsavingaccountinfo(self): """method and attributes to use with different customer account instances""" print ("\nHi " + self.customer_name + ", Welcome to your Savings Account - your customer information is:\nCustomer ID: " + self.customer_ID, "\nCustomer Address: " + self.customer_address, "\nContact: " + self.contact, "\nYour Minimum Balance is set to: " + str(self.minbalance)) r3 = SavingsAccount ("Bank of Singapore", "xddg789", "Singapore Main", "123 Singapore Circle", "", "John Smith", "324 Confluence St, East Singapore, Singapore", "+88987765454", "SAV87678", 0) class Atm(SavingsAccount): """Atm class that inherits from SavingsAccount class, with menus to select account type and withdraw, deposit, balance and exit""" def __init__(self, bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact, accountID, balance): super ().__init__ (bankname, ifcs_code, branch, location, customer_ID, customer_name, customer_address, contact, accountID, balance) customer1 = Atm("Bank of Singapore", "xddg789", "Singapore Main", "123 Singapore Circle", "", "John Smith", "324 Confluence St, East Singapore, Singapore", "+88987765454", "JS8767", 0) customer1.customer_ID = str (input (Fore.RED + "*" * 65 + Fore.RESET + "\nWelcome to the Bank of Singapore - Please enter you Customer ID1: ")) print ("Account ID: "+ customer1.accountID + "\n" + Fore.RED + "*" * 65 + Fore.RESET) if customer1.customer_ID != 0: def menu(): print ("*" * 65) print ("[1] Account") print ("[2] Savings Account") print ("*" * 65) menu () choice = int (input ("Please choose Account or Savings Account: ")) while choice != 0: if choice == 1: customer1.getaccountinfo() break elif choice == 2: customer1.getsavingaccountinfo() break else: print (Fore.RED + "Invalid Option" + Fore.RESET) menu () choice = int (input ("Please choose Account or Savings Account: ")) else: print("not this") if customer1.customer_ID != 0: def menu(): print ("*" * 48) print ("[1] Withdrawal") print ("[2] Deposit") print ("[3] Balance") print ("[0] Exit and return card") print ("*" * 48) menu () choice = int (input ("Please select Withdrawal, Deposit, Balance or Exit and return card: ")) while choice != 0: if choice == 1: try: amount = int (input ("Please enter Withdraw Amount or enter Q to sign-off $")) customer1.withdraw (amount) customer1.get_balance () except ValueError: break elif choice == 2: try: amount = int (input ("Please enter Deposit Amount or enter Q to sign-off $")) customer1.deposit (amount) customer1.get_balance () except ValueError: break elif choice == 3: customer1.get_balance() else: print (Fore.RED + "Invalid Option" + Fore.RESET) menu () choice = int (input ("Please select Withdrawal, Deposit, Balance or Exit and return card: ")) print ("*" * 48 + "\n") print (Fore.RED + "Thank you for using Bank of Singapore. Please remove your card." + Fore.RESET) else: print("not this")
#!/usr/bin/env python3 import random EMPTY = 0 FIRST_PLACE = 0 HALF = 2 ONE_RIGHT = 1 ONE_LEFT = 1 MOVE_ONE = 1 LAST_CELL = 1 class WordTracker(object): """ This class is used to track occurrences of words. The class uses a fixed list of words as its dictionary (note - 'dictionary' in this context is just a name and does not refer to the pythonic concept of dictionaries). The class maintains the occurrences of words in its dictionary as to be able to report if all dictionary's words were encountered. """ def __init__(self, word_list): """ Initiates a new WordTracker instance. :param word_list: The instance's dictionary. """ self.original_list = list(word_list) self.dictionary_words = self.original_list[:] #copy the list self.all_encountered_words = [] self.quicksort(self.dictionary_words) #get a sorted list def __contains__(self, word): """ Check if the input word in contained within dictionary. For a dictionary with n entries, this method guarantees a worst-case running time of O(n) by implementing a binary-search. :param word: The word to be examined if contained in the dictionary. :return: True if word is contained in the dictionary, False otherwise. """ #look if the word is in the list: if self.binary_search(self.dictionary_words, word): return True else: False def encounter(self, word): """ A "report" that the give word was encountered. The implementation changes the internal state of the object as to "remember" this encounter. :param word: The encountered word. :return: True if the given word is contained in the dictionary, False otherwise. """ if self.__contains__(word): #check if the word is in the list of words #we make a list in a certain order self.encountered_words_sort(self.all_encountered_words, word) return True else: return False def encountered_words_sort(self, encounter_word, word): """ put the given word in the right place in the list. if there is the same word, it only enters it once """ if len(self.all_encountered_words) == EMPTY: #if the list is empty self.all_encountered_words.insert(FIRST_PLACE, word) bottom = FIRST_PLACE #beginning of the list top = len(encounter_word)-LAST_CELL while top >= bottom: middle = (top + bottom) // HALF #check if the word in the middle is larger or smaller then the #input word if encounter_word[middle] < word: bottom = middle + ONE_RIGHT #change the bottom elif encounter_word[middle] > word: top = middle - ONE_LEFT else: return # we check again now inorder to insert the word if encounter_word[middle] > word: self.all_encountered_words.insert(middle, word) if encounter_word[middle] < word: self.all_encountered_words.insert(middle + ONE_RIGHT, word) else: return return False def encountered_all(self): """ Checks whether all the words in the dictionary were already "encountered". :return: True if for each word in the dictionary, the encounter function was called with this word; False otherwise. """ # if the input list of words is as the same length as the list of #the encountered words, then all the words have been encountered. if len(self.all_encountered_words) == len(self.dictionary_words): return True else: return False def reset(self): """ Changes the internal representation of the instance such that it "forget" all past encounters. One implication of such forgetfulness is that for encountered_all function to return True, all the dictionaries' entries should be called with the encounter function (regardless of whether they were previously encountered ot not). """ self.all_encountered_words = [] #reset it by making a new list. def binary_search(self, sorted_data, word): """returns the index of the word in the data, if it was found. None otherwise""" bottom = FIRST_PLACE #The first cell in the suspected range top = len(sorted_data)-LAST_CELL #the last cell while top >= bottom: middle = (top+bottom) // HALF #check if the word in the middle is larger or smaller then the #input word if sorted_data[middle] < word: bottom = middle + ONE_RIGHT elif sorted_data[middle] > word: top = middle - ONE_LEFT else: return True return False def quicksort(self, data): """quick-sorts a list """ self._quicksort_helper(data, FIRST_PLACE, len(data)) return data def swap(self, data, ind1, ind2): """swaps two items in a list""" data[ind1], data[ind2] = data[ind2], data[ind1] def partition(self, data, start, end): """partitions the list (from start to end) around a randomly selected pivot""" #assumes start<end #select a random pivot, place it in the last index pivot_ind = random.randrange(start, end) pivot_val = data[pivot_ind] self.swap(data, pivot_ind, end-ONE_LEFT) pivot_ind = end-ONE_LEFT end -= ONE_LEFT while start < end: #check if the chosen item is larger or smaller then the #one in the pivot if(data[start]) < pivot_val: start += ONE_RIGHT elif(data[end-ONE_LEFT]) >= pivot_val: end -= ONE_LEFT else: self.swap(data, start, end-ONE_LEFT) start += ONE_RIGHT end -= ONE_LEFT #swap pivot into place. self.swap(data, pivot_ind, start) return start def _quicksort_helper(self, data, start, end): """A helper fucntion for quick-sort's recursion.""" #start is the first index to sort, #end is the index _after_ the last one if start < end-ONE_LEFT: pivot_index = self.partition(data, start, end) self._quicksort_helper(data, start, pivot_index) self._quicksort_helper(data, pivot_index + MOVE_ONE, end)
#Data type notes splitter_length = 100 splitter_character = '*' section_splitter = '\n' + splitter_character * splitter_length + '\n' a=11.9 print('When casting with the int function:') print('int() will round down...') print('a = ' + str(a) + ' and then int(a) = ' + str(int(a)) + ',if you don\'t believe me? Check the code homie...') print(section_splitter) #None print('when assigned as a value None will not print in the REPL') print('try it in the REPL') print('>>> a = None') print('>>>a') print('See what happened?') print(section_splitter) #bool x = 0 y = -1 print('bool will treat 1 or any non 0 length string\\list as True, and any 0 length string//list or 0 int//float as False') print('x = ' + str(x) + ' and then bool(x) = ' + str(bool(x)) + ',if you don\'t believe me? Check the code homie...') print('y = ' + str(y) + ' and then bool(y) = ' + str(bool(y)) + ',if you don\'t believe me? Check the code homie...')
import pygame import math X = 0 Y = 1 Z = 2 COLOR = 3 PLANE_X = X PLANE_Y = Y PLANE_Z = Z class PointCloud: """ A class responsible for loading, calculating and transforming point clouds """ def __init__(self, filename): """ Constructor loads point cloud from text file formatted like this: X; Y; Z X; Y; Z X; Y; Z ... X; Y; Z where every X, Y and Z is a floating point number. """ self.points = [] self.max_x, self.max_y, self.max_z = 0, 0, 0 self.min_x, self.min_y, self.min_z = 0, 0, 0 self.scale = 3 self.offset_x, self.offset_y = 0, 0 data = open(filename, "r").readlines() for line in data: if not line.split(): continue line = line.replace("\n", "").split(";") point = [float(line[0]), float(line[1]), float(line[2])] self.points.append(point) if point[X] > self.max_x: self.max_x = point[X] elif point[X] < self.min_x: self.min_x = point[X] if point[Y] > self.max_y: self.max_y = point[Y] elif point[Y] < self.min_y: self.min_y = point[Y] if point[Z] > self.max_z: self.max_z = point[Z] elif point[Z] < self.min_z: self.min_z = point[Z] self.normalise() def sort(self): """ Sorts every point cloud point from the furthest one to the closest. """ self.points.sort(key = lambda x: [ x[PLANE_Z], x[PLANE_X], x[PLANE_Y] ]) def normalise(self): """ Moves point cloud so that there aren't any negative coordinates. """ self.max_x -= self.min_x self.max_y -= self.min_y self.max_z -= self.min_z for i in range(len(self.points)): self.points[i][X] -= self.min_x self.points[i][Y] -= self.min_y self.points[i][Z] -= self.min_z self.min_x = 0 self.min_y = 0 self.min_z = 0 def rotate_cloud(self, angle, axis): """ Rotates entire point cloud around an axis by a angle in degrees. """ if not angle: return angle = math.radians(angle) if axis == X: A = 1 B = 2 CA = self.max_y / 2 CB = self.max_z / 2 elif axis == Y: A = 0 B = 2 CA = self.max_x / 2 CB = self.max_z / 2 elif axis == Z: A = 0 B = 1 CA = self.max_x / 2 CB = self.max_y / 2 for i in range(len(self.points)): s = math.sin(angle) c = math.cos(angle) self.points[i][A] -= CA self.points[i][B] -= CB xnew = self.points[i][A] * c - self.points[i][B] * s ynew = self.points[i][A] * s + self.points[i][B] * c self.points[i][A] = xnew + CA self.points[i][B] = ynew + CB self.sort() def get_pos(self, point, width=0, height=0): """ Converts a 3D point to a 2D point, considers a render scale and offsets """ x, y, z = point[PLANE_X] * self.scale, point[PLANE_Y] * self.scale, point[PLANE_Z] * self.scale X_offset, Y_offset = 0, 0 x_p, y_p = x - z * X_offset + self.offset_x, y - z * Y_offset + self.offset_y if width: x_p += (width - self.max_x * self.scale) / 2 if height: y_p += (height - self.max_y * self.scale) / 2 return (int(x_p), int(y_p))
# # @lc app=leetcode.cn id=104 lang=python3 # # [104] 二叉树的最大深度 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # def maxDepth(self, root: TreeNode) -> int: # res = [] # self.helper(root, 1, res) # return max(res) # def helper(self, node, depth, res): # if not node: # res.append(depth - 1) # return # self.helper(node.left, depth + 1, res) # self.helper(node.right, depth + 1, res) def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 left_height = self.maxDepth(root.left) right_height = self.maxDepth(root.right) return max(left_height, right_height) + 1 # @lc code=end
# # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): n = int(input()) if n <= 3 : print(n - 1) else: if n % 2 == 0: #one move make it to two and one susbtraction to make it 1 print(2) else: #substract to make it even and another two move to make it 1 print(3) def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main()
# # author: vongkh # created: Wed Nov 25 2020 # from sys import stdin, stdout # only need for big input def solve(): d, k = map(int, input().split()) #we find game breaking point #observe that the player 2 can choose his point on y = x line #the last point of y = x line is the breaking point => player 2 wins #else y = x + 1 is the breaking point which player 1 can choose his strategy for x in range(0,d,k): y = x + k if x * x + x * x > d * d : break if x * x + y * y > d * d: print("Utkarsh") return print("Ashish") def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main()
from sys import stdin, stdout # only need for big input def read_int_from_line(): return list(map(int, input().split())) def solve(): n = int(input()) a = read_int_from_line() #range_sum[i] = a[0] + ... + a[i] : the position robot ends up after i move range_sum = [0] * n #overshoot[i] the right-most position during move a[0], ..., a[i], starting from 0 overshoot = [0] * n range_sum[0] = a[0] overshoot[0] = max(range_sum[0], overshoot[0]) for i in range(1, n): range_sum[i] = a[i] + range_sum[i-1] overshoot[i] = max(overshoot[i-1], range_sum[i]) maxPos = 0 curPos = 0 #use straight forward simulation to find the maximum position for i in range(n): maxPos = max(maxPos, curPos + overshoot[i]) curPos += range_sum[i] print(maxPos) def main(): solve() if __name__ == "__main__": main()
from sys import stdin, stdout # only need for big input def read_int_from_line(): return list(map(int, input().split())) def solve(): #since n is big, we read input n as string n = input() num_digit = len(n) #state in binary representation represents how we delete/keep digits #i-th digit of state = 0 means we delete i-th digit of n state = 0 # 111..1 is the max_state which we keeps everything MAX_STATE = (1 << num_digit) - 1 ans = num_digit while state <= MAX_STATE : #remember an integer is divisible by 3 if and only if #the sum of its digit is divisible by 3 digit_sum = 0 delete_count = 0 for i in range(num_digit): #check if we keep i-th digit in this state if ((1 << i) & state) != 0 : digit_sum += int(n[i]) else: #if not, it means we deleted the i-th digit delete_count += 1 if digit_sum % 3 == 0 and ans > delete_count: ans = delete_count state += 1 #it is not allowed to delete all digits if ans == num_digit: ans = -1 print(ans) def main(): solve() if __name__ == "__main__": main()
#import programs import os import csv #set csvpath to open the csvfile csvpath = os.path.join("election_data.csv") #set the counts for all the candiates to 0, and as it scans through the row and sees the deligate it will count #alternatively I think a diction could be created as it scans through or the dict read could be used #I'm going to work on these alternative code for practice, but submit this since it works! khan = 0 correy = 0 li = 0 otooley = 0 vote = 0 # open the file, printing for confirmation that the correct file is opening, and skipping the first line during the loop # as stated above, each row is a vote cast so the vote count tallying up on each rown # similarly for each of the candidates, there is a vote count if there name is recognized with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) csv_header=next(csvreader) for row in csvreader: vote = vote + 1 if row[2] == "Khan": khan = khan + 1 elif row[2] == "Correy": correy = correy + 1 elif row[2] == "Li": li = li + 1 elif row[2] == "O'Tooley": otooley = otooley + 1 #calculations & formating. I definetly think creating a dictionary as one loops through the rows would down size the rows and the codelines #also, I can not get in the print out for three decimal places. Need to continue working on this percent_khan= (khan/vote) * 100 format_per_khan = round(percent_khan, 3) format2_per_khan = "{0}%".format(format_per_khan) percent_correy= (correy/vote) * 100 format_per_correy = round(percent_correy, 3) format2_per_correy = "{0}%".format(format_per_correy) percent_li= (li/vote) * 100 format_per_li = round(percent_li, 3) format2_per_li= "{0}%".format(format_per_li) percent_otooley= (otooley/vote) * 100 format_per_otooley = round(percent_li, 3) format2_per_otooley= "{0}%".format(format_per_otooley) #Finally, a bit of logic to determine the winner. Khan is first and is the winner, but I rearranged order to test this winner = "winner" x = 0 if khan > x: winner = "Khan" if correy > khan: winner = "Correy" if li > correy: winner = "Li" if otooley > li: winner = "O'tooley" #create path for the test file results = os.path.join("pypollanalysis.txt") #open and write to txt, and then read and print what has been written with open(results, "w+") as analysis: analysis.writelines("Election Results\n") analysis.writelines("------------------------------------------------\n") analysis.writelines("Total Votes: " + str(vote) + "\n") analysis.writelines("------------------------------------------------\n") analysis.writelines("Khan: " + format2_per_khan + " (" + str(khan) + ")\n") analysis.writelines("Correy: " + format2_per_correy + " (" + str(correy) +")\n") analysis.writelines("Li: " + format2_per_li + " (" + str(li) +")\n") analysis.writelines("O'Tooley: " + format2_per_otooley + " (" + str(otooley) +")\n") analysis.writelines("------------------------------------------------\n") analysis.writelines("The Winner of the election is : " + winner + "\n") analysis.writelines("------------------------------------------------\n") readanalysis = open(results, "r") read = readanalysis.readlines() for lines in read: print(lines)
import math # Basic logical statements x = int(input('Enter a number: ')) y = int(input('Enter another number: ')) areEqual = (x == y) if areEqual: print('The numbers are equal') else: print('The numbers are not equal') if x > y: print('The first is bigger') elif x < y: print('The second is bigger') else: print('The numbers are equal') print('But we already printed that message') xIsEven = x % 2 == 0 yIsEven = y % 2 == 0 if xIsEven and yIsEven: print('Both numbers are even') # what is the output of the following code? if x > 0: if y > 0: print('A') else: if y > 0: print('B') elif y < 0: print('C') else: print('D')
class Node(object): def __init__(self, data=None): self.data = data self.next = None class Stack(object): def __init__(self): self.head = Node() def add(self,data): new_node = Node(data) ptr = self.head while ptr.next is not None: ptr = ptr.next ptr.next = new_node def push_stack(self, data): ptr = self.head new_node = Node(data) new_node.next = self.head.next self.head.next = new_node def pop(self): if self.head.next is not None: ptr = self.head.next self.head.next = ptr.next def display(self): elems=[] cur_node = self.head while cur_node.next is not None: cur_node=cur_node.next elems.append(cur_node.data) print (elems) def find_max(self): elems=[] cur_node = self.head while cur_node.next is not None: cur_node=cur_node.next elems.append(cur_node.data) return max(elems) s = Stack() s.add(1) s.add(3) s.add(4) s.add(6) s.add(8) s.add(2) s.push_stack(20) s.push_stack(10) s.display() s.pop() s.display() print(s.find_max())
import numpy as np # imports from pandas import read_csv import plotly.express as px # read data from disk faithful = read_csv('./data/faithful.csv') def hist(bins = 30): # calculate the bins x = faithful['waiting'] counts, bins = np.histogram(x, bins=np.linspace(np.min(x), np.max(x), bins+1)) bins = 0.5* (bins[:-1] + bins[1:]) p = px.bar( x=bins, y=counts, title='Histogram of waiting times', labels={ 'x': 'Waiting time to next eruption (in mins)', 'y': 'Frequency' }, template='simple_white' ) return p plot = hist() plot.show() hist()
n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) media = (n1 + n2)/2 if media < 5.0: print('Sua média é {:.1f}, você foi REPROVADO!'.format(media)) elif media >= 5.0 and media < 6.9: print('Sua média é {:.1f} e você está em RECUPERAÇÃO!'.format(media)) elif media >= 7: print('Sua média é {:.1f} e você foi APROVADO!'.format(media))
import random aluno_1 = input('Digite o nome do primeiro aluno: ') aluno_2 = input('Digite o nome do segundo aluno: ') aluno_3 = input('Digite o nome do terceiro aluno: ') aluno_4 = input('Digite o nome do quarto aluno: ') lista = [aluno_1, aluno_2, aluno_3, aluno_4] escolhido = random.choice(lista) print('O escolhido foi {}!'.format(escolhido))
pt = int(input('Primeiro termo: ')) r = int(input('Razão: ')) t = pt cont = 1 total = 0 mais = 10 while mais != 0: total = total + mais while cont <= total: print('{} -> '.format(t), end='') t += r cont += 1 print('PAUSA') mais = int(input('Quantos termos vc quer mostrar a mais? ')) print('Progressão finalizada com {} termos mostrados.'.format(total))
from random import randint computador = randint(0, 5) jogador = int(input("Vou pensar emum numero de 0 a 5, tente adivinhar: ")) if jogador == computador: print('Parabéns, você adivinhou! Eu pensei no número {}'.format(computador)) else: print('Não foi dessa vez! eu pensei no número {}!'.format(computador))
c = 1 for i in range(1, 11): for c in range(1, 11, 1): print('{} x {} = {}'.format(i, c, i*c)) #OU num = int(input('Digite um número para ver sua tabuada: ')) for c in range(1, 11): print('{} x {:2} = {}'.format(num, c, num*c))
dias = int(input('Você alugou o carro por quantos dias? ')) km = float(input('Quantos km foram rodados? ')) preco = (60*dias)+(0.15*km) print('O preço do aluguel será R${:.2f}'.format(preco))
#num = float(input('Digite um numero: ')) #num_int = int(num) #print('o numero {} tem a parte inteira {}'.format(num, num_int)) from math import trunc num = float(input('Digite um numero: ')) print('o numero {} tem a parte inteira {}'.format(num, trunc(num)))
import random Number = random.randint(1,9) chances = 0 while chances<5: Guess = int(input("enter your guess :- ")) if Guess==Number: print("You Won :) !") break elif Guess<Number: print("Guess higher than" + str(Guess)) elif Guess>Number: print("Guess lower than" + str1(Guess)) else: print("try again") chances = chances+1 if not chances<5: print("You Lost :( !")
import sklearn.linear_model def build_linear_model(current_obervations_values, current_decision_values): # it is a linear model current_regression = sklearn.linear_model.LinearRegression() # fit in the observation current_regression.fit( X = current_obervations_values, y = current_decision_values ) # return it return current_regression def print_model_details(current_regression, current_observations_variables, current_decision_variable): print("Printing model details for "+ str(current_decision_variable)) print("Intercept = " + str(current_regression.intercept_)) print("Variables and their coeficient") for i in range(len(current_observations_variables)): print(str(current_observations_variables[i]) + " = " + str(current_regression.coef_)) def make_prediction(current_regression, new_observations, current_decision_variable): print("Making prediction for " + str(current_decision_variable)) new_prediction = current_regression.predict(new_observations) for i in range(len(new_observations)): print(str(new_observations[i]) + " = " + str(new_prediction[i])) if __name__ == "__main__": # set to current working directory import os abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # the dataset is a concrete dataset # this can be read from file as well # simple example with 20 observations and only 2 variables, there is more current_observations_variables = ["cement", "water"] current_obervations_values = [ [540,162],[540,162],[332.5,228],[332.5,228],[198.6,192],[266,228],[380,228],[380,228], [266,228],[475,228],[198.6,192],[198.6,192],[427.5,228],[190,228],[304,228],[380,228], [139.6,192],[342,228],[380,228] ] current_decision_variable = ["Concrete Strength"] current_decision_values = [ 79.99,61.89,40.27,41.05,44.3,47.03,43.7,36.45,45.85,39.29, 38.07,28.02,43.01,42.33,47.81,52.91,39.36,56.14,40.56 ] # build the linear regression model current_regression = build_linear_model(current_obervations_values, current_decision_values) # print model details print_model_details(current_regression, current_observations_variables, current_decision_variable) # use the linear regression model new_observations = [ [500,162], [330,162], [200,162] ] # make prediction make_prediction(current_regression, new_observations, current_decision_variable)
#*****CLASSES*************************************************************************# #*****USER****************************************************************************# class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {} def get_email(self): return self.email def get_name(self): return self.name def change_email(self, address): self.email = address print("Email for %s has been updated to %s!" % (self.name, self.email)) def __repr__(self): return "%s, %s, has recorded %i books!" % (self.name, self.email, len(self.books)) def __eq__(self, other_user): if self.name == other_user.name and self.email == other_user.name: return True else: return False def read_book(self, book, rating = None): self.book = {book:rating} def get_average_rating(self): rating_total = 0 count = 0 for e in self.books.values(): if e: rating_total+= e count += 1 try: return rating_total/count except ZeroDivisionError: return 0 #*****BOOK****************************************************************************# class Book(object): def __init__(self, title, isbn): self.title = title self.isbn = isbn self.rating = [] def get_title(self): return self.title def get_isbn(self): return self.isbn def set_isbn(self, isbn): self.isbn = isbn return "The ISBN for %s has been set to %i!" % (self.title, self.isbn) def add_rating(self, rating): if rating: if rating >=0 and rating <=4: self.rating.append(rating) else: print("Invalid Rating") def __eq__(self, other_Book): if self.title == other_Book.title and self.isbn == other_Book.isbn: return True else: return False def get_average_rating(self): rating_total = 0 for e in self.rating: rating_total += e if len(self.rating) > 0: return rating_total / len(self.rating) else: return 0 def __hash__(self): return hash((self.title, self.isbn)) def __repr__(self): return "%s by Unknown" % (self.title) #*****FICTION*************************************************************************# class Fiction(Book): def __init__(self, title, author, isbn): super().__init__(title, isbn) self.author = author def get_author(self): return self.author def __repr__(self): return "%s by %s" % (self.title, self.author) #*****NON_FICTION*********************************************************************# class Non_Fiction(Book): def __init__(self, title, subject, level, isbn): super().__init__(title, isbn) self.subject = subject self.level = level def get_subject(self): return self.subject def get_level(self): return self.level def __repr__(self): return "%s, a %s manual on %s" % (self.title, self.level, self.subject) #*****TOMERATER***********************************************************************# class TomeRater(object): def __init__(self): self.users = {} self.books = {} def __repr__(self): string = "TomeRater has following users: \n" for e in self.users: string += self.users[e].get_name() + "\n" string += "They have read the following books: \n" for e in self.books: string += e.get_title() + "\n" return string def __eq__(self, other_rater): if self.users == other_rater.users and self.books == other_rater.books: return True else: return False def create_book(self, title, isbn): return Book(title, isbn) def create_novel(self, title, author, isbn): return Fiction(title, author, isbn) def create_non_fiction(self, title, subject, level, isbn): return Non_Fiction(title, subject, level, isbn) def add_book_to_user(self, book, email, rating=None): if email not in self.users: print("No user with the email %s!" % (email)) user = self.users.get(email, None) if user: user.read_book(book, rating) if book not in self.books: self.books[book] = 0 self.books[book] += 1 book.add_rating(rating) def add_user(self, name, email, user_books = None): new_user = User(name, email) self.users[email] = new_user if user_books: for e in user_books: self.add_book_to_user(e, email) def print_catalog(self): print("Catalog list: ") for e in self.books.keys(): print(e) def print_users(self): print("User list: ") for e in self.users.keys(): print(e) def most_read_book(self): most_read_count = 0 most_read_book = None for e in self.books: reads = self.books[e] if reads > most_read_count: most_read_count = reads most_read_book = e return "%s is the most read book being read by %i users" % (most_read_book, most_read_count) def highest_rated_book(self): highest_rated_book = None highest_rating = 0 for e in self.books: rating = e.get_average_rating() if rating > highest_rating: highest_rating = rating highest_rated_book = e return highest_rated_book def most_positive_user(self): most_positive_user = None highest_average_user_rating = 0 for e in self.users.values(): if e.get_average_rating() > highest_average_user_rating: most_positive_user = e highest_average_user_rating = e.get_average_rating() return most_positive_user #*****__MAIN__************************************************************************# Tome_Rater = TomeRater() #Create some books: book1 = Tome_Rater.create_book("Society of Mind", 12345678) novel1 = Tome_Rater.create_novel("Alice In Wonderland", "Lewis Carroll", 12345) novel1.set_isbn(9781536831139) nonfiction1 = Tome_Rater.create_non_fiction("Automate the Boring Stuff", "Python", "beginner", 1929452) nonfiction2 = Tome_Rater.create_non_fiction("Computing Machinery and Intelligence", "AI", "advanced", 11111938) novel2 = Tome_Rater.create_novel("The Diamond Age", "Neal Stephenson", 10101010) novel3 = Tome_Rater.create_novel("There Will Come Soft Rains", "Ray Bradbury", 10001000) #Create users: Tome_Rater.add_user("Alan Turing", "[email protected]") Tome_Rater.add_user("David Marr", "[email protected]") #Add a user with three books already read: Tome_Rater.add_user("Marvin Minsky", "[email protected]", user_books=[book1, novel1, nonfiction1]) #Add books to a user one by one, with ratings: Tome_Rater.add_book_to_user(book1, "[email protected]", 1) Tome_Rater.add_book_to_user(novel1, "[email protected]", 3) Tome_Rater.add_book_to_user(nonfiction1, "[email protected]", 3) Tome_Rater.add_book_to_user(nonfiction2, "[email protected]", 4) Tome_Rater.add_book_to_user(novel3, "[email protected]", 1) Tome_Rater.add_book_to_user(novel2, "[email protected]", 2) Tome_Rater.add_book_to_user(novel3, "[email protected]", 2) Tome_Rater.add_book_to_user(novel3, "[email protected]", 4) #Uncomment these to test your functions: Tome_Rater.print_catalog() Tome_Rater.print_users() print("Most positive user:") print(Tome_Rater.most_positive_user()) print("Highest rated book:") print(Tome_Rater.highest_rated_book()) print("Most read book:") print(Tome_Rater.most_read_book()) print(Tome_Rater) Tome_Rater_2 = TomeRater() print(Tome_Rater == Tome_Rater_2) Tome_Rater_3 = TomeRater() Tome_Rater_3 = Tome_Rater print(Tome_Rater == Tome_Rater_3)
arr = [int(x) for x in input().split()] req = int(input()) n = len(arr) def LinearSearch(): for i in range(n): if(req == arr[i]): return i+1 return 0 b = LinearSearch() if(b!=0): print(b) else: print("The element is not found")
class Parser: """ Parser the file """ def __init__(self, inputF): """ init Parser :param inputF: file of input """ self.lines = inputF.readlines() self.lines = [' '.join(l.split()) if l.find("//") == -1 else ' '.join(l[:l.find("//")].split()) for l in self.lines] ## remove space and remarks self.cur_line = -1 self.ArithmeticCommand = {'add', 'sub', 'neg', 'eq', 'gt', 'lt', 'and', 'or', 'not'} def hasMoreCommands(self): """ has more commands :return: true if there are """ return self.cur_line < len(self.lines) - 1 def advance(self): """ advance for next line in file :return: nothing """ self.cur_line = self.cur_line + 1 def commandType(self): """ Returns the type of the current command. C_ARITHMETIC is returned for all the arithmetic VM commands. """ cur_command = self.lines[self.cur_line] cur_command = cur_command.split(" ")[0] for arithCom in self.ArithmeticCommand: if arithCom in cur_command: return "C_ARITHMETIC" if 'pop' in cur_command: return "C_POP" elif 'push' in cur_command: return "C_PUSH" elif 'if-goto' in cur_command: return "C_IF" elif 'function' in cur_command: return "C_FUNCTION" elif 'call' in cur_command: return "C_CALL" elif 'label' in cur_command: return "C_LABEL" elif 'goto' in cur_command: return "C_GOTO" elif 'return' in cur_command: return "C_RETURN" def arg1(self): """ Returns the first arg. of the current command. In the case of C_ARITHMETIC, the command itself (add, sub, etc.) is returned. Should not be called if the current command is C_RETURN :return: string """ cur_command = self.lines[self.cur_line].split(" ") if len(cur_command) > 1: return cur_command[1] return cur_command[0] def arg2(self): """Returns the second argument of the current command. Should be called only if the current command is C_PUSH, C_POP, C_FUNCTION, or C_CALL. :return: string """ cur_command = self.lines[self.cur_line].split(" ") return cur_command[2] def getLine(self): """ get line in file :return: line """ return self.cur_line def restart(self): """ start from the first line :return: """ self.cur_line = -1 class CompilationEngine: """ Parser the file """ def __init__(self, inputStreamFile, outputStreamFile): """ init Parser :param inputF: file of input """ self.ofile = outputStreamFile self.fileTokenizer = JackTokenizer(inputStreamFile) self.ofile.write("<class>\n") self.CompileClass() self.ofile.write("</class>\n") def writeInFile(self,type,whatToWrite): self.ofile.write("<"+type.lower()+">"+whatToWrite+"</"+type.lower()+">\n") def writeType(self): if self.fileTokenizer.tokenType() == 'KEYWORD' or self.fileTokenizer.tokenType() == 'IDENTIFIER': if self.fileTokenizer.tokenType() == 'KEYWORD' and ( self.fileTokenizer.keyword() == 'INT' or self.fileTokenizer.keyword() == 'BOOLEAN' or self.fileTokenizer.keyword() == 'CHAR'): self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.keyword()) else: # TODO: do we need to check if the string is something???? self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.identifier()) self.fileTokenizer.advance() return 1 return 0 def CompileClass(self): self.fileTokenizer.advance() if self.fileTokenizer.tokenType() == 'KEYWORD': if self.fileTokenizer.keyword() == 'CLASS': self.writeInFile(self.fileTokenizer.tokenType(),"class") self.fileTokenizer.advance() if self.fileTokenizer.tokenType() == 'IDENTIFIER': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.identifier()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType()== 'SYMBOL': if self.fileTokenizer.symbol() == '{': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.CompileClassVarDec() self.CompileSubRoutine() if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == '}': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) def CompileClassVarDec(self): if self.fileTokenizer.hasMoreTokens(): self.fileTokenizer.advance() if self.fileTokenizer.tokenType()=='KEYWORD': if self.fileTokenizer.keyword() == 'STATIC' or self.fileTokenizer.keyword() == 'FIELD': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.keyword().lower()) self.fileTokenizer.advance() # if self.fileTokenizer.tokenType()=='KEYWORD' or self.fileTokenizer.tokenType()=='IDENTIFIER': # if self.fileTokenizer.tokenType()=='KEYWORD' and (self.fileTokenizer.keyword() == 'INT' or self.fileTokenizer.keyword() == 'BOOLEAN' or self.fileTokenizer.keyword() == 'CHAR'): # self.writeInFile(self.fileTokenizer.tokenType(),self.fileTokenizer.keyword()) # else: # # TODO: do we need to check if the string is something???? # self.writeInFile(self.fileTokenizer.tokenType(),self.fileTokenizer.identifier()) if self.writeType(): self.fileTokenizer.advance() while True: if self.fileTokenizer.tokenType()=='IDENTIFIER': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.identifier()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType()=='SYMBOL': if self.fileTokenizer.symbol()==",": self.writeInFile(self.fileTokenizer.tokenType(),self.fileTokenizer.symbol()) elif self.fileTokenizer.symbol() == ";": self.writeInFile("symbol",";") break self.CompileClassVarDec() def CompileSubRoutine(self): if self.fileTokenizer.tokenType()=="KEYWORD": if self.fileTokenizer.keyword()=="CONSTRUCTOR" or self.fileTokenizer.keyword()=="FUNCTION" or self.fileTokenizer.keyword()=="METHOD": self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.keyword()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType()=="KEYWORD": if self.fileTokenizer.keyword()=="VOID" or self.writeType(): if self.fileTokenizer.keyword() == "VOID": self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.keyword()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType() == 'IDENTIFIER': # todo : should i check it????? self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.identifier()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == '{': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.CompileParameterList() if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == '}': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.fileTokenizer.advance() self.CompileSubroutineBody() def CompileParameterList(self): if self.writeType(): if self.fileTokenizer.tokenType()=="IDENTIFIER": self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.identifier()) self.fileTokenizer.advance() if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == ",": self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.fileTokenizer.advance() self.CompileParameterList() def CompileSubroutineBody(self): if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == '{': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.fileTokenizer.advance() self.CompileVarDec() self.CompileStatements() if self.fileTokenizer.tokenType() == 'SYMBOL': if self.fileTokenizer.symbol() == '}': self.writeInFile(self.fileTokenizer.tokenType(), self.fileTokenizer.symbol()) self.fileTokenizer.advance() def CompileVarDec(self): def CompileStatements(self): fd
class Student(object): role = "Stu" def __init__(self,name): self.name = name @staticmethod def fly(self): print(self.name,"is flying...") @staticmethod def walk(self): print("student walking...") s = Student("Jack") s.fly(s) # s.fly(s) s.walk()
class RelationShip: """保存couple之间的对象关系""" def __init__(self): self.couple = [] def make_couple(self,obj1,obj2): self.couple = [obj1,obj2] # 两个人就成了对象 print("[%s] 和 [%s] 确定了男女关系..." % (obj1.name,obj2.name)) def get_my_parter(self,obj): # p1 p2 #print("找[%s]的对象" % obj.name,) for i in self.couple: if i != obj: # 代表这个是obj的对象。。。 return i else: print("你自己心里没有点数么,你没有对象。。。") def break_up(self): print("[%s] 和 [%s] 正式分手了....江湖再见...改日再约..." % (self.couple[0].name,self.couple[1].name) ) self.couple.clear() # 分手 class Person: def __init__(self,name,age,sex,relation): self.name = name self.age = age self.sex = sex self.relation = relation # 在每个人的实例存储 关系对象 #self.parter = None # 应该是一个对象 ,代表 另一半 def do_private_stuff(self): pass relation_obj = RelationShip() p1 = Person("Mjj",24,"M",relation_obj) p2 = Person("Lyy",22,"F",relation_obj) relation_obj.make_couple(p1,p2) # 让2人成为对象 print(p1.relation.couple) print(p1.relation.get_my_parter(p1).name) # 拿到mjj的对象 p1.relation.break_up() p2.relation.get_my_parter(p2) # # 双向绑定,关联 # p1.parter = p2 # 这样就把Lyy当做了Mjj的另一半 # p2.parter = p1 # # print(p1.parter.name,p2.parter.name ) # # p2.parter = None # #p1.parter = None # # # print(p1.parter,p2.parter )
# Berikut contoh program Turunan (Inheritance) 1 : class Ayah: def methodAyah(self): print('Ini adalah Method Ayah') class Anak(Ayah): def methodAnak(self): print('Ini adalah Method Anak') # Deklarasi objek kelas Ayah p = Ayah() p.methodAyah() # Deklarasi objek kelas Aanak c = Anak() c.methodAnak() c.methodAyah()
# Program selisih jam # judul # mencari durasi dari 2 waktu # kamus # jamawaljam = int # jamakhirjam = int # jamawalmenit = int # jamakhirmenit = int # jamawaldetik = int # jamakhirdetik = int # deskripsi print(">>>>>>>>>>>>>>>>>>SELAMAT DATANG<<<<<<<<<<<<<<<<<<<<") print("Masukan dalam format 24jam") print("--------------------------") jamawaljam = int(input("masukan jam awal: ")) jamawalmenit = int(input("masukan menit awal: ")) jamawaldetik = int(input("masukan detik awal: ")) print("\t\t\t\t\t ") jamakhirjam = int(input("masukan jam akhir: ")) jamakhirmenit = int(input("masukan menit akhir: ")) jamakhirdetik = int(input("masukan detik akhir: ")) detikawal = jamawaljam * 3600 + jamawalmenit * 60 + jamawaldetik detikakhir = jamakhirjam * 3600 + jamakhirmenit * 60 + jamakhirdetik if(detikawal < detikakhir): durasi = detikakhir - detikawal else: durasi = (detikakhir+24*3600)-detikawal # konversi jamdurasijam = durasi/3600 jamdurasimenit = (durasi % 3600)/60 jamdurasidetik = durasi % 60 # konversi (am 00.00-11.59 pm 12.00-23.59) print("durasinya %d jam %d menit %d detik" % (jamdurasijam, jamdurasimenit, jamdurasidetik))
# Pencarian dengan Binary Search (Pencarian Biner) def binary_search(angka, listku): listku.sort() # Penyortiran List langkah = 0 ketemu = False awal = 0 akhir = len(listku)-1 while awal <= akhir and not ketemu: tengah = (awal+akhir)//2 if listku[tengah] == angka: ketemu = True elif angka > tengah: awal = tengah+1 else: akhir = tengah-1 langkah += 1 if ketemu: print('Angka ditemukan!') print('posisi angka yang ditemukan adalah %s' % str(awal+1)) else: print('Angka yang anda masukkan tidak ditemukan!') print('Langkah yang sudah di ambil dalam menemukan adalah %s langkah' % langkah) binary_search(3, [1, 1, 2, 6, 7, 8, 9, 3, 4])
from numpy import * # 抽样工具 class Sampling: # 无放回随机抽样 def randomSampling(dataMat, number): dataMat = array(dataMat) try: #slice = random.sample(dataMat, number) sample = [] for i in range(number): index = random.randint(0, len(dataMat)) #包含low,但不包含high sample.append(dataMat[index]) dataMat = delete(dataMat, index, 0) return dataMat, sample except e: print(e) # 有放回随机抽样 def repetitionRandomSampling(dataMat, number): sample = [] for i in range(number): sample.append(dataMat[random.randint(0, len(dataMat))]) return dataMat, sample # 系统随机抽样 def SystematicSampling(dataMat, number): length = len(dataMat) k = length / number sample = [] i = 0 if k > 0: while len(sample) != number: sample.append(dataMat[0 + i * k]) i += 1 return sample else: return dataMat, Sampling.randomSampling(dataMat, number) if __name__ == '__main__': randomData = random.random((4, 2)) print(randomData) dataMat, sample = randomSampling(randomData, 2) print("dataMat=" , dataMat) print("sample=" , sample)
# # a,b = 25,"Neal" # # Déclarer une variable et lui attribuer un nombre. Afficher le résultat de la multiplication de cette variable par 4 # # Déclarer une variable et lui attribuer un nombre. trouver ensuite 2 syntaxes différentes pour ajouter "1" à ce nombre. Afficher ce nombre à chaque fois que vous ajoutez "1". # # print("je m'appelle",b, "et j'ai",a,"ans") # # a=12 # # print(a*4) # #d=23 # #d=d+1 # #print(d) # #Même exercice qu'avant, mais cette fois en soustrayant "1" On peut utiliser variable= variable+1 ou utiliser variable = +=+1 # #e=32 # #e=e-1 # #print(e) # #Même exercice qu'avant, mais en multipliant par 2 # #f=25 # #f=f*2 # #print(f) # #Même exercice qu'avant mais en divisant par 2 # #g=50 # #g=g/2 # # print(g) # # Déclarer 2 variables "a" et "b", leur affecter des valeurs. Puis permuter ces variables. # # a,b = 1,2 # # a,b = b,a # # print(a) # #Déclarer 2 variables prenant la meme valeur de 3 manières différentes au moins. # # a,b = 1,1 # # a=1 # # b=1 # # a=b=1 # # b=a=1 # #Déclarer 1 variable "a" et lui affecter la valeur "10". Réaliser la suite dans l'ordre : # #Afficher a # #Afficher le résultat de la division de a par 2 # #Afficher le résultat entier de la division de a par 2 # #Afficher le reste de la division de a par 2 # #Afficher a puissance 3 # # a=10 # # print(a) # # print(a/2) # # print(a//2) # # print(a%2) # # print(a**3) # # Ecrire un programme qui lit le prix HT d’un article, le nombre d’articles et qui définit une variable contenant le taux de TVA à 20%, # # et qui fournit le prix total TTC correspondant. Se servir de la fonction "input()" pour demander a l'utilisateur de renseigner les informations. # # prix = int(input("quel est le prix ?")) # # nb = int(input("combien d'articles avez-vous ?")) # # tva = (prix+nb)*0.2 # # total = prix*nb+tva # # print("le prix de votre article est de",prix,"€","vous en avez:", nb,"ce qui vous fait",total,"€","dont", tva,"€ de TVA") # # Ecrire une liste comportant les nombres "4" et "5" et l'afficher. # # liste = [4,5] # # print(liste) # # Ecrire une liste avec 2 chaines de caractère et 2 nombres. # # Afficher la liste # # Afficher le premier élément de la liste # # Afficher le type du 3eme élément de la liste # # a = ["salut","bonjour",1,2] # # print(a) # # print( a[0] ) # # type(a[1]) # # print( type(a[2]) ) # # Créer 2 listes "x" et "y", avec 2 nombres dans chacune d'elle. Créer une troisième liste qui sera la concaténation de x et y. Afficher cette troisième liste # # x= [1,2] # # y= [3,4] # # z=x+y # # print(z) # # Soit la liste suivante : x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # #Afficher la valeur du 4ème élément # #Afficher les nombres entre l'indice 3 inclut et 5 exclut # #Afficher les nombres entre l'indice 2 inclut et l'indice 8 exclut, par saut de 2 # #Afficher la longueur de la liste x # #Affiher la valeur minimum de x # #Afficher la valeur maximum de x # #Afficher la somme des valeurs contenues dans la liste x # #Supprimer les nombres entre l'indice 3 inclut et 5 exclut, afficher la liste x # # x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # # print(x[3]) # # print(x[3:5]) # # print(x[2:8:2]) # # len(x) # # print(len (x)) # # min(x) # # print(min (x)) # # max(x) # # print(max (x)) # # sum(x) # # print(sum(x)) # # del(x[3:5]) # # print(x) # # Soit la liste suivante : x = ["ok", 4, 2, 78, "bonjour"] # #Afficher le quatrième élément de la liste # #Affecter la valeur "toto" au 2ème élément de la liste, afficher la liste # # x= ["ok",4,2,78,"bonjour"] # # print(x[3]) # # x[1]="toto" # # print(x) # #Créer un dictionnaire "x" avec les clés / valeurs suivantes : # #"key" -> "valeur" "key2" -> "valeur2" # #afficher x afficher la valeur de la clé "key" ajouter la valeur "toto" correspondante à la clé "titi" remplacer la valeur de la clé "titi" par "tata". # #afficher x. supprimer la clé "titi" et sa valeure correspondante supprimer la valeur "key" et afficher la valeure correspondante qui à été supprimée # #afficher "x" créez un dictionnaire "y", lui affecter le dictionnaire "x" et afficher "y" # # x={"key":"valeur","key2":"valeur2"} # # print(x) # # print(x["key"]) # # x["titi"]="toto" # # x["titi"]="tata" # # print(x) # # del(x["titi"]) # # print(x) # # y=x # # print(y) # #Ecrire un programme qui demande deux nombres à l’utilisateur et l’informe ensuite si leur produit est nul, négatif ou positif. # #Variable n en Entier # #Début # #Ecrire "Entrez un nombre : " # #Lire n # #Si n > 0 Alors # #Ecrire "Ce nombre est positif” # #Sinon # #Ecrire "Ce nombre est négatif" # #Finsi # # a,b = 4,10 # # if a*b > 0: # # print("positif") # # elif a*b < 0: # # print("négatif") # # elif a*b == 0: # # print("nul") # #Ecrire un programme qui demande l'age de l'utilisateur, et qui lui dit s'il est majeur ou non # # a = 20 # # if a >=18: # # print ("Vous êtes majeur") # # elif a <18 : # # print ("Vous êtes mineur") # # #Demandez un nombre à un utilisateur, créer une condition qui affichera si le nombre de l'utilisateur est comprit entre 5 et 10. 5 et 10 sont exclut # #(les nombres doivent donc etre 6, 7, 8 ou 9 pour que le programme afficher "vrai") # # a = 12 # # if a > 5 and a < 10: # # print("vrai") # # else : # # print("faux") # # créez une boucle for qui affiche les numéros de 0 à 5 # # a = 0 # # for loop in range(5): # # print(a) # # a = a + 1 # # créez une liste de 3 mots. Parcourez la liste a l'aide d'une boucle "for" et pour chaque mot afficher le nombre de caractère du mot et le mot en question # # a = ["Bonjour", "Merci", "Aurevoir"] # # for element in a: # # print(element) # # print(len(element)) # # Soit la variable a = "anticonstitutionnellement". A l'aide d'une boucle for, afficher les lettres présentes dans x. # # a = ["anticonstitutionnellement"] # # for element in a: # # print(a) # # print(len(element)) # # En utilisant la fonction range(), afficher tous les nombres de 0 à 5 en ordre décroissant # # a = [0, 1, 2, 3, 4, 5] # # for i in range(5,0,-1): # # print(i) # # print(0) # # Grâce à la fonction range(1, 10), afficher tous les nombres de 1 à 3. La boucle doit s'arrêter une fois que le chiffre 3 est affiché # # a = [1,2,3,4,5,6,7,8,9,10] # # for i in range(1,3+1): # # print (i) # # Refaire le même exercice que le précédent, mais cette fois variabiliser tous les nombres. # # a = [1,2,3,4,5,6,7,8,9] # # Grâce à la fonction range(1, 10), afficher tous les nombres de 1 à 9. # # La boucle ne doit pas afficher le nombre "3" mais doit obligatoirement continuer jusqu'au bout. Le faire de 2 manières différentes. # # a = [1,2,3,4,5,6,7,8,9,10] # # for element in a: # # print(element) # # créez une boucle for qui affiche les numéros de 0 à 5 # # a = [0,1,2,3,4,5] # # for i in range (6) : # # print (i) # # créez une liste de 3 mots. Parcourez la liste a l'aide d'une boucle "for" et pour chaque mot afficher le nombre de caractère du mot et le mot en question # # a = ["bonjour" , "merci" , "stp"] # # for element in a: # # print(element) # # print(len(element)) # # Soit la variable x = "anticonstitutionnellement". A l'aide d'une boucle for, afficher les lettres présentes dans x. # # x = ["anticonstitutionnellement"] # # for element in x: # # print(x) # # print(len(element)) # # Soit la liste suivante : x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. parcourez l'ensemble pour afficher tous les nombres # # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # # for nombre in x: # # for liste in nombre: # # print(liste) # # Soit la liste suivante : x = [1,10,20,30,40,50]. Définissez a et b, 2 variables prenant chacune la somme des nombres de la liste x. # # Les 2 sommes doivent être calculées différemment. Afficher a et b # # x = [1,10,20,30,40,50] # # cpt = 0 # # for element in x: # # print(element) # # cpt = cpt + element # # print(cpt) # #En utilisant la fonction range(), afficher tous les nombres de 0 à 5 en ordre décroissant. # # a = [0,1,2,3,4,5] # # for i in range(5,0,-1): # # print(i) # # print(0) # # Grâce à la fonction range(1, 10), afficher tous les nombres de 1 à 3. La boucle doit s'arrêter une fois que le chiffre 3 est affiché. # # a = [1,2,3,4,5,6,7,8,9,10] # # for i in a : # # if i in range (0,4) : # # print(i) # #définir une variable et lui attribuer un nombre. Afficher cette variable # # a = 1 # # print(a) # # définir 2 variables : 1 contenant un age en nombre et l'autre contenant votre prénom. # # Créez une troisième variable qui devra contenir la phrase suivante : "Je suis [NOM] et j'ai [AGE] ans." Enfin, afficher cette dernière variable # # a = 25 # # b = "Dylan" # # c = "je m'appelle",b, "et j'ai",a,"ans" # # print("je m'appelle",b, "et j'ai",a,"ans") # #Refaire l'exercice précédent, mais cette fois déclarer les 2 premières variables sur une seule ligne # #a,b = 25,"Dylan" # #c = "je m'appelle",b, "et j'ai" ,a, "ans" # #print("je m'appelle",b, "et j'ai" ,a, "ans") # # Déclarer une variable et lui attribuer un nombre. Afficher le résultat de la multiplication de cette variable par 4. # #a = 4 # #a = a*4 # #print(a) # #Déclarer une variable et lui attribuer un nombre. trouver ensuite 2 syntaxes différentes pour ajouter "1" à ce nombre. Afficher ce nombre à chaque fois que vous ajoutez "1". # #a = 1 # #a = a+1 # #print(a) # #Même exercice qu'avant, mais cette fois en soustrayant "1" # #a = 6 # #a = a-1 # #print(a) # #Même exercice qu'avant, mais en multipliant par 2 # #a = 5 # #a = a*5 # #print(a) # #a = 10 # #a = a/2 # #print(a) # #Déclarer 2 variables "a" et "b", leur affecter des valeurs. Puis permuter ces variables. # #a,b = 1,2 # #a,b= b,a # #print(a) # #Déclarer 2 variables prenant la meme valeur de 3 manières différentes au moins. # #a,b = 1,1 # #a = 1 # #b = 1 # #a = b = 1 # #b = a = 1 # #Déclarer 1 variable "a" et lui affecter la valeur "10". Réaliser la suite dans l'ordre : #Afficher "a" #Afficher le résultat de la division de a par 2 #Afficher le résultat entier de la division de a par 2 #Afficher le reste de la division de a par 2 #Afficher a puissance 3 # a = 10 # a = a/2 # print(a) # a = a%2 # print(a) #L'ensemble des exercices qui vont suivre sont destinés à parcourir une grande diversités de concepts sur les classes. #Ces exercices sont à faire dans l'ordre, et pour chaque exercice, vous repartirez du code réalisé dans l'exercice précédant. #1 - Créez une classe "Carre", prennant en paramètre un élément "côté", représentant la longueur d'un côté en cm. #2 - A la fin de votre fichier, ajouter une condition permettant d'exécuter le code qui sera dans la condition si le fichier de la classe est appelé directement. # Afficher "carré" lors de l'exécution du script. #A noté que pour la suite des exercices, vous serez ammené à modifier cette partie afin de tester les fonctionnalités que vous aurez développé. #De même pour la simplification des énnoncés à venir, nous appellerons cette partie du code, la partie "test". #3 - Créez une méthode "perimeter" qui va retourner la valeur du périmètre. Ajouter un attibut "perimeter" qui sera défini lors de l'instanciation de la classe "carre". #Dans la partie "test", créer une instance de "carre" et afficher le périmètre calculé #4 - Créez une méthode "area" qui va retourner l'aire du carré. Ajouter un attribut "area" qui sera défini lors de l'instanciation de la classe "carre". # Dans la partie "test", créer une instance de carre et afficher l'aide calculé #5 - Surchargez la méthode de représentation de la classe "Carre" pour afficher la phrase suivante # : "Le carré à un côté d'une longueur de Xcm, une aire de Xcm2 et un périmètre de Xcm." grâce à la fonction "print()". # Utilisez la fonction "print()" sur votre objet dans la partie "test". #6 - Créez une fonctino "factor", qui va permettre de retourner un carré "x" fois + grand que celui en cours. #Testez la fonctionalité #7 - Créez une fonction permettant d'aditionner 2 carré, de telle manière que la syntaxe suivante "Carre(2) + Carre(3)" donne une résultat de "Carre(5)" #Testez la fonctionnalité #8 - Refaire la même chose que pour l'exercice n°7, mais avec une soustraction #9 - Créer une fonction qui permet de retourner un entier lors de l'utilisation de la fonction "int(Carre(2))", de telle sorte que la longueur du côté soit retournée (dans notre cas "2") #10 - Surchargez la méthode permettant de réaliser l'opération suivante : "Carre(2) < Carre(3)", et qui retourne True ou False en se basant sur la longueur des côtés de chaque carré. # Testez l'opérateur #11 - Recommencer pour tous les opérateurs suivants : #">" #"<=" #">=" #"==" #"!=" Pour chacune de ces fonctions, testez les opérateurs #12 - Créer un attribut de classe "count" qui sera incrémenté à chaque instanciation de la classe "Carre". Dans la partie test, créer un objet "a" de la classe "Carre", afficher "count". # Créer un deuxième objet "b" de la classe "Carre". Afficher "count" de l'objet "a". # class Carre: # count = 0 # def __init__(self, nb_cote, taille_cote): # self.nb_cote = nb_cote # self.taille_cote = taille_cote # def calculate_perimeter(self): # return self.nb_cote * self.taille_cote # def calculate_area(self): # return self.taille_cote * self.taille_cote # def factor(self): # return (self.nb_cote * self.taille_cote) * multi # def count(self): # return type(self)ct = count # count += 1 # """ # def int(self): # return (self.nb_cote) # def Comp(self): # if self.taille_cote > C2.taille_cote2: # print("True") # else: # print("False") # """ # if __name__ == "__main__": # a = int(input("Entrer Nombre de coter : ")) # b = int(input("Entrer Tailler des coter : ")) # d = int(input("Entrer Tailler des coter : ")) # C = Carre(a, b) # C2 = Carre(a, d) # multi = int(input("Entrer : ")) # # multi2 = int(input("Entrer : ")) # print(C.nb_cote) # print(C.taille_cote) # print(C.calculate_perimeter()) # print(C.calculate_area()) # print(C2.nb_cote) # print(C2.taille_cote) # print(C2.calculate_perimeter()) # print(C2.calculate_area()) # print(C.count()) # print("Le carré n°1 est", multi, "fois plus grand, soit", C.factor(), "cm") # print("Les cotés du carré ont une longueur de", C.taille_cote,"cm, une aire de", C.calculate_area(),"cm², et un périmètre de", C.calculate_perimeter(),"cm.") # """ # class Carre2: # def __init__(self, nb_cote2, taille_cote2): # self.nb_cote2 = nb_cote2 # self.taille_cote2 = taille_cote2 # def calculate_perimeter2(self): # return self.nb_cote2 * self.taille_cote2 # def calculate_area2(self): # return self.taille_cote2 * self.taille_cote2 # def factor2(self): # return (self.nb_cote2 * self.taille_cote2) * multi2 # print(C2.nb_cote2) # print(C2.taille_cote2) # print(C2.calculate_perimeter2()) # print(C2.calculate_area2()) # print(C.int()) # print(C.Comp()) # print("Le carré n°2 est", multi2, "fois plus grand, soit", C2.factor2(), "cm") # print("Les cotés du carré ont une longueur de", C2.taille_cote2,"cm, une aire de", C2.calculate_area2(),"cm², et un périmètre de", C2.calculate_perimeter2(),"cm.") # print("Les deux carré additionnés ont un périmètre de", C.calculate_perimeter() + C2.calculate_perimeter2(),"cm") # print("Les deux carré soustrait ont un périmètre de", C.calculate_perimeter() - C2.calculate_perimeter2(),"cm") # """ # 15 - Créer 2 listes "x" et "y", avec 2 nombres dans chacune d'elle. Créer une troisième liste qui sera la concaténation de x et y. Afficher cette troisième liste # x = [1,2] # y = [3,4] # z = x + y # print (z) # 16 - Soit la liste suivante : x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Afficher la valeur du 4ème élément # Afficher les nombres entre l'indice 3 inclut et 5 exclut # Afficher les nombres entre l'indice 2 inclut et l'indice 8 exclut, par saut de 2 # Afficher la longueur de la liste x # Affiher la valeur minimum de x # Afficher la valeur maximum de x # Afficher la somme des valeurs contenues dans la liste x # Supprimer les nombres entre l'indice 3 inclut et 5 exclut, afficher la liste x # x = [0,1,2,3,4,5,6,7,8,9] #print (x[3]) #print (x[3:5]) #print (x[2:8:2]) # print (len(x)) # print (min(x)) # print (max(x)) # print (sum(x)) # del(x[3:5]) # print (x) # x = ["ok", 4, 2, 78, "bonjour"] # Afficher le quatrième élément de la liste # Affecter la valeur "toto" au 2ème élément de la liste, afficher la liste # print (x[3]) # x[1]="toto" # print (x) # Créez une liste des nombres allant de 0 à 5, le faire de 2 manières possible et afficher les résultats # a = [0,1,2,3,4,5] # print (a) # 19 - Créer un dictionnaire "x" avec les clés / valeurs suivantes : # "key" = "valeur" "key2" = "valeur2" # afficher x afficher la valeur de la clé "key" ajouter la valeur "toto" correspondante à la clé "titi" remplacer la valeur de la clé "titi" # par "tata". afficher x. supprimer la clé "titi" et sa valeure correspondante supprimer la valeur "key" et afficher la valeure # correspondante qui à été supprimée afficher "x" créez un dictionnaire "y", lui affecter le dictionnaire "x" et afficher "y" # x ={"key":"valeur","key2":"valeur2"} # print(x["key"]) # x["titi"]="toto" # x["titi"]="tata" # print(x) # del(x["titi"]) # print(x) # y=x # print(y) # 20 - Créez une liste "x" de 4 tuples de forme (x, y) # afficher x # ajouter la string "a" à la fin de la liste, afficher x # ajouter la string "b" à la fin de la liste d'une manière différente, afficher x # créer une liste "y" avec les valeurs "1", "2", "3". Ajouter tous les éléments de la liste y à la liste x. Afficher x # Ajouter "2" à l'index n°4 de la liste x, sans supprimer l'index existant, ni le remplacer. Afficher x # Supprimer la première valeur uniquement de x qui correspond à "2". afficher x # Afficher y # créez une liste "z" et lui affecter les meme valeurs qu'à y, afficher z # supprimer tous les éléments dans y, afficher y # supprimer tous les éléments dans z, d'une manière différente, puis afficher z # x = ["l","y","u","j"] # print(x) # (x).append('a') # print(x) # x.insert(5,'b') # print(x) # y = ["1","2","3"] # (x).append(y) # print(x) # x.insert(3,2) # print(x) # x.pop(3) # print(x) # print(y) # z = ["1","2","3"] # print (z) # print(y) # y.clear() # print(y) # 1 - Ecrire un programme qui demande deux nombres à l’utilisateur et l’informe ensuite si leur produit est nul, négatif ou positif. # nb1=input("1er nombre:") # print(nb1) # nb2=input("2ème nombre:") # print(nb2) # x= int(nb1)+int(nb2) # print(x) # if x<0:print("le produit est négatif") # elif x>0:print("le produit est positif") # else:print("le produit est nul") #Ecrire un programme qui demande l'age de l'utilisateur, et qui lui dit s'il est majeur ou non # age =(input("Saisir age:")) # print(age) # if age >="18": # print ("Vous êtes majeurs") # else: # print ("vous êtes mineurs") #3 - Demandez un nombre à un utilisateur, créer une condition qui affichera si le nombre de l'utilisateur est comprit entre 5 et 10. 5 et 10 sont exclut # (les nombres doivent donc etre 6, 7, 8 ou 9 pour que le programme afficher "vrai") # a = int(input("Donnez un nombre")) # print (a) # if a > 5 and a < 10: # print("vrai") # else: # print("faux")
# -*- coding: utf-8 -*- # @Time : 2021/5/21 13:42 # @Author : lvzhimeng # @FileName: 华为面试题.py # @Software: PyCharm import itertools def test_list(n): if n < 1: return 1 else: vue = test_list(n - 1) char_list = list(str(vue)) count_list = [list(v) for k, v in itertools.groupby(char_list)] result_str = '' for i in count_list: count = len(i) num = i[0] result_str += str(count) + str(num) return int(result_str) print(test_list(10))
#!/usr/bin/env python ################################################################################ #Imports import random import sys #Body def determine_digits(): '''Retrieves the number of digits from an arg given in the command line. If an arg is not given, the number of digits defaults to 3. Function returns the number of digits. ''' try: digits = int(sys.argv[1]) except: digits = 3 #Convert digit to default of 3, if user input is not applicable. if type(digits) is str or digits <=0: digits = 3 return digits def max_guesses(digits): '''Function calculates the maximum number of guesses the user has in the game. The maximum number is a function of the number of digits. ''' maxguesses = (2**digits) + digits return maxguesses def generate_random_number(digits): '''Generates a random positive integer with the number of digits (d) passed to the function. Returns the random positive integer. ''' number = random.randint(0, (10**digits)-1) return number def user_guesses(digits): '''Function promprts user to guess a positive integer, and will prompt the user again if the input they provide is not appropriate (i.e. a string, a negative number, or a number with too many digits). ''' #Set pluralization of 'digits' for prompting user. if digits == 1: digits_plural = '' else: digits_plural = 's' #Prompt user to guess a positive integer. #Prompts user again if input is not an appropriate guess. #Guesses without the correct number of digits, #negative guesses, decimals, and words are all #inappropriate guesses. while True: guess = raw_input('Guess a positive integer with {0} digit{1}.\n>'.format(digits, digits_plural)) if len(guess) != digits or '.' in guess or '-' in guess: print "You can't get lucky if you're not listening." continue else: try: int(guess) except: print "You can't get lucky if you're not listening." continue else: return guess def test_guess(): '''Function calls other functions to generate the number of digits, the random number, and the maximum number of guesses. Function then compares the random number to the guess the user input. If the guess is correct, the user is congratulated and the program terminated. Otherwise, the user is given a hint as to whether their guess was too low/high, and then prompted to guess again. The game terminates if the maximum number of guesses is reached. ''' digits = determine_digits() number = str(generate_random_number(digits)) maxguesses = max_guesses(digits) print 'Welcome to the mimsmind game. You have {0} tries to guess the random number.'.format(maxguesses) guess = user_guesses(digits) guess_str = str(guess) guess_dict = {i:guess_str[i] for i, value in enumerate(guess_str)} #I wanted to user enumerate here but couldn't figure out how. guess_count = 1 while guess != number and guess_count < maxguesses: bulls = 0 cows = 0 number_used_list = [d for d in number] for digit in guess_dict: if guess_dict[digit] == number_used_list[digit]: bulls += 1 number_used_list[digit] = 'used' for digit in guess_dict: if guess_dict[digit] in number_used_list: cows += 1 print "{0} bull(s), {1} cow(s).".format(bulls, cows) guess = user_guesses(digits) guess_str = str(guess) guess_dict = {i:guess_str[i] for i , value in enumerate(guess_str)} #I wanted to user enumerate here but couldn't figure out how. guess_count += 1 if guess == number: print "Congratulations, you're spot on!. You guessed the correct number in {0} tries.".format(guess_count) else: print "Sorry, but you've guessed {0} times. That is too many!".format(guess_count) return ################################################################################ def main(): '''Function generates a positive random integer and prompts the user to guess the correct number. After each guess, the computer will provide feedback to guide the user in making their next guess. The number of digits for the random number may be given as an arg when the function is called from the command line. Otherwise, it defaults to a 1-digit number. ''' test_guess() if __name__ == "__main__": main()
''' * @Author: csy * @Date: 2019-04-28 14:01:32 * @Last Modified by: csy * @Last Modified time: 2019-04-28 14:01:32 ''' requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if 'extra cheese'in requested_toppings: print("Adding extra cheese.") print("\nFinished making your pizza!\n") requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print("Adding "+requested_topping) print("\nFinished making your pizza!\n") requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping == "green peppers": print("Sorry,we are out of green peppers right now.") else: print("Adding "+requested_topping) print("\nFinished making your pizza!\n") requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print("Adding "+requested_topping) else: print("Are you sure you want a plain pizza?\n") available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding"+requested_topping) else: print("Sorry,we are out of "+requested_topping + "right now.") print("\nFinished making your pizza!\n")
def somaRecursivo(number): if len(number) == 1: return int(number) soma = str(sum([int(char) for char in number])) return somaRecursivo(soma) def proxMultiplo10(number): if number%10 == 0: return number number+=1 return proxMultiplo10(number) # Espera receber os campo1, 2 e 3 sem pontos, apenas números. def criaDV(digitos): multiplicadorPar = 2 multiplicadorImpar = 1 count = 0 somador = 0 for digito in digitos[::-1]: if count%2 == 0: resultadoMultiplicacao = str(int(digito)*multiplicadorPar) somador += somaRecursivo(resultadoMultiplicacao) else: resultadoMultiplicacao = str(int(digito)*multiplicadorImpar) somador += somaRecursivo(resultadoMultiplicacao) count +=1 return str(proxMultiplo10(somador) - somador) def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] def gerar_linha_digitavel(codebar): cod_banco = codebar[:3] # Identificação do Banco cod_moeda = codebar[3:4] # Código da Moeda (Real = 9, Outras=0) dig_verif = codebar[4:5] # Dígito verificador do Código de Barras fator_venc = codebar[5:9] # Fator de Vencimento (Vide Nota) valor = codebar[9:19] # Valor campo_livre = codebar[19:44] # Campo Livre # Banco Bradesco agencia_benef = codebar[19:23] # Agência Beneficiária (Sem o digito verificador) carteira = codebar[23:25] # Carteira num_nosso_num = codebar[25:36] # Número do Nosso Número (Sem o digito verificador) conta_benef = codebar[36:43] # Conta do Beneficiário (Sem o digito verificador) zero = codebar[43:44] # Zero campo_1 = cod_banco + cod_moeda + campo_livre[0:5] campo_1 += criaDV(campo_1) campo_2 = campo_livre[5:15] campo_2 += criaDV(campo_2) campo_3 = campo_livre[15:25] campo_3 += criaDV(campo_3) campo_4 = dig_verif campo_5 = fator_venc + valor campo_1 = insert_str(campo_1, '.', 5) campo_2 = insert_str(campo_2, '.', 5) campo_3 = insert_str(campo_3, '.', 5) linha_digitavel = campo_1 + ' ' + campo_2 + ' ' + campo_3 + ' ' + campo_4 + ' ' + campo_5 return linha_digitavel
# Jonas Claes - 02/06/2019 12:19 # Store exam results. examResults = [] # Get all the results. for i in range(0, 5): examResults.append(int(input("Exam %i result? " % (i + 1)))) # Sort exam results from low to high. examResults.sort() # Check if first two elements are below 50. if (examResults[0] < 50 and examResults[1] < 50): print("You failed because you have more than 1 failed test.") input("Press 'ENTER' to exit...") exit(1) # Calculate total. total = 0 for result in examResults: total += result # Calculate average. average = total / 5 # Check if average is less than 50. if (average < 50): print("You failed because your average was %i" % int(average)) input("Press 'ENTER' to exit...") exit(1) print("You passed.") input("Press 'ENTER' to exit...")
#!/usr/bin/env python3 """Script for Tkinter GUI chat client.""" #followed tkinter module from socket import AF_INET, socket, SOCK_STREAM #initiate socket from threading import Thread #Threading import tkinter def receive(): """Looks at received messages.""" while True: try: message = client_socket.recv(B).decode("utf8") #we chose utf8 because it's better for words message_list.insert(tkinter.END, message) except OSError: # No connections. saw this on online example break def send(event=None): """Sends messages.""" messages = s_message.get() s_message.set("") # Lets user enter client_socket.send(bytes(messages, "utf8")) if messages == "{quit}": #lets them leave and closes the GUI client_socket.close() top.quit() def bye(event=None): """This is the exit message.""" s_message.set("{quit}") send() top = tkinter.Tk() #from tkinter module top.title("Conversation") #title for chatroom messages_frame = tkinter.Frame(top) s_message = tkinter.StringVar() # For the messages to be sent. s_message.set("Enter text.") scrollbar = tkinter.Scrollbar(messages_frame) # To look at old things. message_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set) #message view layout, used similar from the tkinter example and picked random heiht and width scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) message_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH) message_list.pack() messages_frame.pack() entry_field = tkinter.Entry(top, textvariable=s_message) entry_field.bind("<Return>", send) entry_field.pack() send_button = tkinter.Button(top, text="Send", command=send) send_button.pack() top.protocol("WM_DELETE_WINDOW", bye) #Socket set up HOST = input('Enter host: ') #enter 127.0.0.1 if server is running on home address PORT = input('Enter port: ') if not PORT: PORT = 33000 #automatically links to this if no entry else: PORT = int(PORT) B = 1024 #buffer size A = (HOST, PORT) client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(A) #set up GUI receive_thread = Thread(target=receive) receive_thread.start() tkinter.mainloop() # Starts GUI execution.
"""Gradient descent implementation.""" import numpy from sklearn.utils import shuffle def l2_regularization_gradient(l2, w): g = w.copy() g[0] = 0. # don't penalize intercept return 2 * g * l2 def adjust(x): """Prepends row filled with 1s to the vector, so that constant of a polynomial is evaluated easily. """ return numpy.insert(x, 0, 1, axis=1) def gradient_descent(loss_gradient, x, y, batch_size, n_epochs, shuffle_: bool, l2, learning_rate, decay): """Vectors in X are expected to have 1 as the first element.""" start = numpy.zeros((x.shape[1],)) w = start for num in range(n_epochs): if shuffle_: x, y = shuffle(x, y) batch_iterator = ( (x[start:start + batch_size], y[start:start + batch_size]) for start in range(0, x.shape[0], batch_size) ) for bx, by in batch_iterator: grad = loss_gradient(w, bx, by) + l2_regularization_gradient(l2, w) w += -learning_rate * grad learning_rate *= decay return w
import numpy as np from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier class Perceptron: def __init__(self, model=None): self.model = model def fit(self, X, y): """ this method learns the parameters of the model and stores the trained model (namely, the variables that define hypothesis chosen) in self.model. :param X: a training set :param y: labels :return: """ m, d = X.shape w = np.zeros((d + 1, 1)) homogeneus_X = np.ones((m, d + 1)) homogeneus_X[:m, :d] = X i = 0 # while loop which stops when the classifier fits correctly all the training set. while (True): w = w + y[i] * homogeneus_X[i][:, np.newaxis] cond = ((y[:, np.newaxis] * np.dot(homogeneus_X, w)) <= 0).T[0] cond_where = np.argwhere(cond) is_cond = len(cond_where) if is_cond > 0: i = cond_where[0][0] else: self.model = w break def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ m, d = X.shape homogeneus_X = np.ones((m, d + 1)) homogeneus_X[:m, :d] = X return np.sign(np.dot(homogeneus_X, self.model)).reshape(X.shape[0], ) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict class LDA: def __init__(self, model=None): self.model = model def fit(self, X, Y): num_of_samples = X.shape[0] num_of_samples_minus_1 = np.count_nonzero(Y == -1) num_of_samples_1 = num_of_samples - num_of_samples_minus_1 pi_minus_1 = num_of_samples_minus_1 / num_of_samples pi_1 = num_of_samples_1 / num_of_samples mu_minus_1 = self.estimated_mu(Y, -1, X, num_of_samples_minus_1) mu_1 = self.estimated_mu(Y, 1, X, num_of_samples_1) cov = self.estimated_cov(X, Y, mu_minus_1, mu_1) inversed_cov = np.linalg.inv(cov) # The functions delta+1,delta-1 are called discriminant functions: this classification rule predicts # the label, based on which of the two discriminant functions is larger at the sample x we # wish to classify. self.model = np.concatenate( (np.dot(inversed_cov ,mu_1) - np.dot(inversed_cov , mu_minus_1), - 0.5 * (np.dot(np.dot(mu_1.T, inversed_cov) , mu_1) - np.dot(np.dot(mu_minus_1.T , inversed_cov) , mu_minus_1)) + np.log(pi_1) - np.log(pi_minus_1))) def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ m, d = X.shape homogeneus_X = np.ones((m, d + 1)) homogeneus_X[:m, :d] = X return np.sign(np.dot(homogeneus_X, self.model)).reshape(X.shape[0], ) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict def estimated_cov(self, X, Y, mu_minus_1, mu_1): m, n = X.shape cov = np.zeros((n, n)) for (mu, y) in [(mu_minus_1, 0), (mu_1, 1)]: X_y = np.array(X[Y == y].T) center_X = X_y - np.array(mu) cov += np.dot(center_X ,center_X.T) return cov / (m - 2) def estimated_mu(self, Y, y, X, N_y): mu = np.sum(X[Y == y], axis=0)[:, np.newaxis] return mu / N_y class SVM: def __init__(self, model=None): self.svm = SVC(C=1e10, kernel='linear') self.model = model def fit(self, X, y): """ this method learns the parameters of the model and stores the trained model (namely, the variables that define hypothesis chosen) in self.model. :param X: a training set :param y: labels :return: """ self.model = self.svm.fit(X, y) def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ # return self.model.predict(X) return self.svm.predict(X) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict class SOFT_SVM: def __init__(self, model=None): self.soft_svm = SVC(C=1, kernel='linear') self.model = model def fit(self, X, y): """ this method learns the parameters of the model and stores the trained model (namely, the variables that define hypothesis chosen) in self.model. :param X: a training set :param y: labels :return: """ self.model = self.soft_svm.fit(X, y) def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ # return self.model.predict(X) return self.soft_svm.predict(X) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict class Logistic: def __init__(self, model=None): self.logistic = LogisticRegression(solver='liblinear') self.model = model def fit(self, X, y): """ this method learns the parameters of the model and stores the trained model (namely, the variables that define hypothesis chosen) in self.model. :param X: a training set :param y: labels :return: """ self.model = self.logistic.fit(X, y) def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ return self.logistic.predict(X) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict class DecisionTree: def __init__(self, model=None): self.tree = DecisionTreeClassifier(max_depth=10) self.model = model def fit(self, X, y): """ this method learns the parameters of the model and stores the trained model (namely, the variables that define hypothesis chosen) in self.model. :param X: a training set :param y: labels :return: """ self.model = self.tree.fit(X, y) def predict(self, X): """ This function predicts the label of each sample. :param X: an unlabeled test set X :return: Returns a vector of predicted labels y """ return self.tree.predict(X) def score(self, X, y): """ :param X: an unlabeled test set X :param y: true labels y of this test set :return: returns a dictionary with the following fields : num samples: number of samples in the test set error: error (misclassification) rate accuracy: accuracy FPR: false positive rate TPR: true positive rate precision: precision recall: recall """ num_samples = X.shape[0] self.fit(X, y) y_pred = self.predict(X) TP = np.count_nonzero((y + y_pred > 1)) FN = np.count_nonzero((y - y_pred > 1)) FP = np.count_nonzero((y - y_pred < -1)) TN = np.count_nonzero((y + y_pred < -1)) P = len(np.argwhere(y > 0)) N = len(np.argwhere(y < 0)) error = (FN + FP) / (P + N) accuracy = (TP + TN) / (P + N) FPR = FP / N TPR = TP / N precision = TP / (TP + FP) recall = TP / P dict = {'number samples': num_samples, 'error': error, 'accuracy': accuracy, 'FPR': FPR, 'TPR': TPR, 'precision': precision , 'recall': recall} return dict
def read_only_properties(*attrs): """ Decorator to make select attributes from a class read-only. Overrides _setattr_ to raise an AttributeError whenever any attributes listed in attrs is set. This results in attributes that are initially writable (during __init__ of the object), but immediately after __setattr__ is overridden to protect the attributes, so it can only be done on an attribute that is fixed after instantiation. Modified from: https://stackoverflow.com/questions/14594120/python-read-only-property https://github.com/oz123/oz123.github.com/blob/master/media/uploads/readonly_properties.py Args: *attrs: String names of attributes to be read-only """ def class_decorator(cls): class WrappedClass(cls): """The wrapped class""" def __setattr__(self, key, value): if key in attrs and key in self.__dict__: raise AttributeError(f"Cannot set attribute {key} - attribute is protected") else: super().__setattr__(key, value) return WrappedClass return class_decorator
import collections import six import time import re def is_iterable(arg): """ Returns whether an argument is an iterable but not a string From stackoverflow: "how to tell a varaiable is iterable but not a string" Args: arg: some variable to be tested Returns: (bool) """ return ( isinstance(arg, collections.Iterable) and not isinstance(arg, six.string_types) ) class Timer: def __init__(self, exit_message=None): """ Construct a simple timer class Args: exit_message (str): If used as a context manager, this message is prepended to the context exit message """ self.reference_time = None self.reset() if exit_message is not None: self.exit_message = exit_message + ": " else: self.exit_message = "" def elapsed(self): """ Return the time elapsed between when this object was instantiated (or last reset) and now Returns: (float): Time elapsed in seconds """ return time.perf_counter() - self.reference_time def reset(self): """ Reset the reference timepoint to now Returns: None """ self.reference_time = time.perf_counter() def __enter__(self): pass def __exit__(self, *_): print(f"{self.exit_message}Elapsed={self.elapsed()}s") def network_path_to_python(path): """ Convert a network path (right click, copy network path) to a path that works in python Args: path (str): Path, like "file://somewhere/some%20thing.txt" Returns: (str): Path in format that will work inside Python, eg: "file://somewhere/some%20thing.txt" becomes "file:\\somewhere\some thing.txt" """ path = re.sub(r'file:', '', path) path = re.sub(r'/', "\\\\" , path) path = re.sub(r'%20', ' ', path) return path
#!/usr/bin/env python # coding: utf-8 # In[1]: from IPython.display import clear_output def display_board(board): clear_output() print(board[7]+' |'+board[8]+' |'+board[9]) print('----') print(board[4]+' |'+board[5]+' |'+board[6]) print('----') print(board[1]+' |'+board[2]+' |'+board[3]) print('----') # In[2]: def player_input(): marker=' ' while marker not in ['X','O']: marker=input('Player1:Choose between X or O: ') if marker=='X': return ('X','O') else: return ('O','X') # In[3]: Player1_marker,Player2_marker=player_input() # In[4]: Player2_marker # In[5]: def place_marker(board,marker,position): board[position]=marker # In[6]: def win_check(board,mark): return ((board[7]==mark and board[5]==mark and board[3]==mark) or (board[1]==mark and board[2]==mark and board[3]==mark) or (board[4]==mark and board[5]==mark and board[6]==mark) or (board[7]==mark and board[8]==mark and board[9]==mark) or (board[1]==mark and board[4]==mark and board[7]==mark) or (board[2]==mark and board[5]==mark and board[8]==mark) or (board[3]==mark and board[6]==mark and board[9]==mark) or (board[1]==mark and board[5]==mark and board[9]==mark)) # In[7]: import random def choose_first(): flip=random.randint(0,1) if flip==0: return 'Player1' else: return 'Player2' # In[8]: def space_check(board,position): return board[position]==' ' # In[9]: def full_board_check(board): for i in range(1,10): if space_check(board,i): return False return True # In[10]: def player_choice(board): position=0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position): position=int(input('Choose a position (1-9): ')) return position # In[11]: def replay(): choice=input('Play again:Enter Yes or NO: ') return choice=='Yes' # In[12]: #main code print('WELCOME TO PLAY TIC TAC TOE') while True: the_board=[' ']*10 Player1_marker,Player2_marker=player_input() turn = choose_first() print(turn + "will go first") play_game = input ('Ready to play y or n: ') if play_game=='y': game_on=True else: game_on=False while game_on: if turn =='Player1': display_board(the_board) position=player_choice(the_board) place_marker(the_board,Player1_marker,position) if win_check(the_board,Player1_marker): display_board(the_board) print('PLAYER1 HAS WON !') game_on=False else: if full_board_check(the_board): display_board(the_board) print('TIE GAME') game_on=False else: turn ='Player2' else: display_board(the_board) position = player_choice(the_board) place_marker(the_board,Player2_marker,position) if win_check(the_board,Player2_marker): display_board(the_board) print('PLAYER2 HAS WON !') game_on=False else: if full_board_check(the_board): display_board(the_board) print('TIE GAME') game_on=False else: turn = 'Player1' if not replay(): break # In[ ]: # In[ ]:
# Jumping number is the number that All adjacent digits in it differ by 1. def jumping_number(number) : s, i = str(number), 1 for each in s : if i == len(s) : return 'Jumping!!' elif int(each) == int(s[i]) - 1 or int(each) == int(s[i]) + 1 : i = i + 1 return 'Not!!' print(jumping_number(9)) print(jumping_number(23)) print(jumping_number(8987)) print(jumping_number(5679))
# Given an array/list [] of integers , Find The maximum difference # between the successive elements in its sorted form. def max_gap(numbers) : sorted_nums = sorted(numbers) lst, i, diff = [], 1, 0 for each in sorted_nums : if i == len(numbers) : break diff = sorted_nums[i] - each lst.append(diff) i = i + 1 return max(lst) print(max_gap([13,10,2,9,5])) # print(max_gap([13,3,5])) # print(max_gap([24,299,131,14,26,25])) # print(max_gap([-7,-42,-809,-14,-12])) # print(max_gap([-1,-1,-1]))
def duty_free(price, discount, holiday_cost): # return int(holiday_cost / (price - (((100-discount)/100) * price))) # discount_percent = (100 - discount) / 100 # discount_price = price * discount_percent # savings = price - discount_price # how_many_bottles = int(holiday_cost / savings) # return how_many_bottles # another way with less math haha saving = price * discount / 100.0 print(saving) return int(holiday_cost / saving) print(duty_free(10, 10, 500)) print(duty_free(12, 50, 1000))
# Create a function named divisors/Divisors that takes an integer n > 1 # and returns an array with all of the integer's divisors(except for 1 and # the number itself), from smallest to largest. If the number is prime return # the string '(integer) is prime' (null in C#) (use Either String a in Haskell # and Result<Vec<u32>, String> in Rust). def divisors(integer) : lst = [] index = 2 while index < (integer + 1) / 2 : case = integer % index if case == 0 : lst.append(index) index = index + 1 if len(lst) == 0 : return str(integer) + ' is prime' else : return lst print(divisors(5))
# In this Kata, you will be given an array of numbers in which two numbers # occur once and the rest occur only twice. Your task will be to return the # sum of the numbers that occur only once. # For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 # occur once, and their sum is 15. # first solution # def repeats(arr) : # new_lst = [] # for each in arr : # if arr.count(each) == 1 : # new_lst.append(each) # # return sum(new_lst) # list comprehension # def repeats(arr) : # return sum([i for i in arr if arr.count(i) == 1]) # apparently didn't need the brackets, neat def repeats(arr) : return sum(i for i in arr if arr.count(i) == 1) print(repeats([4,5,7,5,4,8]))
def alternate_case(s) : st = '' for each in s : if each.isupper() : st += each.lower() elif each.islower() : st += each.upper() else : st += each return st # return s.swapcase() print(alternate_case('Hello World'))
states = { 'AZ': 'Arizona', 'CA': 'California', 'ID': 'Idaho', 'IN': 'Indiana', 'MA': 'Massachusetts', 'OK': 'Oklahoma', 'PA': 'Pennsylvania', 'VA': 'Virginia' } def by_state(str) : # long and convoluted but it works! new_str = '..... ' state_list = [] str_list = [] split = str.split('\n') for each in split : state = each[-2:] try : full_state = states[state] except : quit() if full_state not in state_list : state_list.append(full_state) no_commas = each.split(',') no_commas[2] = no_commas[2][:-2] + full_state for part in no_commas : new_str = new_str + part str_list.append(new_str) new_str = '..... ' str_list = sorted(str_list) another_list = [] big_str = '' i = 0 for each in sorted(state_list) : big_str = big_str + each + '\r\n' for person in str_list : if i < len(str_list) - 1: if each in person : big_str = big_str + person + '\r\n' i = i + 1 else : if each in person : big_str = big_str + person i = i + 1 big_str = big_str + ' ' another_list.append(big_str) big_str = '' s = '' for each in another_list : s = s + each return s[:-1] print(by_state("""John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Sal Carpenter, 73 6th Street, Boston MA""")) print('=======================') print(by_state("""John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Orville Thomas, 11345 Oak Bridge Road, Tulsa OK Terry Kalkas, 402 Lans Road, Beaver Falls PA Eric Adams, 20 Post Road, Sudbury MA Hubert Sims, 328A Brook Road, Roanoke MA Amy Wilde, 334 Bayshore Pkwy, Mountain View CA Sal Carpenter, 73 6th Street, Boston MA"""))
# Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight. # Your task is to make 'Past' function which returns time converted to milliseconds. def past(h, m, s) : return ((h * 36000) + (m * 60) + s) * 1000 print(past(0, 1, 1)) lst = ['one','two','three'] def count(x) : return len(x) y = map(count, lst) print(y) print(list(y)) def counter(z) : return list(map(lambda u: len(u), z)) print(counter(['ones', 'twos', 'threes'])) def cou(t) : return list(map(lambda x: x * 3, t)) print('should be 15, 18, 21', cou([5,6,7])) def c(nums) : return set(map(lambda p: p * p, nums)) print(c((1,2,3)))
# Name: Eric A Dockery # Section: 01 # Date: 1/27/2012 # Email: [email protected] # Purpose: # Program to find the area of the face in the given picture. # Preconditions: # Given area is calculated. ## Design from math import * def main(): # 1. Measure the length of the given face. Length = eval( input( "Enter the length of the face in inches " )) # 2. Measure the width of the given face. Width = eval( input( "Enter the width of the face in inches ")) # 3. Calculate the area of the face as a whole using formula Area= Length* Width Area_whole_face = Length * Width # 4. Measure the diameter of the right eye( circle) diameter_right= eval(input( "Enter the diameter of the right eye in inches ")) # 5. Calculate the Area of the right eye using formula Area= pi*((diameter/2)**2) Area_right_eye = pi*(diameter_right/2)**2 # 6. Measure the diameter of the left eye( circle) diameter_left = eval(input( "Enter the diameter of the left eye in inches ")) # 7. Calculate the Area of the left eye using formula Area= pi*((diameter/2)**2) Area_left_eye = pi*(diameter_left/2)**2 # 8. Measure the lenght of one side of the square nose Nose = eval(input( "Enter the measurement of one side of the nose in inches ")) # 9. Calculate the area of the nose using the formula Area= side**2 Area_Nose = Nose ** 2 # 10. Measure the base of the Mouth (isosceles triangle) Base_Mouth = eval(input( "Enter the measurement of the base of the mouth in inches ")) # 11. Measure the height of the Mouth (isosceles triangle) Height_Mouth = eval(input ( "Enter the measurement of the hight of the mouth in inches ")) # 12. Calculate the area of the Mouth using formula Area = (1/2)* Base * Height Area_Mouth = (1/2)*Base_Mouth*Height_Mouth # 13. Total the Area of the Mouth, Nose, Right eye, Left eye then subtract it from the Area of the face Face_real = (Area_whole_face-(Area_right_eye + Area_left_eye + Area_Nose + Area_Mouth))//1 print ( "The Total area of the face is" , Face_real, " square inches") main() # Total area of the face is 97013.0 square inches.
# Prolog # Author: Eric Dockery # Section: 001 # Date: 1/18/2012 # Purpose: # Program to find the volume of a right cone given the length # of the radius of the base and the height # Preconditions: (input) # User supplies radius and height of the cone (as numbers, no error checking done) # Postconditions: (output) # User greeted with a message # Cone volume displayed #### Design # 1. greet the user # 2. ask the user for the radius and height and read them in # 3. calculate the area using the formula for volume (pi * radius * radius * height / 3) # 4. output the results with an appropriate label from math import * def main(): print ("Hello Human!") radius = eval(input("Enter the radius of the base of the cone ")) height = eval(input("Enter the height of the cone ")) volume = pi * radius * radius * height / 3 # volume of a cone print ("The volume of the cone is ", volume) main ()
# Names: Eric Dockery, Brent Dawson, George Grote # Lab 5 # Team:2 # Section:1 # Date 2/6/2012 #Preconditions: (input) #User will input three variables. #Postcondtions #Code will print the product of the numbers #Code will output the product in its individual digits #Code will output the products individual digits in reverse. #Design: def main(): x = eval(input("Enter a number ")) y = eval(input("Enter a number ")) z = eval(input("Enter a number ")) num = (x * y * z) # code to calculate the product of x,y and z print("The product of your numbers is ", num) # Add code that will # calculate, using mathematical operators, the three # digits of the number. # Assume that it only has three digits. # You must deal with num as a number, not a string. dig1= num//100%100 dig2= num//10%10 dig3= num%10 print("Your number is", dig1, dig2, dig3) print("Your number reversed is ", dig3, dig2, dig1, sep="") main () # Normal Test Cases: # Test case one: ##Enter a number 9 ##Enter a number 9 ##Enter a number 9 ##The product of your numbers is 729 ##Your number is 7 2 9 ##Your number reversed is 927 # # Test Case two: ##Enter a number 8 ##Enter a number 8 ##Enter a number 8 ##The product of your numbers is 512 ##Your number is 5 1 2 ##Your number reversed is 215 # # Abnormal Test Case: ##Enter a number 99 ##Enter a number 99 ##Enter a number 99 ##The product of your numbers is 970299 ##Your number is 2 9 9 ##Your number reversed is 992 # The abnormal test case only gave the first #three ouput numbers of the #product due to dig1, dig2, and dig3 only covering the #output of the first three digits.
# -*- coding:utf-8 -*- # 有如下面值的硬币 现在输入一个数值 求出与之匹配的硬币数 conins = [1, 5, 10, 50, 100, 500] def conins_list(A, input): for i in range(len(conins)-1, -1, -1): current_number = min(input[i], A/conins[i]) A -= current_number * conins[i] print "{0},{1}".format(conins[i], current_number) pass def main(): # conins number input = [10, 10, 10, 10, 3, 1] aimed_number = 138 conins_list(aimed_number, input) pass if __name__ == '__main__': main()
#!/usr/bin/env python3 """ #### # Taken from https://github.com/antoine-trux/regex-crossword-solver # All credit should go to original author # # - Changed 'xrange' to 'range' in this file to make it python3 compatible. # - Added python3 shebang # #### A program to solve regular expression crosswords like those from http://regexcrossword.com/ """ import regex as re class Crossword(object): """ The crossword puzzle The width and height index begins in the upper left hand corner """ # represents all the available characters for this puzzle possibility = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890' def __init__(self, width, height): self.width = width self.height = height self.regexes = dict( [('{}A'.format(index), []) for index in range(1, self.height + 1)] + [('{}D'.format(index), []) for index in range(1, self.width + 1)] ) self.solutions = ['' for _ in range(self.width * self.height)] self.set_possibility(self.possibility) def set_possibility(self, string): """ Replaces the current value of self.possibility with `string` """ self.possibility = string self.possibilities = [self.possibility for _ in range(self.width * self.height)] def add_to_possibility(self, string): """ For those puzzles that use more than just letters and numbers, add the extra values to the possibilities """ self.possibility += string self.possibilities = [self.possibility for _ in range(self.width * self.height)] def remove_from_possibility(self, string): for letter in string: if letter in self.possibility: self.possibility = self.possibility.replace(letter, '') self.possibilities = [self.possibility for _ in range(self.width * self.height)] def add_regex(self, index, direction, regex): """ Given the index and direction (Across or Down), add the regex to self.regexes """ if direction not in ['A', 'D']: raise ValueError('{} is not A or D'.format(direction)) elif index <= 0: raise ValueError('Index cannot be less than 0') elif direction == 'D' and index > self.width: raise ValueError('Index cannot be greater than width') elif direction == 'A' and index > self.height: raise ValueError('Index cannot be greater than height') self.regexes['{}{}'.format(index, direction)].append(regex) def solve(self, return_all=False): """ Solve the puzzle and return the results as a string. Results represent the answers read from left to right, as when reading a book. Uses the Backtracking algoritm https://en.wikipedia.org/wiki/Backtracking select next available for this spot from the available list if matches: if last spot: yay! else: go to next spot if doesn't match: set this spot back to all possibilities go back to previous spot Recursion was attempted first, but python's maximum recursion depth was hit after trying to solve a 5x5 puzzle. A while loop is being used instead. Optional arg `return_all` when set to True means this method will return a list of all possible solutions, else, only the first found solution is returned. """ index = 0 sols = [] while True: if index < 0: if return_all: return sols raise UnsolvableError('Puzzle is unsolvable!') elif not self.possibilities[index]: self.solutions[index] = '' self.possibilities[index] = self.possibility index -= 1 continue self.solutions[index] = self.possibilities[index][-1] self.possibilities[index] = self.possibilities[index][:-1] if self._check_fuzzy_solution(): if self._is_solved(): this_sol = ''.join(self.solutions) if not return_all: return this_sol sols.append(this_sol) continue index += 1 else: if not self.possibilities[index]: self.solutions[index] = '' self.possibilities[index] = self.possibility index -= 1 def _check_fuzzy_solution(self): """ Return True if the current values in self.solution returns a fuzzy match for all rows/columns """ # confirm all rows for row_index in range(1, self.height + 1): row_str = ''.join(self._get_solutions_for_row(row_index)) row_regexes = self.regexes['{}A'.format(row_index)] for regex in row_regexes: if not is_fuzzy_match(row_str, regex, max_length=self.width): return False # confirm all columns for col_index in range(1, self.width + 1): col_str = ''.join(self._get_solutions_for_col(col_index)) col_regexes = self.regexes['{}D'.format(col_index)] for regex in col_regexes: if not is_fuzzy_match(col_str, regex, max_length=self.height): return False return True def _get_solutions_for_row(self, index): """ Given an integer for the index, return the current solutions for that row """ if index < 0: raise ValueError('Index cannot be less than 0') elif index > self.height: raise ValueError( 'Index cannot be larger than the height of the crossword') begin = self.width * (index - 1) end = begin + self.width return self.solutions[begin:end] def _get_solutions_for_col(self, index): """ Given an integer for the index, return the current solutions for that column """ if index < 0: raise ValueError('Index cannot be less than 0') elif index > self.width: raise ValueError( 'Index cannot be larger than the width of the crossword') begin = index - 1 interval = self.width return self.solutions[begin::interval] def _is_solved(self): """ Return True if all elements of self.solution have values (a space is considered a value) """ return all(self.solutions) def is_fuzzy_match(string, regex, max_length=None): """ Given a string and a regular expression, return True if the string matches the beginning of the regex. For example, if string = 'A' and regex = 'A{3}', returns True because what is given of the string would match the regular expression. However, if string = 'B' and regex = 'A{3}', then return False. """ partial = len(string) != max_length pattern = re.compile(regex) if pattern.fullmatch(string, partial=partial): return True return False class UnsolvableError(Exception): pass
class Node: def __init__(self, elem=-1, children=None): self.elem = elem self.children = children class Tree(object): def __init__(self, root=None): self.root = root def add(self, elem): node = Node(elem) if self.root is None: self.root = node else: queue = [] queue.append(self.root) while queue: cur = queue.pop(0) if cur.lchild is None: cur.lchild is node return elif cur.rchild is None: cur.rchild is node return else: queue.append(cur.lchild) queue.append(cur.rchild)
user_input = str(input("Enter the string:")) text = user_input.split() # creating list of words after splitting the user input # print(text) ac = "" # defining an empty string for x in text: ac = ac + str(x[0]).upper() print(ac) # printing the final acronymn
# Lists vs Tuples ''' Definition of Constant folding: the process of recognizing and evaluating constant expressions at compile time rather than computing them at runtime ''' from dis import dis (1, 2, 3) [1, 2, 3] dis(compile('(1, 2, 3, "a")', 'string', 'eval')) print('-------------------------------------') dis(compile('[1, 2, 3, "a"]', 'string', 'eval')) print('-------------------------------------') from timeit import timeit # We can run timeit() on a tuple and a list. Lists are immutable, but process slower print(timeit("(1, 2, 3, 4, 5, 6, 7, 8, 9)", number=10_000_000)) print('-------------------------------------') print(timeit("[1, 2, 3, 4, 5, 6, 7, 8, 9]", number=10_000_000)) def fun1(): pass dis(compile('(fun1, 10, 20)', 'string', 'eval')) ''' A tuple (t1) making another tuple has the same memory address. thus t2 = tuple(t1) id(t1) == id(t2) because tuples are immutable, it doesn't make sense to have a different address ''' t = tuple() prev = sys.getsizeof(t) for i in range(10): c = tuple(range(i+1)) size_c = sys.getsizeof(c) delta, prev = size_c - prev, size_c print(f'{i+1} items: {size_c)') l = list() prev = sys.getsizeof(t) for i in range(10): c = list(range(i+1)) size_c = sys.getsizeof(c) delta, prev = size_c - prev, size_c print(f'{i+1} items: {size_c)') c = list() prev = sys.getsizzeof(l) print(f'0 items: {prev}') for i in range(255): c.append(i) size_c = sys.getsizeof(c) delta, prev = size_c - prev, size_c print(f'{i+1} items: {size_c}, delta={delta}') t = tuple(range(100_000)) l = list(t) timeit('t[99_999]', globals=globals(), number=10_000_000) timeit('l[99_999]', globals=globals(), number=10_000_000)
import unittest def running_sum(ls): '''Modify list so it contains the running sum of original elements''' for i in range(1, slen(ls)): ls[i] = ls[i-1] + ls[i] class TestRunningSum(unittest.TestCase): '''Tests for running_sum''' def test_running_sum_empty(self): '''Testing an empty list''' argument = [] expected = [] running_sum(argument) self.assertEqual(expected, argument,'The list is empty.') def test_running_sum_one(self): '''Tests a one-item list''' argument = [2] expected = [2] running_sum(argument) self.assertEqual(expected, argument, "The list contains one element.") def test_running_sum_two(self): '''Tests two-item list''' argument = [2,5] expected = [2,7] running_sum(argument) self.assertEqual(expected, argument, "The list contains two items.") def test_running_sum_multi_neg(self): '''Tests a list of negative values''' argument = [-1, -5, -3, -4] expected = [-1, -6, -9, -13] running_sum(argument) self.assertEqual(expected, argument, 'The list constains only negative values.') def test_running_sum_multi_zeros(self): '''Tests a list of zeros''' argument = [0,0,0,0] expected = [0,0,0,0] running_sum(argument) self.assertEqual(expected, argument, 'The list contains only zeros') def test_running_sum_multi_pos(self): '''Tests a list of positive values''' argument = [4, 0, 2, -5] expected = [4, 4, 6, 1] running_sum(argument) self.assertEqual(expected,argument, "The list constains zeros and positive and negative values.") if __name__ == '__main__': unittest.main(argv=['first-arg-is-ignored'], exit=False)
#functioms with outputs # use print or return same here def format_name(f_name, l_name): f_name_edited = f_name.title() l_name_edited = l_name.title() return f"{f_name_edited} {l_name_edited}" #however we need to save the function that trigger in a variable then print or just print the new function it need print man = format_name("pro" ,"BrJ") print(man) #notice even if lower case or up it is same result #JUST IMAGINE LEN() we need input which is string that give return function then we print it outunct
#advanced python arguments not how to argument but how to specfify a large range of inputs u know keyword argument? it is better while you create the function u specfify paramter and argument together then u just clal function name easy though we can change it while declaring but yea it will always have defulte value so when you Hover over a function and see =... = defult value is given arg = argumeent if u hover a function you would know what argument(value)to give too optional = no need to wirte them since they have defult value(hover to see) you can implement using paramter or not also optional very epic #Unlimited argument use *then name of paramter mostly #args u can use other name if u Warning lets test it lets test it # def add(*args): # sum = 0 #also can do positions args[0] # for n in args: # sum += n # return sum #notice return is never in a for loop #here it does in tuple list do the stuff # print(add(45,1,1)) # **kwargs = keywoard arguments and ** = many so many kwargs #here is a test # def calculate(n,**kwargs): # print(kwargs) # it is like dictionary # # for key,value in kwargs.items(): # # print(key) # # print(value) # # or simply # print(kwargs["add"]) # n += kwargs["add"] # n *= kwargs["multiply"] # print(n) # so they took thee code and did like this since intially tinenter was not based on python also this way does not show agruments # calculate(2,add= 5,multiply = 3) class Car: def __init__(self,**kwargs): self.make = kwargs.get("make") self.model = kwargs.get("model") #use.get so that u dont get error dont use other ay car = Car(make = "bro") # if u dont specficy then it ill give 0 #this is conveting that is why we use this way and it is like this not that effient as others print(car.make)
# some websites does not have api so we use webscarbing #or api does not let us do what we want to do #webscarbing = look in underline html code to get the information we want #so today we will learn how to make soup beautiful soup it is a library that help people like us make sense of websites like even webpage as google.com if we see page source it is so big and complicated and if u want to make sense of it and pull main important information then we need html passer like beutiful soup to pull out the html stracture once we make it we can take any website so at end we can pull data with the stracutre pretty epic to copy websites too #beutoful soup is used to pass html data = helps you extract data contained in a website #it can also pull data from xml files and html are both stractural langauges #it saves us a lot of time to geet the data you want from a website from bs4 import BeautifulSoup #bs4 means beutifulsoup 4 import lxml with open("website.html") as file: content = file.read() #once file is read then we can save it as content #now we can start using beutiful soup soup = BeautifulSoup(content,"html.parser") # soup = BeautifulSoup(content,"lxml") #creating new object from that imported class #markup = the html site #next paramter is the passer = what type of document is this = it can be html or xml #called parser #though better use lxml we install and import it #html parser gives error sometimes os ya stick to lxml #now this soup object allow access various part of our website using code # an example # print(soup.title) # print(soup.title.name) #name of title tag is title # print(soup.title.string) #note very important soup here is basically the eentire html site # print(soup) #there is a method called prettyfiy that indent all the site to make it look more clear # print(soup.prettify()) # print(soup.a) #this give us the first anchor tag in our website #we can change/swap this with first p or first li = first paragraph or list #but what if we want all the paraghraphs and achor tag in our website #then we use a meethod called find_all it is the most commonly used #example # all_anchor = soup.find_all(name="a") #change this a string to anything u want to find # print(all_anchor) # #what if we want to just know the text in the acnhor tag # # we neeed for loop # for tag in all_anchor: # # print(tag.getText()) #this method prints all the text in the anchor tag # #what if we want to get hold of the hrehf the link # print(tag.get("href")) #it will give thee link we used the get method alone #using the find_all method we can not just search names but also search attributes very useful if we want to search by id/class # heading = soup.find(name = "h1",id="name") #or soup.find_all() #this seearches for first item in quiry that is usually the defult # print(heading) #same with class # section_heading = soup.find(name="h3",class_="heading") #easy fix use _ after class to fix the resvered keyword bug usually in most library they do that for resvered keywords # print(section_heading) # #though we usually get error cuz class keyord is a resevered keyword in python = special word which can only be used for creating class if other word the same resvered keyword means a word that can only be used to do one thing like pass or break # print(section_heading.getText()) # print(section_heading.name) #name of tag # print(section_heading.get("class")) #those wasy might not work cuz some sites are so big and that is by narrowing the thing by its unique like this anchor tag is inside a p tag inside an em tag inside a strong tag #we can use seleectiors #example company_url = soup.select_one(selector="p a") #select gives all matching item and selectone one just the firt matching item #so here we are looking for an anchor tag that sits in a paragraph tag and this string #is the css selector print(company_url) #we can also use the class or id name = soup.select_one(selector="#name") #to select id we use pound sign = hash tag then name of id #same as id using in css we use # print(name) #note css selector is how u work with css like .class #id and normal p a where a inside p #both and p are tags so it is a tag inside a tag it can be different tags headings = soup.select(selector=".heading") # same as we using in css we use . for class print(headings) #this can be useful to seend our self daily msg to see the most highest number all those cool for statics
for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) #note if is paried with else that is why it print the else with the third else so please use elif
#we gonna create habit tracker using piexal api =japanese developer #shows intensity of how u did a day like high colored = read a lot of pages # we used get requests #there is 3 others than get request which are post put delete #the code looks pretty much the same #get = ask external system for particaluar pieace of data they give that in a response #post request we give data and we just want a reseponse of success or NotADirectoryError# #like posting data to google sheet that means post !or post a tweet all through a post request #put = update external data in the external service like updating values of google sheet =updating(editing) a twitter post #delete = delete external data in external service = deleting a post or deleting a google sheet #go to pixe.la there is 6 steps to follow #token is like an api key and here in this api it should be from 8 to 120 charachter import requests from datetime import datetime USER_NAME = "bro234135" TOKEN = "brorororororoadsaddada" PIEXLA_END_POINT= "https://pixe.la/v1/users" #most data are usually in string even numbers though numbers just try without string first but ya go non string if failed it will show the error (should) in console but in case they dont show #this dictionary made here is a json data GRAPH_ID ="graph14" user_params = { "token":TOKEN, "username":USER_NAME, "agreeTermsOfService":"yes", "notMinor":"yes", } #usually see get started + open doc at same time lol #once u make the first basic api you can rock and make it better easily # response =requests.post(PIEXLA_END_POINT,json=user_params) #what aree the praramters/inputs that we wanna give to server? so first of all is the endpoint which is usually in guide after a word post # print(response.text) #try to never start a name with a number so that it does not make errors but number after a charater #colors here are named in japanese so ya sora = blue GRAPH_END_POINT = f"{PIEXLA_END_POINT}/{USER_NAME}/graphs" graph_para= { "id":GRAPH_ID, "name":"hahagraph", "unit":"hr", "type":"float", "color":"sora", } headers = { "X-USER-TOKEN":TOKEN, } # response = requests.post(url=GRAPH_END_POINT,json=graph_para,headers=headers) # print(response.text) #get response as text #ALWAYS PROVIDE PARAMTERS ALONG ARGUMENT SO THAT THE ONE READING IT KNOWS WHHAT IS HAPPENONG #PLUS WAY LESS ERRORS LIKE NOW THE CODE WOULD NOT WORK IF WE HAD NOT GIVEN THE PARAMTERS #ALONG THE ARGUMENTS #3 ways to authiticate api key paramater like usually with request #X-Api-Key HTTP header #via the authorizat HTTP header #first one is like putting in browser = bad way anybody can hack/sniff us though it is HTTPS and s stand for secure but still u can be hacked if someone have virus on ur pc and sometimes it might be leaked #follow step by step as her so that u dont waste time and get confused since each step # #in programming is a meme that need to be checked PIXEL_CREATION_ENDPOINT = F"{PIEXLA_END_POINT}/{USER_NAME}/graphs/{GRAPH_ID}" today = datetime.now() #this give us date format but not same as api ( that is normal ) #use method called strftime #she uses w3school quite alot while making project + if she have error she search #stack flow #you can give paramters here year,month,day then it will format it as well pixel_data= { "date": today.strftime("%Y%m%d"), #you can add dashes here too "quantity":"10", } # response= requests.post(url=PIXEL_CREATION_ENDPOINT,json=pixel_data,headers=headers) # print(response.text) update_endpoint = f"{PIEXLA_END_POINT}/{USER_NAME}/graphs/{GRAPH_ID}/{today.strftime('%Y%m%d')}" new_pixel_data = { "quantity":"4.5", } # response = requests.put(url=update_endpoint,json=new_pixel_data,headers=headers) # print(response.text) # do not forget to always print response in a text format delete_endpoint = f"{PIEXLA_END_POINT}/{USER_NAME}/graphs/{GRAPH_ID}/{today.strftime('%Y%m%d')}" response = requests.delete(url=delete_endpoint,headers= headers) #delete does not need data cuz it is deleting lol obvs print(response.text) #alwaysa print out the print that you usee for test so that you dont get confused + save time worrying about naming the print name since like here all took same name #change the dictionary of quanitiy to input + data to now so that you can daily us this program to track your habits pretty cool
#turtle only work with .gif format import turtle from turtle import Turtle, Screen #coordinate = spelled like cowardinate = x,y postions = coor screen = Screen() screen.title("U.S States Game") image = "blank_states_img.gif" #epic storing path ways screen.addshape(image) # this add shape to turtle turtle.shape(image) # and here we added the image to turtle # def get_mouse_click_coor(x, y): # print(x, y) # turtle.onscreenclick(get_mouse_click_coor) #wwe use this method and put inside of it this function that have 2 inputs # turtle.mainloop() # better replaced for exitonclick = keeps screen open #though we have better way answer_state = screen.textinput(title= "guess the state",prompt= "what is another state name")
print("why " + input("how are you bro?")) #input wworks beforee print() # control / to change to comment and control z to undo use thonny program for step by step ing
#files dont just have names they also have pathes #on computers there is file and folders and files can live in folders #and you can navigate(go through) serveral folders to get to a particular file # the root is the main path of folder which is represented by / #then the main path which is usually c and the path c contain folder that could contain folder and file and that folder in folder could contain files #directions are like how you worked in cordova projects same way forward slash / and this is called absolute file path always have / #relative file path = depend on the directory that we are working from also like cordova as we choose the path like an example if we are working in folder that contains the file u want to use we just say /file_name_we_wanna_use.txt so that explains why data.txt was working #fine in same main.py and how game works cool stuff so the relative file path alwways depend on the working directory #if we wanna go up we use ../ = going up 1 parents file means going up by 1 folder #./ for same place or / or nothing since same location that is why ../ is one parent (this is relative that is why ./) #go to windows press properites in a file you want to use and copy location (that is path file ) #usually windows uses \ and we should fix it to use / #each ../ means file file backward so ../../ means 2 folders up awesome to use in relative file path so that u dont repeat code again #absolute file path = always relative to the root of your computer #in windowws in c drive and relative file path is relative to currenr working directory it depend on ur stituation depend on you u can use both with open("data.txt") as cool: cool.read() print(cool)
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? \n")) #if and else should be at same indentional level to work and just #write comment here at top to preven future erros of thee spacing betwee lines in python or near to code == is equal and != is not equal # one = means assignign value 2 equa means checks equality so elif is like if so it continue codee and can be added to normal if else and put nesteed inside of it and main if elif else have different indetnt thant the nest making an epic program man if height > 180: # like here so that u dont do space error print("you can enter bro") elif height < 10: print("meh") age = int(input("what is your age\n")) if age <= 18: print ("pay more 7$") elif age == 9000 : print("pay 1000$") else: print("please pay 12$") meme = int(input("what is your meme number: ")) if meme < 18: print("okay bro") elif meme == 1023: print("no bro") else: print("omfg") else: # if no () then use : to close code for each code function used print("u can not sadly bro") #this is block of code (block = line)
def checkio(stones): ''' minimal possible weight difference between stone piles ''' print (stones) stones.sort() stones.reverse() print (stones) bag1, bag2 = 0, 0 for i in stones: # print('i:',i) if bag1 < bag2: bag1 += i else: bag2 += i print('bag1', bag1) print('bag2', bag2) return abs(bag1 - bag2) if __name__ == '__main__': print(checkio([12, 30, 30, 32, 42, 49])) print('---') print(checkio([771, 121, 281, 854, 885, 734, 486, 1003, 83, 62])) ''' assert checkio([10,10]) == 0, 'First, with equal weights' assert checkio([10]) == 10, 'Second, with a single stone' assert checkio([5, 8, 13, 27, 14]) == 3, 'Third' assert checkio([5,5,6,5]) == 1, 'Fourth' # assert checkio([12, 30, 30, 32, 42, 49]) == 9, 'Fifth' assert checkio([1, 1, 1, 3]) == 0, "Six, don't forget - you can hold different quantity of parts" assert checkio([771, 121, 281, 854, 885, 734, 486, 1003, 83, 62]) == 0 '''
# coding=utf-8 names=['Job','Favourite','Thinking'] print len(names) print names[-1] #打印倒数第一个 names.append('Append') print names[-1] names.pop() print names names.insert(0, 'First') print names[0] t = ('aaa', 'bbb', ['xx', 'yy']) t[2][0] = 'X' # t[0] = '111' # TypeError: 'tuple' object does not support item assignment print t
#scape information from website import requests #use to get webpage libraries for now html from bs4 import BeautifulSoup #lib will be responsibe to pass html code oyo_url= "https://www.oyorooms.com/hotels-in-bangalore/" req= requests.get(oyo_url) #to get the accessed content content= req.content #need to pass content to form soup object class bs4 package soup= BeautifulSoup(content,"html.parser") #The parser module provides an interface to Python's internal parser and byte-code compiler all_hotels = soup.find_all('div',{"class":"hotelCardListing"}) #each listing card info for h in all_hotels : hotel_name = h.find("h3",{"class":"listingHotelDescription__hotelName"}).text hotel_address = h.find("span",{"itemprop":"streetAddress"}).text #try and throw block in python try expected block try: hotel_rating = h.find("span",{"class":"hotelRating__ratingSummary"}).text except AttributeError: pass hotel_cost = h.find("span",{"class":"listingPrice__finalPrice"}).text print(hotel_name,hotel_address,hotel_cost,hotel_rating)
class View: def display(self, list_of_dictionaries): for dictionary in list_of_dictionaries: for key in dictionary: print("{0} = {1}".format(key, dictionary[key])) import plotly print(plotly.__version__) # version >1.9.4 required """ plotly.offline.plot({ "data": [ Scatter(x=[1, 2, 3, 4], y=[4, 1, 3, 7]) ], "layout": Layout( title="hello world" ) }) """ # Learn about API authentication here: https://plot.ly/python/getting-started # Find your api_key here: https://plot.ly/settings/api # import plotly.plotly as py # import plotly.graph_objs as go fig = { 'data': [{'labels': ['Sales'], 'values': [19, 26, 55], 'type': 'pie'}], 'layout': { 'title': 'Forcasted 2014 U.S. PV Installations by Market Segment'} } plotly.offline.plot(fig)
# NoteMaster # Prompts the user to create a journal entry - to track ideas and for later reference import datetime as dt from difflib import SequenceMatcher # Welcome text (colorized) # ANSI exit codes (\033) enable text color changing 1 for style (bold), 36 for color (cyan), 4 (black background), 0 to cancel, m to finish print(''' \033[1;36;40mWelcome to NoteMaster!\033[0;36;49m Just type a note and hit enter to get started. To end your session, type \"exit\". Tip: Multiple contexts/keywords can be entered by separating them with commas.\033[0m''') file = open('journal.txt', 'r') # Brings in historical journal entries journalOldLines = [] # Stores the existing journal as a list, separated by lines journalOldWords = [] # Stores the existing journal as a list, separated by words # Converts the .txt file to a list for line in file: stripped_line = line.strip() line_list = stripped_line.split() journalOldLines.append(stripped_line) journalOldWords.append(line_list) file = open('journal.txt', 'a+') # Allows adding entries to the journal journalNew = [] # List for storing journal entries created in the current session context = '' # Compares similarity of strings - find past journal entries that are relevant to what's being typed now def similar(a,b): return SequenceMatcher(None,a,b).ratio() if __name__ == '__main__': # Allows the program to run repeatedly while True: entry=input("\n\033[1;36;49mNote: \033[0m") # Prompts user to create a new note if entry.lower() == 'exit': # Session will end if the use types "exit" (case insensitive) break entry2=input("\033[1;36;49mContext(s): \033[0;33;49m%s\tChange?: \033[0m" % context) # Shows current context and allows user to change context(s) if entry2 != '': # Previous context will be maintained if the user makes no change context = entry2 entry3=input("\033[1;36;49mKeyword(s): \033[0m") # Prompts user to enter keyword(s) for the new note now=dt.datetime.now() journal_entry=str(now)+' '+entry+' CONTEXT: '+context+' KEYWORDS: '+entry3 # Adds time, context, and keywords to the new note journalNew.append(journal_entry) # Adds new note to the python list file.write(journal_entry+'\n') # Writes new note to the text file similarityRatio = 0.0 similarityLine = '' # Compares the similarity of the current note with the entries in the journal when the app was opened # Displays the most similar result # Needs adjustment for string length, it misses obvious matches for i in range(len(journalOldLines)): ratioTest = similar(journal_entry.partition(' ')[2].partition(' ')[2],journalOldLines[i].partition(' ')[2].partition(' ')[2].partition(' CONTEXT: ')[0]) if ratioTest>similarityRatio: similarityRatio=ratioTest similarityLine=journalOldLines[i] print('\033[1;36;49mSimilar Note: \033[0;33;49m'+similarityLine.partition(' ')[2].partition(' ')[2].partition(' CONTEXT: ')[0]+"\033[0m") # Prints most similar journal entry # Prints notes that were created in the current session without timestamps print('\n\033[1;36;49mNew Notes:\033[0m') for i in range(len(journalNew)): print(journalNew[i].partition(' ')[2].partition(' ')[2]) # Consider removing/reducing weight of non-descriptive words. ex. "the" # Rank words and phrases by descriptiveness, common words will be lower # Add the ranking score of matched words between the note entered and each line or group of notes # Possibly adjust for long sentences # Consider synonym strength # Later, add tools to analyze notes
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Put your code into 'input' # I'll try not to use RegEx. It'll be hard! input = '''( ((pattern) ê (replacement)) (ê) )''' # ① Obliger GlobalScope # ② Obliger PatternScheme class LanghException(Exception): """ Langh's most basic Exception. """ def __init__( self, w ): self.reason = w print(self) def __str__( self ): return self.__class__.__name__ + ': ' + self.reason class LanghError(LanghException): """ Langh's Error. It stops compilation. """ def __init__( self, w ): LanghException.__init__(self, w) from sys import exit exit(1) class LanghWarning(LanghException): """ Langh's Warning. Compilation continues. """ pass class SyntaxError(LanghError): pass class GrammarError(LanghError): pass def split_in_scopes( input ): """ str -> [str,] Splits the first level of Scopes """ scopes = [] c = input + '\n' buffer = '' n = 0 # n(i) nn = n # n(i-1) def change_n( new ): "Can't use one-level up variables" #global n #global nn nn = n n = new try: for i in range(len(c)): if c[i] == '(': #change_n(n + 1) nn = n # n(-1) n = n+1 # n(0) if nn != 0: buffer += c[i] elif c[i] == ')': #change_n(n - 1) nn = n # n(-1) n = n-1 # n(0) if n == 0: #print(buffer)# scopes.append(buffer) buffer = '' buffer += c[i] else: buffer += c[i] #print(n)# if len(scopes) == 0: raise GrammarError( "you didn't mind to embed your code in the GlobalScope, didn't you?") if n < 0: # Une ')' trouvée, sans paire '(': # Le dernier scope est celui en cause raise SyntaxError( "cannot find (Global||local)Scope's ending" '\n' \ "In: " + scopes[len(scopes) -1] + ')' '\n' \ "Near " + '-'*(len("In: ") + len(scopes[len(scopes) -1]) -len("Near ") -len(')')) + '↗' '\n' \ '\t' "(unmatching left parenthesis)" ) except LanghException as e: pass print(scopes)# return scopes # ① Spliter en sous scopes scopes = split_in_scopes(input) n = nn = 0 # ② Appliquer les schemes for scope in scopes: split_in_scopes(scope) c = scope for i in range(len(c)): pass
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 15:50:49 2020 @author: VIRUS """ """ stack = [] def Push(): element = input("Enter a number: ") stack.append(element) print("Element added: ",stack) def PopElement(): if not stack: print("stack underflow!") else: elem = stack.pop() print("Removed Element: ", elem) print(stack) def PrintStack(): if not stack: print("Stack Underflow") else: for i in stack: print(i) while True: print("Select the operation to be performed: 1.Push, 2.Pop, 3.Print Stack, 4.print top most elem 5.Quit") choice = int(input()) if choice == 1: Push() elif choice == 2: PopElement() elif choice == 3: PrintStack() elif choice == 4: print("The top most element is: ",stack[-1]) elif choice == 5: break else: print(stack) """ #example 2 #impleamenting stack using list stack = [] #a function pushing elements into a stack def Push(): element = int(input("Enter an element: ")) stack.append(element) print("Element added in the stack is: ",element) #a function poping elements from a stack def Pop(): if not stack: print("Stack underflow") else: value = stack.pop() print("Element poped: ", value) #a function displaying the top most element in a stack def PrintTop(): if not stack: print("Stack underlow") else: print("The top most element in the stack is: ",stack[-1]) while True: print("Choose an option: 1.Push, 2.pop, 3.Print top elem, 4.Print stack, 5.Quit") choice = int(input()) if choice == 1: Push() elif choice == 2: Pop() elif choice == 3: PrintTop() elif choice == 4: print(stack) elif choice == 5: break else: print("Enter a valid choice!")
def soma(x,y): print(x+y) soma (2,10) print() def soma(x,y, z=2): print(x+y+z) soma (2,10) print() # * siginifa uma lista ou tupla # ** significa um dicionário def funcaoDinamica(*args, **kwargs): print(args) print(kwargs) funcaoDinamica(1, 'a', texto = 'teste')
import math linha = input().split() A = float(linha[0]) B = float(linha[1]) C = float(linha[2]) areaTriangulo = (A*C)/2 areaCirculo = 3.14159*math.pow(C,2) areaTrapezio = (((A+B))*C)/2 areaQuadrado = math.pow(B,2) areaRetangulo = A*B print('TRIANGULO: {:.3f}'.format(areaTriangulo)) print('CIRCULO: {:.3f}'.format(areaCirculo)) print('TRAPEZIO: {:.3f}'.format(areaTrapezio)) print('QUADRADO: {:.3f}'.format(areaQuadrado)) print('RETANGULO: {:.3f}'.format(areaRetangulo))
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches # how big is our world? SIZE = 100 def generate_circles(num, mean, std): """ This function generates /num/ random circles with a radius mean defined by /mean/ and a standard deviation of /std/. The circles are stored in a num x 3 sized array. The first column is the circle radii and the second two columns are the circle x and y locations. """ circles = np.zeros((num,3)) # generate circle locations using a uniform distribution: circles[:,1:] = np.random.uniform(mean, SIZE-mean, size=(num,2)) # generate radii using a normal distribution: circles[:,0] = np.random.normal(mean, std, size=(num,)) return circles # generate circles: world = generate_circles(10, 8, 3) print world # now let's plot the circles: ax = plt.subplot(111) fcirc = lambda x: patches.Circle((x[1],x[2]), radius=x[0], fill=True, alpha=1, fc='k', ec='k') circs = [fcirc(x) for x in world] for c in circs: ax.add_patch(c) plt.xlim([0,SIZE]) plt.ylim([0,SIZE]) plt.xticks(range(0,SIZE + 1)) plt.yticks(range(0,SIZE + 1)) ax.set_aspect('equal') ax.set_xticklabels([]) ax.set_yticklabels([]) plt.show()
import pandas as pd import numpy as np df_csv=pd.read_csv("nyc-east-river-bicycle-counts.csv") df_bridge=df_csv[df_csv.columns[6:8]] x=df_bridge[df_bridge.columns[0]] y=df_bridge[df_bridge.columns[1]] def gradient_descent(): w=0 b=0 lr=0.000000001 num_iter = 10000 n = len(x) for i in range(num_iter): yi = w * x + b J_cost = (1/n)*sum([val**2 for val in (y - yi)]) wd = -(2/n)*sum(x*(y-yi)) bd = -(2/n)*sum(y-yi) w = w - lr * wd b =b - lr * bd return w, b if __name__=='__main__': w,b=gradient_descent() print("w {}, b {}".format(w,b))
# Задача 2. Вариант 3. # Напишите программу, которая будет выводить на экран наиболее понравившееся вам # высказывание, автором которого является Нострадамус. # Не забудьте о том, что автор должен быть упомянут на отдельной строке. S = "Жизнь - это череда выборов.\n\n" Auth = "\t\tНострадамус" print(S,Auth) inp = input() # KAKURKIN I.V. # 29.02.2015
# Задача 1, Вариант 12 # Напишите программу , которая будет сообщать род деятельности и псевдоним под которым скрывается Мария Луиза Чеччарелли. # Послевывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода. # Лях А. А. # 21.05.2016 print("Мария Луиза Чечарелли, более известна как итальянская актриса Моника Витти.\n\n") input("Нажмите Enter для выхода.")
# 5. 49 ''' # , . ''' # Ametova M. M. # 31.03.2016 import random wifes = [" ", " ", " ", " ", " ", " ", " ", " ", " "] number = random.randint(0, 8) name = wifes[number] print(name, "- ") input("\n Enter .")
#Задача № 3. Вариант 28 # Программа вводит имя и запрашивает его псевдоним # Цкипуришвили Александр #25.05.2016 print("Анри Мари Бейль \nПод каким псевданимом он был известен?") psev=input("Ваш ответ:") if (psev)==("Стендаль"): print("Все верно! Анри Мари Бейль-Стендаль - " + psev) input("\n\n\nНажмите Enter для завершения") exit else: print("Неверно!") input("\n\n\nНажмите Enter для завершения")
#Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы #большее количество баллов за меньшее количество попыток. # Кодзоков М.М., 26.05.2016 import random pigs=("Ниф-ниф","Наф-наф","Нуф-нуф") choice=random.choice(pigs) pg=input("Угадайте одного из трех поросят: ") points=1000 while pg != choice: pg=input("Не угадали. Попробуйте еще: ") points-=100 if points <=0: break if points <=0: print("К сожалению, у вас 0 очков, и вы проиграли. А это был поросенок по имени",choice) else: print("Вы угадали. Это",choice,"! У вас",points,"очков!") input("Нажмите ENTER для продолжения")
#Задача 7. Вариант 1. #Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток. import random guessesTaken=0 print('Компьютер загадал имя одного из трех мушкетеров - товарищей д`Артаньяна. \nТвоя цель отгадать имя загаданного мушкетера.') musketry=random.choice(["Атос", "Партос", "Арамис"]) while guessesTaken < 2: print('Загаданное имя мушкетера: ') guess=input() guessesTaken=guessesTaken+1 if guess!=musketry: print('Неверно!') if guess==musketry: break if guess==musketry: print('Верно! Число использованных попыток: ', guessesTaken) if guessesTaken==1: print('Количество заработанных баллов: ', 100) if guessesTaken==2: print('Количество заработанных баллов: ', 50) if guess!=musketry: print('Попытки кончились') print('Вы не набрали баллов') input('Нажмите Enter') #Abdrahmanova G. I. #28.03.2016
# Задача 12. Вариант 50 # Разработайте игру "Крестики-нолики". #(см. М.Доусон Программируем на Python гл. 6). # Alekseev I.S. # 20.05.2016 board = list(range(1,10)) def draw_board(board): print("-------------") for i in range(3): print( "|", board[0+i*3], "|", board[1+i*3], "|", board[2+i*3], "|") print( "-------------") def take_input(player_token): valid = False while not valid: player_answer = input("Куда поставим " + player_token+"? ") try: player_answer = int(player_answer) except: print( "Некорректный ввод. Вы уверены, что ввели число?") continue if player_answer >= 1 and player_answer <= 9: if (str(board[player_answer-1]) not in "XO"): board[player_answer-1] = player_token valid = True else: print( "Эта клеточка уже занята") else: print( "Некорректный ввод. Введите число от 1 до 9 чтобы походить.") def check_win(board): win_coord = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) for each in win_coord: if board[each[0]] == board[each[1]] == board[each[2]]: return board[each[0]] return False def main(board): counter = 0 win = False while not win: draw_board(board) if counter % 2 == 0: take_input("X") else: take_input("O") counter += 1 if counter > 4: tmp = check_win(board) if tmp: print( tmp, "выиграл!") win = True break if counter == 9: print( "Ничья!") break draw_board(board) main(board)
# Задача 3. Вариант 27. # Напишите программу, которая выводит имя "Михаил Евграфович Салтыков", и #запрашивает его псевдоним. Программа должна сцеплять две эти строки и #выводить полученную строку, разделяя имя и псевдоним с помощью тире. # Denisenko A. N. # 02.06.2016 name = "Михаил Евграфович Салтыков" print(name) psevdonim = input("Введите псевдоним: ") print (name, " - ", psevdonim) input("\n\nВведите ENTER для выхода")
# Задача 7. Вариант 15. # Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее # количество баллов за меньшее количество попыток. # Чинкиров В.В. ИНБ-ДБ1 # 11.05.2016, 11.05.16 balls=7 import random print("Создайте игру, в которой компьютер загадывает имя одного из двенадцати апостолов, а игрок должен его угадать.") print("У вас 7 попыток") choice = random.randint(1,13) if choice == 1: choice="Валек" elif choice == 2: choice="Петр" elif choice == 3: choice="Андрей" elif choice == 4: choice="Иоанн" elif choice == 5: choice="Иаков" elif choice == 6: choice="Филипп" elif choice == 7: choice="Варфоломей" elif choice == 8: choice="Матфей" elif choice == 9: choice="Фома" elif choice == 10: choice="Фадей" elif choice == 11: choice="Иуда" elif choice == 12: choice="Иаков Алфеев" elif choice == 13: choice="Cимон Канонит" print("Угадайте одного из аппостолов: ") otvet = input("\nВведите имя аппостала: ") while(otvet != choice): print("\nНеправильно. Попробуй еще раз") balls=balls-1 otvet = input("\nВведите имя аппостала: ") print("Правильно! Имя аппостала",choice,"!") if balls>0: print("Вы набрали ",ochki," очков! Поздравляем!") elif balls<=0: print("У вас 0 очков. Вы проиграли. Попробуйте еще.") input("Нажмите ENTER для продолжения")
# Задача 6. Вариант 7. # Создайте игру, в которой компьютер загадывает имя одного из двух сооснователей компании Google, а игрок должен его угадать. # Zorin D.I. #11.04.2016 import random a = random.randint(1,2) if a == 1: w="Сергей Брин" elif a ==2: w="Ларри Пейдж" print("Основатель компании google: ") otvet = input("\nВведите имя: ") while(otvet != w): print("\nНеправильно. Попробуй еще раз") otvet = input("\nВведите имя: ") print("Правильно!", w,"!") input("Нажмите ENTER для продолжения")
#Задача №3. Вариант 6 #Борщёва В.О #02.03.2016 print("Герой нашей сегодняшней программы-Самюэл Ленгхорн Клеменс") psev=input("Под каким же именем мы зтого человека? Ваш ответ:") if(psev)==(Марк Твен): print(Все верно:Самюэл Ленгхорн Клеменс-"+psev) else: print("Вы ошиблись. это ни его псевдоним.") input("Нажмите Enter для выхода ")
#Задача 9. Вариант 32. #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. #Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо #буква в слове, причем программа может отвечать только "Да" и "Нет". #Вслед за тем игрок должен попробовать отгадать слово. # Ширлин Вячеслав Викторович # 29.04.16 import random WORDS = ("стол" , "стул" , "ствол", "машина", "карты" , "больница" ,"дом") word = random.choice(WORDS) print("\t\Приветствуем!") print("Даем вам 10 попыток для отгадки слова, которое загадал компьютер.") print("У тебя есть возможность узнать, есть ли определенная буква в слове.Затем ты можешь сразу сказать слово.") print("Поехали!") print("\nКоличество букв в слове:", len(word)) tries = 10 letter = () while tries >= 1: letter = str(input("В этом слове есть буква: ")) if letter not in word: tries -= 1 print("\nК сожалению, этой буквы нет в слове!") print(" У вас осталось", tries, "попыток(ки)!") if letter in word: tries -= 1 print("\nВы угадали, эта буква есть в слове!") print("У вас осталось", tries, "попыток(ки)!") no_assumptions= "Нет предположений" print("\nВаши 10 попытки исчерпаны, вы готовы угадать слово?") print("Если вы сдались и не хотите продолжать, напишите'Нет предположений' .") correct = (input("\nЭто слово: ")) while correct != word: print("Попробуйте еще раз!") correct = (input("\nЭто слово: ")) if correct == word: print("\n Спасибо за игру! Вы выиграли!Поздравляю!") if correct == i_dont_know: print("\n Спасибо за игру!Очень жаль!Может стоит попробовать еще?") break input("\nНажмите Enter для выхода")
# -*- coding: UTF-8 -*- # Задача 5. Вариант 15. # Напишите программу, которая бы при запуске случайным образом отображала название одного из двенадцати городов, входящих в Золотое кольцо России. # Mochalov V. V. # 08.03.2016 import random x=random.randint(1, 12) if x == 1: print ('Сергиев Посад') elif x == 2: print ('Переславль-Залесский') elif x == 3: print ('Ростов') elif x == 4: print ('Ярославль') elif x == 5: print ('Кострома') elif x == 6: print ('Иваново') elif x == 7: print ('Суздаль') elif x == 8: print ('Владимир') elif x == 9: print ('Углич') elif x == 10: print ('Плёс') elif x == 11: print ('Юрьев-Польский') elif x == 12: print ('Тутаев') input("\n\nНажмите Enter для выхода.")
#Задача 10. Вариант 10. #1-50. Напишите программу "Генератор персонажей" для игры. Пользователю должно быть предоставлено 30 пунктов, которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но и возвращать их туда из характеристик, которым он решил присвоить другие значения. #Кишуков Назир #25.05.2016 POINT = 30 ochki = 30 person = {"Сила":"0","Здоровье":"0","Мудрость":"0","Ловкость":"0"} points = 0 choice = None while choice != 0: print(""" 1 - Добавить очков к характеристике 2 - Уменьшить очков характеристики 3 - Просмотр характеристик 0 - Выход """) choice = int(input("Выберите пункт: ")) if choice == 1: print("Пожалуйста, введите характеристику. ", len(person), "характеристики:") for item in person: print(item) char = str(input("\n:")) char = char.title() while char not in person: print("Такой характеристики не существует: ") char = str(input("\n:")) char = char.title() else: print("\nВведите количество очков. Вам доступно", ochki, "очков") points = int(input("\n:")) while points > ochki or points < 0: print("Вы не можете сделать столько очков. Доступно", ochki, "свободных очков") points = int(input("\n:")) person[char] = points print(points, "очков было добавлено к", char) ochki -= points elif choice == 2: print("Пожалуйста, введите имя характеристики. Доступно изменение для: ") for item in person: if int(person[item]) > 0: print(item) char = str(input("\n:")) char = char.title() while char not in person: print("Такой характеристики не существует: ") char = str(input("\n:")) char = char.title() else: print("\nВведите количество очков. Доступно", person[char], "очков:") points = int(input("\n:")) while points > int(person[char]) or points < 0: print("Вы не можете сделать столько очков. Доступно", person[char], "очков") points = int(input("\n:")) person[char] = points print(points, "очков было удалено") ochki= points elif choice == 3: print("\nХарактеристики Вашего героя") for item in person: print(item, "\t\t", person[item]) elif choice == 0: print("Ваш персонаж создан!") else: print("В меню нет такого пункта") input("Нажмите ENTER для продолжения")
POINT = 30 ochki = 30 person = {"Сила":"0","Здоровье":"0","Мудрость":"0","Ловкость":"0"} points = 0 choice = None while choice != 0: print(""" 0 - Выход 1 - Добавить пункты к характеристике 2 - Уменьшить пункты характеристики 3 - Просмотр характеристик """) choice = int(input("Выбор пункта меню: ")) if choice == 1: print("Пожалуйста, введите характеристику. ", len(person), "характеристики:") for item in person: print(item) char = str(input("\n:")) char = char.title() while char not in person: print("Нет такой характеристики, вы не в WoW: ") char = str(input("\n:")) char = char.title() else: print("\nВведите количество пунктов. У вас", ochki, "свободных пунктов") points = int(input("\n:")) while points > ochki or points < 0: print("Вы не можете назначить такое количество пунктов", "Доступно", ochki, "свободных пунктов") points = int(input("\n:")) person[char] = points print(points, "пунктов было добавлено к", char) ochki -= points elif choice == 2: print("Пожалуйста, введите имя характеристики.", "Доступно изменение для: ") for item in person: if int(person[item]) > 0: print(item) char = str(input("\n:")) char = char.title() while char not in person: print("Нет такой характеристики, вы не в WoW: ") char = str(input("\n:")) char = char.title() else: print("\nВведите количество пунктов. Доступно", person[char], "пунктов:") points = int(input("\n:")) while points > int(person[char]) or points < 0: print("Невозможно удалить такое количество пунктов. Доступно", person[char], "пунктов") points = int(input("\n:")) person[char] = points print(points, "пунктов было удалено") ochki += points elif choice == 3: print("\nХарактеристики Вашего героя") for item in person: print(item, "\t\t", person[item]) elif choice == 0: print("BB") elif choice == 100500: ochki += 99999999 print ("Вы ввели чит код на 99999999 поинтов") else: print("В меню нет такого пункта")
#Задача 9. Вариант 33 #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. #Perepyelkov Y.A. #04.05.2016 import random WORDS = ("питон", "анаграмма", "функции", "класс", "GIT", "gitbook") word = random.choice(WORDS) print("\t\tЗдравствуй игрок!") print("Попробуй угадать с пяти попыток слово, которое загадал компьютер.") print("Ты можешь спрашивать, есть ли определенная буква в слове. А потом скажешь слово.") print("Итак, поехали!") print("\nКоличество букв в слове:", len(word)) tries = 5 letter = () while tries >= 1: letter = str(input("В загаданном слове есть буква: ")) if letter not in word: tries -= 1 print("\nВы ошиблись, такой буквы нет в слове!") print(" У вас осталось", tries, "попыток(ки)!") if letter in word: tries -= 1 print("\nВы угадали, эта буква есть в слове!") print("У вас осталось", tries, "попыток(ки)!") i_dont_know = "Не знаю" print("\nВаши 5 попыток закончились, вы готовы угадать слово?") print("Если вы сдались и не хотите продолжать, напишите 'Не знаю'.") correct = (input("\nЭто слово: ")) while correct != word: print("Попробуйте еще раз!") correct = (input("\nЭто слово: ")) if correct == word: print("\nПоздравляю! Вы выиграли!") if correct == i_dont_know: print("\nОчень жаль!") break input("\nНажмите Enter для выхода")
# Задача 6. Вариант 28. # Создайте игру, в которой компьютер загадывает название одного из шести континентов Земли, а игрок должен его угадать. # Cherniy F. Y. # 27.03.2016 import random print("Компьютер загадал название одного из шести континентов Земли, а Вы должны его угадать.\n") continents = ('Евразия','Африка','Северная Америка','Южная Америка','Австралия','Антарктида') continent = random.randint(0,5) x = 0 #print (continents[0]\n,continents[1]\n,continents[2]\n,continents[3]\n,continents[4]\n,continents[5]) while(x != 6): print(continents[x]) x += 1 answer = input("\nВведите название континента: ") while(answer != continents[continent]): print("Неверно, попробуйте ещё раз.") answer = input("\nВведите название континента: ") print("Верно, Вы победили!") input("\nДля выхода нажмите Enter.")
#Задача 7. Вариант 46 #Создайте игру, в которой компьютер загадывает название одной из трех стран, входящих в #военно-политический блок "Антанта", а игрок должен его угадать. #Gryadin V. D. import random print("Попробуй угадать, каую страну входящих в Антанту я загадал") a = random.choice(['Англия','Франция','Россия' ]) b=input("Твой ответ:") i=0 score=0 while b!=a: print("Ты ошибся, попробуй снова") i+=1 b=input("Твой ответ:") else: print("Ты абсолютно прав!") print("Число твоих попыток: " + str(i)) if i==1: score = 100 elif i>1: score = 100-i*10 print("Твой финальный счет: " +str(score)) input("\nВведите Enter для завершения")
# Задача 6. Вариант 22. # Создайте игру, в которой компьютер загадывает имена двух братьев, легендарных # основателей Рима, а игрок должен его угадать. # Щербаков Р.А. # 22.05.2016 import random print("Комп загадал имя одного из двух братьев основавшие рим, попробуй угадать что ли") name='Рем', 'Ромул' rand=random.randint(0,1) ugad="" while ugad!=name[rand]: ugad=input("Введите слово:") input("Вы наконец то угадали!\n\nok")