text
stringlengths
37
1.41M
"area = base * altura / 2" "base = b, altura = h" #area = 0 #b = int #h = int #b = int(input("Introduce la base ")) #h = int(input("Introduce la base ")) #area = b * h/2 #print("el area del triangulo es ",area) def triangulo(num1, num2): result = 0 result = num1 * num2/2 return result def circulo(num1): result = 0 pi = 3.1416 result = pi * pow(num1,2) return result def Options(): print('Opciones') print('1. Triangulo') print('2. Circulo') print('3. Salir') return int(input('Ingrese la opcion a realizar ')) def GetValues1(): number1 = int(input('Ingrese la base: ')) number2 = int(input('Ingrese la altura: ')) return number1, number2 def GetValues2(): number1 = int(input('Ingrese el radio: ')) return number1 def GetResult1(option, number1, number2): result = 0 if option == 1: result = triangulo(number1, number2) return result def GetResult2(option, number1): result = 0 if option == 2: result = circulo(number1) return result flag = True while flag: option = Options() if option == 3: flag = False elif option > 3: print('Opcion invalida') else: if option == 1: number1, number2 = GetValues1() print(GetResult1(option, number1, number2)) else: option == 2 number1 = GetValues2() print(GetResult2(option, number1))
# This program uses a dictionary as a deck of cards. def main(): # Create a deck of cards. deck = create_deck() # Get the number of cards to deal. num_cards = int(input('How many cards should I deal? ')) # Deal the cards. deal_cards(deck, num_cards) # The create_deck function returns a dictionary # representing a deck of cards. def create_deck(): # Create a dictionary with each card and its value # stored as key-value pairs. deck = {'Ace of Spades': 1, '2 of Spades': 2, '3 of Spades': 3, '4 of Spades': 4, '5 of Spades': 5, '6 of Spades': 6, '7 of Spades': 7, '8 of Spades': 8, '9 of Spades': 9, '10 of Spades': 10, 'Jack of Spades': 10, 'Queen of Spades': 10, 'King of Spades': 10, 'Ace of Hearts': 1, '2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4, '5 of Hearts': 5, '6 of Hearts': 6, '7 of Hearts': 7, '8 of Hearts': 8, '9 of Hearts': 9, '10 of Hearts': 10, 'Jack of Hearts': 10, 'Queen of Hearts': 10, 'King of Hearts': 10, 'Ace of Clubs': 1, '2 of Clubs': 2, '3 of Clubs': 3, '4 of Clubs': 4, '5 of Clubs': 5, '6 of Clubs': 6, '7 of Clubs': 7, '8 of Clubs': 8, '9 of Clubs': 9, '10 of Clubs': 10, 'Jack of Clubs': 10, 'Queen of Clubs': 10, 'King of Clubs': 10, 'Ace of Diamonds': 1, '2 of Diamonds': 2, '3 of Diamonds': 3, '4 of Diamonds': 4, '5 of Diamonds': 5, '6 of Diamonds': 6, '7 of Diamonds': 7, '8 of Diamonds': 8, '9 of Diamonds': 9, '10 of Diamonds': 10, 'Jack of Diamonds': 10, 'Queen of Diamonds': 10, 'King of Diamonds': 10} print(type(deck)) # Return the deck. return deck # The deal_cards function deals a specified number of cards # from the deck. def deal_cards(deck, number): # Initialize an accumulator for the hand value. hand_value = 0 # Make sure the number of cards to deal is not # greater than the number of cards in the deck. if number > len(deck): number = len(deck) # Deal the cards and accumulate their values. for count in range(number): card, value = deck.popitem() print(card) hand_value += value # Display the value of the hand. print('Value of this hand: ', hand_value) ############################################# # alternate way since popitem doesn't work import random # create an empty list list_of_keys = list(deck) print(list_of_keys) for count in range(number): card = random.choice(list_of_keys) value = deck[card] print(card) hand_value += value list_of_keys.remove(card) del deck[card] print('Value of this hand: ', hand_value) # Call the main function. main()
#CAHPTER 08 PYTHON PROJECT 06 def sortStringByChar(data) : data.sort(reverse=True) return data data = ['apel', 'rambutan', 'jeruk'] dataTersort = sortStringByChar(data) print("Data baru terurut dengan karakter terbanyak ke terkecil : ", dataTersort)
#CHAP. 05 PRAK. 01 LATIHAN 03 bahasaIndo = int(input("Nilai Bahasa Indonesia : ")) mat = int(input ("Nilai Matematika : ")) ipa = int(input("Nilai IPA : ")) print ("---------------------------") if (bahasaIndo < 0) or (bahasaIndo > 100): print("Maaf input anda tidak valid") elif(mat < 0) or (mat > 100): print("Maaf input anda tidak valid") elif(ipa < 0) or (ipa > 100): print("Maaf input anda tidak valid") elif (bahasaIndo >= 60) and (ipa >= 60) and (mat > 70): print ("Status Kelulusan : LULUS") else : print ("Status Kelulusan : TIDAK LULUS") print ("Sebab :") if (bahasaIndo < 60): print ("-Nilai Bahasa Indonesia kurang dari 60") if (mat < 70): print ("-Nilai Matematika kurang dari 70") if (mat >69 and mat <71): print ("-Nilai Matematika tidak memenuhi persyaratan") if (ipa < 60): print ("-Nilai IPA kurang dari 60")
#CHAP.05 PRAK.02 LATIHAN 05 from random import randint bil = randint(0,100) print("Hi.. Nama saya Mr.Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 1 sampai dengan 100. Silahkan tebak ya..!!") tebakan = int(input("Tebakan Kamu :")) while True: if (tebakan > bil): print ("Yahhh tebakan mu terlalu besar, coba lagi") tebakan = int(input("Tebakan Kamu :")) elif (tebakan < bil): print ("Yahhh tebakan mu terlalu kecil, coba lagi") tebakan = int(input("Tebakan Kamu :")) else : print ("Yeayy tebakan mu BENAR") break
#CAHPTER 08 PYTHON PROJECT 09 listBuah = {'apel':5000, 'jeruk':8500, 'mangga':7800, 'duku':6500} def jumlahBuah(): jumlah =int(input('Massukkan jumlah Kg yang diinginkan : ')) print("--------------------------------------------") print("Total Harga : ", listBuah.get(namaBuah, 0)*jumlah) print("List buah yang tersedia : ") for x,y in listBuah.items() : print("- ", x, ":", y) while True : namaBuah = input("Masukkan nama buah yang akan dibeli : ") if(namaBuah not in listBuah.keys()) : print("Maaf, buah yang anda masukkan tidak tersedia") continue else : while True : try : jumlahBuah() break except ValueError : continue break
import re import re f1 = open('../../../datas/a.txt','r') strf1 = f1.read() print("原文件内容为:") print(strf1) strf1_list = strf1.split(' ') f1.close() # 由于原文件需要被替换的单词都是大写的英文单词 # 使用正则表达式找出原文件中所有将被替换的单词 replist = re.findall(r'[A-Z]{2,}',strf1) print("原文件中将被替换的单词为:") print(replist) print() for rep in replist: inputstr = input("Enter %s :" % rep) #print(inputstr) # 先将替换后的单词插入到原列表对应的位置 strf1_list.insert(strf1_list.index(rep),inputstr) # 再将原先的单词删除 strf1_list.remove(rep) print(strf1_list) # 将列表转换为字符串 newstr = ' '.join(strf1_list) print("替换后的内容为:") print(newstr) #将新的字符串写入文件b.txt中,并打印到屏幕 f2 = open('../../../datas/b.txt','w+') f2.write(newstr) f2.close()
def gcd(x,y): if y == 0: return x else: return gcd(y,x%y) def lcm(x,y): return x*y/gcd(x,y) x,y = map(int, input().split()) n = int(gcd(x,y)+lcm(x,y)) print(n)
import re select = re.compile(r"^[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]") while True: mail = input() if select.findall(mail): print("Yes") else: print("No")
def is_nice(line): vowels = 0 doubels = False baddies = False for i in range(len(line) - 1): if line[i] in 'aeiou': vowels += 1 if line[i] == line[i + 1]: doubels = True if line[i] + line[i + 1] in ('ab', 'cd', 'pq', 'xy'): baddies = True return vowels >= 3 and doubels and not baddies def is_nice2(line): pair = False repeat = False for i in range(len(line) - 2): if line[i:i+2] in line[i+2:]: pair = True if line[i] == line[i + 2]: repeat = True return pair and repeat def part1(): with open('.day5') as f: return sum([is_nice(line) for line in f]) def part2(): with open('.day5') as f: return sum([is_nice2(line) for line in f]) print( part1() ) print( part2() )
import csv open_file = open('alunos.csv','r') file_csv = csv.reader(open_file,delimiter=';') for [data,nome,status] in file_csv: print('{} - {} - {}'.format(data,nome,status))
import cadquery as cq # These can be modified rather than hardcoding values for each dimension. circle_radius = 50.0 # Radius of the plate thickness = 13.0 # Thickness of the plate rectangle_width = 13.0 # Width of rectangular hole in cylindrical plate rectangle_length = 19.0 # Length of rectangular hole in cylindrical plate # Extrude a cylindrical plate with a rectangular hole in the middle of it. # 1. Establishes a workplane that an object can be built on. # 1a. Uses the named plane orientation "front" to define the workplane, meaning # that the positive Z direction is "up", and the negative Z direction # is "down". # 2. The 2D geometry for the outer circle is created at the same time as the # rectangle that will create the hole in the center. # 2a. The circle and the rectangle will be automatically centered on the # workplane. # 2b. Unlike some other functions like the hole(), circle() takes # a radius and not a diameter. # 3. The circle and rectangle are extruded together, creating a cylindrical # plate with a rectangular hole in the center. # 3a. circle() and rect() could be changed to any other shape to completely # change the resulting plate and/or the hole in it. result = ( cq.Workplane("front") .circle(circle_radius) .rect(rectangle_width, rectangle_length) .extrude(thickness) ) # Displays the result of this script show_object(result)
#Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at #the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes. list = [] while True: val = input("Enter a number: ") if val == 'done': break try: flVal = float(val) except: print("Please enter a number, or enter done if you are finished") continue list.append(flVal) valMax = max(list) valMin = min(list) print("Maximum: ",valMax) print("Minimum: ",valMin)
#::::::::::::: Built-in practice: enumerate() ::::::::::::::::::::::::::::::::::::::::::: # Rewrite the for loop to use enumerate indexed_names = [] for i, name in enumerate(names): index_name = (i,name) indexed_names.append(index_name) print(indexed_names) # Rewrite the above for loop using list comprehension indexed_names_comp = [(i,name) for i,name in enumerate(names)] print(indexed_names_comp) # Unpack an enumerate object with a starting index of one indexed_names_unpack = [*enumerate(names, 1)] print(indexed_names_unpack) #::::::::::::: Built-in practice: map() ::::::::::::::::::::::::::::::::::::::::::: # Use map to apply str.upper to each element in names names_map = map(str.upper,names) # Print the type of the names_map print(type(names_map)) # Unpack names_map into a list names_uppercase = [*names_map] # Print the list created above print(names_uppercase) #::::::::::::: Basic NumPy indexing and operations ::::::::::::::::::::::::::::::::: # Print second row of nums print(nums[1,:]) # Print all elements of nums that are greater than six print(nums[nums>6]) # Double every element of nums nums_dbl = nums*2 print(nums_dbl) # Replace the third column of nums nums[:,2] = nums[:,2] + 1 print(nums)
import random #for randint function import time #for sleep function print("\n\n\t\t\tWelcome to ROCK , PAPER and SCISSORS") time.sleep(2) #two sec delay def print_value(choice): #function to print value val={1:"ROCK",2:"PAPER",3:"SCISSORS"} # values stored in dictionary time.sleep(0.5) print(val[choice]) def usr_choice(): #function to input user choice statement="""\n 1 - ROCK 2 - PAPER 3 - SCISSORS enter your choice (1/2/3) - """ print(statement) input_choice=input() try: #try block to try if user enters non int value choice=int(input_choice) except: print("\n\t\t!! invalid choice\n\tPlease enter valid choice") return(usr_choice()) if(choice!=1 and choice!=2 and choice!=3): #if else block to check value is 1/2/3 print("\n\t\t!! invalid choice\n\tPlease enter valid choice") return(usr_choice()) else: print("your choice is - ") print_value(choice) return(choice) def comp_choice(): #function to generate computer's choice choice=random.randint(1,3) print("computers choice is - ") print_value(choice) return(choice) def result(): #function to calculate result usr=usr_choice() time.sleep(1) comp=comp_choice() time.sleep(1) value=usr-comp if(value==0): print("\n\tITS A TIE !!") return(0) elif(value==-1 or value == 2): print("\n\tCOMPUTER WON !!") return(1) else: print("\n\tYOU WON !!") return(2) play="yes" comp=0 usr=0 while(play=="yes"): #loop for rematch score=result() #score, comp, usr variable to save the scores so far if(score==1): comp+=1 elif(score==2): usr+=1 time.sleep(1) print("\nSCORE - \n\tCOMPUTER = "+str(comp)+"\n\tYOU = "+str(usr)) time.sleep(1.5) print("\nDo you want to play again ? (yes/no)") play=input()
#!Python3 import tables, buildings class Unit: # all the units will have following attributes, but it is thought that the workers will be the most numerous, so # -> the default values are set for workers. def __init__(self, owner, text_name): self.owner = owner self.alive = True self.properties = tables.units_properties[text_name.lower()] self.properties['health'] = self.properties['max_health'] self.level = 1 # unit's current level/max = 5 def move(self, direction): if not self.alive: print("Dead can't dance") return self print('The unit moved '+str(self.properties['speed'])+' '+direction+'.') def describe_unit(self): if not self.alive: print("He's already dead...") return self print('-----'+self.text_name+'-----') print('maximum health - '+str(self.properties['max_health']), 'speed - '+str(self.properties['speed']), 'attack - '+str(self.properties['attack']), 'time for creating - '+str(self.properties['creating_time']), sep='\n') print('Cost for breeding:') for source, amount in self.breeding_cost.items(): print(' '+source+' - '+str(amount)) def attack(self, enemy_unit=''): if not self.alive: print("The dead doesn't bite...") return self if isinstance(enemy_unit, Unit): print(self.text_name+' is attacking the '+enemy_unit.text_name) enemy_unit.properties['health']-=self.properties['attack'] if enemy_unit.properties['health']<=0: print('The '+enemy_unit.text_name+' was cut down in battle...') enemy_unit.alive = False else: print('Choose the unit to be attacked...') def upgrade(self): if not self.alive: print("The dead can't be upgrayyed...") return self if self.level < 5: print('The unit is upgrading...') self.level += 1 self.properties['speed'] += 2 self.properties['attack'] += 5 self.properties['creating_time'] -= 1 self.properties['health'] += 10 self.properties['max_health'] += 10 print('The unit has been upgraded to level '+str(self.level)) else: print('The unit can not be uprgayyed more...') class Worker(Unit): # workers are created mainly for collecting resources but can be used for battle at an emergency def __init__(self, owner): self.text_name = 'Worker' super().__init__(owner, self.text_name) def work(self, work_obj=None): if not self.alive: print("His work is finished...") return self if work_obj == 'forest': print('The worker is starting to chop the trees...') else: print('The worker is starting to work...') def build(self, type_of_building): if type_of_building not in self.owner.has_buildings: if self.owner.check_supplies_to_create(tables.building_cost[type_of_building]): self.owner.update_supplies(tables.building_cost[type_of_building]) if type_of_building == 'Barracks': self.owner.has_buildings[type_of_building] = buildings.Barracks(self.owner) elif type_of_building == 'Castle': self.owner.has_buildings[type_of_building] = buildings.Castle(self.owner) elif type_of_building == 'Church': self.owner.has_buildings[type_of_building] = buildings.Church(self.owner) else: print('You haven\'t got enough supplies to build.') class Swordsman(Unit): def __init__(self, owner): self.text_name = 'Swordsman' super().__init__(owner, self.text_name) class Archer(Unit): def __init__(self, owner): self.text_name = 'Archer' super().__init__(owner, self.text_name) def shoot_an_arrow(self, enemy_unit=''): if not self.alive: print("The dead doesn't bite...") return self if isinstance(enemy_unit, Unit): print('The '+self.text_name+' is shooting an arrow at the '+enemy_unit.text_name+'...') enemy_unit.properties['health']-=5 if enemy_unit.properties['health']<=0: print('The '+enemy_unit.text_name+' was cut down in battle...') enemy_unit.alive = False else: print('Choose the enemy unit to be shot...') class Priest(Unit): def __init__(self, owner): self.text_name = 'Priest' super().__init__(owner, self.text_name) def heal(self, wounded_unit=''): if not self.alive: print("This priest now can heal only the souls...") return self if not wounded_unit.alive: print("It's no use healing the dead guy...") return self if isinstance(wounded_unit, Unit): print('The unit is being healed...') if wounded_unit.properties['health'] < wounded_unit.properties['max_health']: wounded_unit.properties['health']+=2 if wounded_unit.properties['health'] > wounded_unit.properties['max_health']: wounded_unit.properties['health'] = wounded_unit.properties['max_health'] else: print('Choose the unit to be healed...') class Knight(Unit): def __init__(self, owner): self.text_name = 'Knight' super().__init__(owner, self.text_name)
#!/usr/bin/python3 # Problem 6 # --------- # Sum square difference # ===================== # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # # The square of the sum of the first ten natural numbers is, # (1 +2 + ... + 10)^2 = 55^2 = 3025 # # Hence the difference between the sum of the squares of the first ten # natural numbers and the square of the sum is `3025 - 385 = 2640`. # # Find the difference between the sum of the squares of the first # one hundred natural numbers and the square of the sum. # def sum_of_squares(num): sum = 0 for i in range(1, num + 1): sum += i**2 return sum def square_of_sum(num): sum = 0 for i in range(1, num + 1): sum += i return sum**2 def main(lib): return square_of_sum(100) - sum_of_squares(100)
class Stack: def __int__(self): self.arr = [] def push(self, val): self.arr = [val] + self.arr if len(self.mins) == 0: self.mins = [val] else: if self.mins[0] >= val: self.mins = [val] def pop(self): v = self.arr[0] self.arr = self.arr[1:] return v def min(self):
class Solution: def isValid(self, s: str) -> bool: brakets = {"(": ")", "[": "]", "{": "}"} stack = [] def check(s): n = len(s) if n == 0: if len(stack) == 0: return True else: return False if s[0] in brakets: stack.append(s[0]) return check(s[1:]) else: open = stack.pop() if s[0] != brakets[open]: return False return check(s[1:]) return check(s) sol = Solution() print(sol.isValid('([]{}'))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class NodeLib: def createList(self, arr) -> ListNode: if len(arr) == 0: return None node = ListNode(arr[0]) node.next = self.createList(arr[1:]) return node def printListNode(self, root): if root is None: return print(root.val, ' -> ', end='') self.printListNode(root.next)
def translate(board, row_or_col): return [ board[x] for x in row_or_col if board[x] ] def how_many_missing(board, row_or_col): return len([ board[x] for x in row_or_col if not(board[x]) ]) def possibilities(board, sum_contraints, pos): left = set(range(1,10)) for (row_or_col, sum_) in sum_constraints: if pos in row_or_col: translated_row_or_col = translate(board, row_or_col) # remove anything that's already used in a row or col left = left.difference(set(translated_row_or_col)) # also can't go over current_sum = sum(translated_row_or_col) left = { x for x in left if (x + current_sum) <= sum_ } # if you're the last one left, you better be exactly the diff if how_many_missing(board, row_or_col) == 1: left = left.intersection({ sum_ - current_sum }) return left def brute_force(board, sum_constraints): def brute_force_loop(board, sum_constraints, pos): if pos == len(board): return board # solved # print "----------------" # print "pos:", pos # print "board:", board ps = possibilities(board, sum_constraints, pos) # print "possibilities:", ps if ps == {}: return None else: for x in ps: board[pos] = x solved = brute_force_loop(board, sum_constraints, pos + 1) if solved: return solved # none worked board[pos] = None return None return brute_force_loop(board, sum_constraints, 0) # ascii board: sums are in parens, otherwise numbers refer to index into [board] # |------+------+--------+------+------+-----| # | | | | (34) | (16) | | # | | | (8) | 0 | 1 | (8) | # | | (13) | (8\21) | 2 | 3 | 4 | # | (18) | 5 | 6 | 7 | 8 | 9 | # | (21) | 10 | 11 | 12 | | | # | | (11) | 13 | 14 | | | # |------+------+--------+------+------+-----| # (indices of board * sum) list sum_constraints = [ # horizontal ([0,1], 8), ([2,3,4], 21), ([5,6,7,8,9], 18), ([10,11,12], 21), ([13,14], 11), # vertical ([5,10], 13), ([6,11,13], 8), ([0,2,7,12,14], 34), ([1,3,8], 16), ([4,9], 8), ] board = [None] * 15 # print possibilities(board, 0) print brute_force(board, sum_constraints)
import pandas as pd #read csv into file under variable cali cali = pd.read_csv("COVID-19_Case_Geography_CA.csv", dtype = str) #print columns print("Columns" , list(cali.columns)) #drop any columns with missing variables using .dropna() on cali cali.dropna() #drop all columns except 'case_month', 'res_state', 'state_fips_code', 'res_county', 'county_fips_code', 'age_group', 'exposure_yn', 'current_status', 'death_yn' drop = ["sex", "race", "ethnicity", "case_positive_specimen_interval" , "case_onset_interval", "process" , "symptom_status" , "hosp_yn" , "icu_yn" , "underlying_conditions_yn" , "exposure_yn" , "death_yn"] #drop without creating new variable by including inplace = True cali.drop(drop, axis = "columns" , inplace =True) cali.to_csv("COVID-19_Case_Geography_CA_CLEAN.csv") #need to drop Probable Case in Rows #more_drop = ["Probable Case"] #arizona.drop(more_drop, axis = "index") #need to drop rows and columns that have blank data (thought .dropna() did that)
def double(T): return([i*2 for i in T]) tup=(1,2,3,4,5) print(double(tup))
# Python code to demonstrate the working of # degrees() and radians() # importing "math" for mathematical operations import math a = math.pi/6 b = 30 # returning the converted value from radians to degrees print ("The converted value from radians to degrees is : ", end="") print (math.degrees(a)) # returning the converted value from degrees to radians print ("The converted value from degrees to radians is : ", end="") print (math.radians(b))
n = int(input("enter the age of the person:")) if(n >= 18): print("the person is eligible to vote !!!") else: print("the person is not eligble to vote ") years = 18 - n print("you should wait for atleast " + str(years) + " years")
class ABC: cvar=0 def __init__(self,var): ABC.cvar+=1 self.var=var print("Object value is : ",var) print("Class value is : ",ABC.cvar) obj1=ABC(10) obj2=ABC(20) obj3=ABC(30) obj4=ABC(40) obj5=ABC(50)
d={1:'ravi',2:'raju',3:'sudheer',4:'sekhar'} print("1st name is"+d[1]) print("2nd name is"+d[2]) print(d) print(d.keys()) print(d.values())
num=[1,2,3,4,10] for index, i in enumerate (num): print(num)
n = int(input("enter the annual income : ")) if(n<=150000): print("the person is eligible for scholarship") else: print("the person is not eligible for scholarship")
import pickle # This program asks the user for some animals, and stores them. # Make an empty list to store new animals in. animals = [] # Create a loop that lets users store new animals. new_animal = '' while new_animal != 'quit': print("\nPlease tell me a new animal to remember.") new_animal = input("Enter 'quit' to quit: ") if new_animal != 'quit': animals.append(new_animal) # Try to save the animals to the file 'animals.pydata'. try: file_object = open('animals.pydata', 'wb') pickle.dump(animals, file_object) file_object.close() print("\nI will remember the following animals: ") for animal in animals: print(animal) except Exception as e: print(e) print("\nI couldn't figure out how to store the animals. Sorry.")
from random import randint def randArray(): array = [] for i in range(0, 10): randnum = randint(1, 100) array.append(randnum) return array def bubleSort(array): for i in range(0, len(array)): for j in range(i+1, len(array)): if array[j] < array[i]: tmp = array[j] array[j] = array[i] array[i] = tmp return array array = randArray() print(array) array = bubleSort(array) print("sorted") print(array)
# -*- coding: utf-8 -*- """ Created on Thu Mar 2 11:14:15 2017 @author: Brandon Mitchell blm150430 Assignment 1, Q1 """ """ Body mass index (BMI) is a measure of health based on weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. """ weight_conv = 0.45359237 height_conv = 0.0254 #Print statements to guide user. print('This program will measure your BMI.') print('\n') print('Body mass index (BMI) is measure of health based on weight.') print('\n') print('It can be calculated by taking your weight in kilograms and dividing it') print('by the square of your height in meters.') print('\n') #Directions for user. wgt_lbs = eval(input('Input your weight in pounds. Conversions occur automatically: ')) hgt_inch = eval(input('Input your height in inches. Conversions occur automatically: ')) print('\n') #Convert user input units into metric wgt_kg = weight_conv*wgt_lbs hgt_mtr = height_conv*hgt_inch #Compute user BMI bmi = wgt_kg / (hgt_mtr ** 2) #Display user BMI print('Your BMI is: {0:.2f}'.format(bmi))
# -*- coding: utf-8 -*- """ Created on Fri Jan 27 19:39:26 2017 @author: bmitchell """ ## Display the number from 1 to 5 num = 0 while num <= 5: print(num) num += 1 # Increment by 1.
# def is define - how to start function #def greeting(): # print("Hello, Chris!") #greeting() # def greeting(n): # print('Hello {}!'.format(n)) # name = input('What is your name?: ') # # greeting(name) # from math import sqrt as square_root # # def sqrt(): # return 'I live to drink soda!' # # print(sqrt(400)) # # from random import randrange # # print(randrange(1, 51, 2)) # mi, km, ft, m # def to_miles(measurement, amount): # km = 1.60934 # ft = 5280 # meter = 1609.34 # use pass for 'scafolding' # # def to_km(measurement, amount): # pass # # def to_ft(measurement, amount): # pass # # def to_meters(measurement, amount): # pass # unit_converter.py # print('Welcome to the unit converter!') # print() # # # allow user to input units in feet, miles, meters, or kilometers # # distance = int(input('What is the distance? ')) # input_unit = input('What is the input unit? (ft, mi, m, yd, in, or km)\n ') # output_unit = input('What is the output unit? (ft, mi, m, yd, in, or km)\n ') # # # creat dictionary with the key as a string and number as a value # # convert_from_meters = {'ft': .3048, 'mi': 1609.34, 'm': 1, 'yd': .9144, # 'in': 39.370, 'km': .0001} # convert_to_meters = {'ft': 3.28, 'mi': .0006, 'm': 1, 'yd': 1.0936, # 'in': .02541, 'km': 1000} # # # distance times convert_to lookup input unit # # x = distance * convert_to_meters[input_unit] # # # save that # # print(str(distance) + input_unit + ' is equal to ' + # str(x * convert_from_meters[output_unit]) + output_unit) # # # meters value convert_from[] lookup output unit # ______________________________________________________________________ # dictionary example # # dictionary = {'key': 'value'} # # # dict() is a built in function # # print(dictionary['key']) # phonebook = {'jones': {'first_name': 'Chris', 'last_name': 'Jones', 'phone': '503-555-5555'}} # print(phonebook['jones']) # print(phonebook['jones']['first_name']) # phonebook # ______________________________________________________________________ # poop
class Human (): count = 0 countwoman = 0 countman = 0 def __init__(self, name, lastname, age, uni, gender ): self.name = name self.lastname = lastname self.age = age self.university = uni self.gender = gender Human.count += 1 self.gen() def gen (self): if self.gender == "woman": Human.countwoman += 1 else: Human.countman += 1 def printName (self): print(self.name + " " + self.lastname)
# -*- coding: utf-8 -*- amount = float(input('Enter a amount:')) inrate = float(input('Enter a inrate:')) period = int(input('Enter a period:')) value = 0 year = 1 while year <=period: value = amount + (amount * inrate) print('every year {} rate {:.2f}'.format(year,value)) amount = value year += 1
# 类 class People(object): def __init__(self,name,age): self.name = name self.age = age self.jump() def walk(self): print("{} 在走路".format(self.name)) def eat(self): print("{}在吃饭".format(self.name)) def jump(self): print("{}跳了一下".format(self.name)) xiaoer = People("小儿",12) wangwu = People("王五",123)
print("." * 10) print("a" + "d" + "s" + "e" + "p", end=" ") formatter = "{}{}{}{}" print(formatter.format("hs","as","ds","dd")) print(formatter.format(1,2,3,9)) print(formatter.format(formatter,formatter,formatter,formatter))
# 字典 states = { 'asd' : ' ASD', 'S' : 's', 'qwewe' : 'QWEWE', 'wewewe' : 'WEWEWE' } cities = { "s" : "city", "P" : "provice", "CO" : "Contry", "asd" : "s" } cities["C"] = "ccccc" cities["AA"] = "AAAAA" print("cities",cities) print("asdada",cities[states["S"]]) # 利用key来获取value print(cities["s"]) print(cities.get('s')) # 当没有d这个key相关的value值时使用后面这个值 print(cities.get('d','sadas')) cities['d'] = 'ceshi' print(cities.get('d','sadas')) # 集合 example_list = {1,2,3,4,'23','4343'} list1 = [1,2,3333,4444,2,2,1] # 有去重功能 列表可以利用set方法转为集合,但是因为集合是无序的,所以将集合利用list转为列表时,可能会导致顺序有问题 print(set(list1)) print(list(set(list1)))
# Number Guess v1.0.0 print("") print("-------------------------Welcome To Number Guess!---------------------------------------") print("In this game, you think of a number from 1 through n and I will try to guess what it is.") print("After each guess, enter h if my guess is too high, l if too low, or c if correct.") print("----------------------------------------------------------------------------------------") print("") total_games = 0 total_guesses = 0 user_input = int(input ("Please enter a number n: ")) high = user_input play = "y" while play == "y": indicator = "" num_guesses = 0 low = 1 high = user_input guess = (low + high) // 2 num_guesses += 1 while indicator != "c": indicator = input(str(guess) +"? ") if indicator == 'c': break elif indicator == 'h': if(low + 1 == guess): guess = low break high = guess - 1 guess = (low + high) // 2 num_guesses += 1 elif indicator == 'l': if(high - 1 == guess): guess = high break low = guess + 1 guess = (low + high) // 2 num_guesses += 1 else: print("Invalid Input..Please enter c, h, or l") total_guesses = total_guesses + num_guesses total_games += 1 avg_guesses_per_game = round((total_guesses / total_games), 2) print("Your number is " + str(guess) + ".") print("It took me " + str(num_guesses) + " guesses.") print ("I averaged " + str(avg_guesses_per_game) + " guesses per game for " + str(total_games) + " game(s).") play = input ("Play again (y/n)?: ")
# Importing required packages import re from nltk.stem.snowball import SnowballStemmer # nltk library stemmer algorithm for English language stem_eng = SnowballStemmer('english') list_of_specialCharacters = [' ',',','$','-','//','..',' / ',' \\ ','.'] def string_stemmer(s): stem_resultList = [] for word in s.lower().split(): stem_resultList.append(stem_eng.stem(word)) return " ".join(stem_resultList) def find_common_words(string1, string2): count = 0 for word in string1.split(): if string2.find(word) >= 0: count += 1 return count def freq_of_words(word, string, i): count = 0 while i < len(string): i = string.find(word, i) if i == -1: break else: count += 1 i += 1 return count def replace_extraChars(word): for char in list_of_specialCharacters: if char in word: if char == '//': word = word.replace(char,'/') elif char == '..': word = word.replace(char,' . ') elif char == '.': word = word.replace(char,' . ') else: word = word.replace(char, ' ') return word def make_changes_to_query(word): x = re.search("([0-9]+)( *)\.?",word) if None != x: regex_term = 'inches|inch|in|\'' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1in. ", word) regex_term = 'foot|feet|ft|\'\'' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1ft. ", word) regex_term = 'pounds|pound|lbs|lb' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1lb. ", word) regex_term = '(square|sq) ?\.?(feet|foot|ft)' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1sq.ft. ", word) regex_term = '(cubic|cu) ?\.?(feet|foot|ft)' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1cu.ft. ", word) regex_term = 'gallons|gallon|gal' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1gal. ", word) regex_term = 'ounces|ounce|oz' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1oz. ", word) regex_term = 'centimeters|cm' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1cm. ", word) regex_term = 'milimeters|mm' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1mm. ", word) regex_term = 'degrees|degree' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1deg. ", word) word = word.replace(" v "," volts ") regex_term = 'volts|volt' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1volt. ", word) regex_term = 'watts|watt' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1watt. ", word) regex_term = 'amperes|ampere|amps|amp' if re.x(regex_term,word) is not None: word = re.sub(regex_term,"\1amp. ", word) return word def check_word_is_string(w): return isinstance(w,str) def split_two_words(string): string = re.sub(r"(\w)\.([A-Z])", r"\1 \2", string) string = string.lower() return string def preprocess_word(word): temp = check_word_is_string(word) if temp == True: word = string_stemmer(word) word = split_two_words(word) word = replace_extraChars(word) word = make_changes_to_query(word) else: word = "null" return word
class Fraction: """ This class represents one single fraction that consists of numerator and denominator """ def __init__(self, numerator, denominator): """ Constructor. Checks that the numerator and denominator are of correct type and initializes them. :param numerator: fraction's numerator :param denominator: fraction's denominator """ if not isinstance(numerator, int) or not isinstance(denominator, int): raise TypeError elif denominator == 0: raise ValueError self.__numerator = numerator self.__denominator = denominator def return_string(self): """ Returns a string-presentation of the fraction in the format numerator/denominator """ if self.__numerator * self.__denominator < 0: sign = "-" else: sign = "" return "{:s}{:d}/{:d}".format(sign, abs(self.__numerator), abs(self.__denominator)) def simplify(self): gcd = greatest_common_divisor(self.__numerator, self.__denominator) self.__numerator //= gcd self.__denominator //= gcd def complement(self): return Fraction(-1*self.__numerator, self.__denominator) def reciprocal(self): swap_numerator, swap_denominator = self.__denominator, self.__numerator return Fraction(swap_numerator, swap_denominator) def multiply(self, other): return Fraction(self.__numerator*other.__numerator, self.__denominator*other.__denominator) def divide(self, other): return Fraction(self.__numerator*other.__denominator, self.__denominator*other.__numerator) def add(self, other): multiply_denominator = self.__denominator*other.__denominator var1 = self.__numerator*(multiply_denominator//self.__denominator) var2 = other.__numerator*(multiply_denominator//other.__denominator) return Fraction(var1+var2, multiply_denominator) def deduct(self, other): multiply_denominator = self.__denominator*other.__denominator var1 = self.__numerator*(multiply_denominator//self.__denominator) var2 = other.__numerator*(multiply_denominator//other.__denominator) return Fraction(var1-var2, multiply_denominator) def greatest_common_divisor(a, b): """ Euclidean algorithm. """ while b != 0: a, b = b, a % b return a
def main(): i = 1 performance_time_list = [] while i <= 5: performance_time = float(input("Enter the time for performance %d: " % i)) performance_time_list.append(performance_time) i += 1 performance_time_list.remove(max(performance_time_list)) performance_time_list.remove(min(performance_time_list)) average_performance = float(sum(performance_time_list) / 3) print("The official competition score is %.2f seconds." % average_performance) main()
def get_input_lines(): lines = "" que = " " while que != '': que = input() lines = lines + que + " " return lines def get_single_line(words, line_length): line = "" words_rest = [] words_rest += words for item in words: if len(line)+len(item) <= line_length: line = line + " " + item words_rest.remove(item) else: final_line = line[1:len(line)] return final_line, words_rest if words_rest is []: final_line = line[1:len(line)] return final_line, words_rest def get_lines_list(words, line_length): EMPTY = [] lines_list = [] while words != EMPTY: line, words = get_single_line(words, line_length) lines_list.append(line) return lines_list def insert_extra_spaces(line, extra_spaces): line_words_list = line.split() no_of_space_positions = len(line_words_list)-1 new_line = "" total_space = extra_spaces + no_of_space_positions no_of_loop = total_space//no_of_space_positions if total_space % no_of_space_positions > 0: no_of_loop += 1 for loop in range(no_of_loop): for index in range(no_of_space_positions): if total_space != 0: line_words_list[index] += " " total_space -= 1 for item in line_words_list: new_line += item return new_line def find_length_of_longest_word (words): words_length = [] for item in words: words_length.append(len(item)) longest_word = max(words_length) return longest_word def print_lines(lines_list, line_length): for index in range(len(lines_list)-1): line = lines_list[index] current_length = len(line) extra_spaces = line_length - current_length line = insert_extra_spaces(line, extra_spaces) print(line) print(lines_list[len(lines_list)-1]) def main(): print("Enter text rows. Quit by entering an empty row.") lines = get_input_lines() lines = lines.strip() words = lines.split() line_length = int(input("Enter the number of characters per line: ")) lines_list = get_lines_list(words, line_length) print(lines_list) # print_lines(lines_list, line_length) main()
def main(): print("Give 5 numbers:") element_list = [] for i in range(0, 5, 1): number = int(input("Next number: ")) element_list.append(number) print("The numbers you entered, in reverse order:") for element in element_list[::-1]: print(element) main()
def main(): print("Give 5 numbers:") element_list = [] for i in range(0, 5, 2): number = int(input("Next number: ")) if number > 0: element_list.append(number) print("The numbers you entered that were greater than zero were:") for element in element_list: print(element) main()
# Introduction to Programming # Geometry from math import pi # square function will take the required dimension from user, # and check if it is greater than zero or not, # and which then prints the circumference # and area of the shape to two decimal places. def square(): dimension = 0 while dimension < 1: dimension = float(input("Enter the length of the square's side: ")) print('The total circumference is %.2f' % (4 * dimension)) print('The surface area is %.2f' % (dimension * dimension)) return # rectangle function will take the required dimensions from user, # and check if it is greater than zero or not, # and which then prints the circumference # and area of the shape to two decimal places. def rectangle(): dimension_1 = 0 dimension_2 = 0 while dimension_1 < 1: dimension_1 = float(input("Enter the length of the rectangle's side 1: ")) while dimension_2 < 1: dimension_2 = float(input("Enter the length of the rectangle's side 2: ")) print('The total circumference is %.2f' % (2 * (dimension_1 + dimension_2))) print('The surface area is %.2f' % (dimension_1 * dimension_2)) return # circle function will take the required radius from user, # and check if it is greater than zero or not, # and which then prints the circumference # and area of the shape to two decimal places. def circle(): radius = float(input("Enter the circle's radius: ")) print('The total circumference is %.2f' % (2 * pi * radius)) print('The surface area is %.2f' % (pi * (radius**2))) return def menu(): while True: answer = input("Enter the pattern's first letter, q stops this (s/r/q): ") if answer == "s": square() # call square function elif answer == "r": rectangle() # call rectangle function elif answer == "c": circle() # call circle function elif answer == "q": return # return to main function else: print("Incorrect entry, try again!") print() # Empty row for the sake of readability def main(): menu() print("Goodbye!") main()
import math import numpy as np def is_multiple(x, k): """ Tests if x is a multiple of k. Parameters ---------- x : int or float k : int or float Returns ------- boolean True if n is a multiple of k. Raises ------ ZeroDivisionError if k is 0 or 0.0 TypeError if x or k are strings or None Examples -------- >>> is_multiple(9,3) True >>> is_multiple(9,2) False """ return x % k == 0 # True if n is a multiple of k def sum_of_all_multiples(divisors=[3, 5], below = 10): """ Find the sum of all the multiples of k or j that are below some number n. Parameters ---------- divisors : list list of [int, int] below : int or float integer or float that all multiples must be below in order to be summed Returns ------- sum_of_multiples : int the sum of multiples of the divisors that are less than the number below Raises ------ TypeError if below is a string or None Examples -------- >>> sum_of_all_multiples(divisors = [3,5], below= 10) 23 >>> sum_of_all_multiples(divisors = [3,5], below= 1000) 233168 """ # Assert enforce that divisors is a list of positive integers assert(isinstance(divisors, list)), "divisors must be a list" assert(np.all([isinstance(d, int) for d in divisors])) , "divisors must be a list of integers" assert(np.all([d > 0 for d in divisors])) , "divisors must be a list of positive integers" # New Method can accommodate any number of divisors, whereas previous method # was rigid, requiring exactly two divisors all_multiples = [] for d in divisors: all_multiples = all_multiples + [i for i in range(1, math.ceil(below)) if is_multiple(i, d)] sum_of_multiples = sum(list(set(all_multiples))) return sum_of_multiples if __name__ == "__main__": assert(sum_of_all_multiples(divisors = [3,5], below = 10) == 23) import doctest doctest.testmod()
def is_leap_year( year ): if year%4 == 0 and year%100 != 0: return True elif year%100 == 0 and year%400 == 0: return True else: return False def find_leap_years(start_year,end_year): years=[] for i in range( start_year, end_year+1 ): if is_leap_year(i): years.append((i,1)) else: years.append((i,0)) return years def turn_years_to_days( years_array ): days=0 for i in years_array: if i[1] == 0: days+=365 else: days+=366 days_array=[0]*days return days_array def mark_day(day_start_index,days_array): for i in range( 0 , len(days_array)+1 , 7 ): days_array[i]+=1 #assumes the first month start is at index 0 def mark_month_start(years,days_array): index=0 days_array[index]+=2 for y in years: if y[1] == 1: days=[31,29,31,30,31,30,31,31,30,31,30,31] else: days=[31,28,31,30,31,30,31,31,30,31,30,31] for d in days: index+=d try: days_array[index]+=2 except: return def main(): #find what day jan1 1901 is #1900 is clearly not a leap year years=find_leap_years(1900,1900) days=turn_years_to_days(years) mark_day(0,days) #days.reverse() ##funny old thing BUT marking days in a year is mirrored from the middle! #print days.index(1) #it's 0 i.e. monday #new years day in 1901 is therefore tuesday #so sunday is (+5) ([tuesday[0]]wednesday[1],thursday[2],friday[3],saturday[4],Sunday[5]) #create 1901->Dec 2000 days full_years=find_leap_years(1901,2000) full_days=turn_years_to_days(full_years) mark_day(5,full_days) mark_month_start(full_years,full_days) print full_days.count(3) if __name__=="__main__": main()
def collatz(start,print_numbers): if print_numbers: print(start) total=start chain_length=1 while total != 1: if total%2 == 0: total/=2 else: total=total*3+1 if print_numbers: print(total) chain_length+=1 if print_numbers: print(("Chain Length: {}").format(chain_length)) return chain_length if __name__=="__main__": collatz(300,True);
import math as math def nCr( n , r ): if n < r: return 0 # nCr: n!/((n-r)!r!) divisor = math.factorial(n) print "Divisor: "+str(divisor) denominator = math.factorial(n-r)*math.factorial(r) print "Denominator: "+str(denominator) return divisor/denominator def nPr( n , r ): # nPr: n!/(n-r)! divisor = math.factorial(n) print "Divisor: "+str(divisor) denominator = math.factorial(n-r) print "Denominator: "+str(denominator) return divisor/denominator if __name__ == "__main__": n=9 r=4 print "n: {} r: {}".format(n,r) print "nCr: "+str(nCr(n,r)) print "nPr: "+str(nPr(n,r))
""" Name: Vu Le Nguyen Phuong Date:18/01/2020 Brief Project Description: My small project to store the list of movies. I have add extra functionality including sort by ascending and descending order and search movie from the list :) GitHub URL:https://github.com/phuong16122000/Movie-To-WatchA2 """ # TODO: Create your main program in this file, using the MoviesToWatchApp class from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.properties import StringProperty from kivy.properties import ListProperty from kivy.uix.button import Button from movie import Movie from moviecollection import MovieCollection from string import capwords class MoviesToWatchApp(App): """Class for GUI movie app""" # Initiate string and list properties sort_by = StringProperty() category = ListProperty() order = ListProperty() current_order = StringProperty() def __init__(self, **kwargs): """Constructor that initiate my collection and movie list""" super(MoviesToWatchApp, self).__init__(**kwargs) self.my_collection = MovieCollection() # Create another list to not TOUCH the original list, in case for back-up or error self.movie_to_show = [] def build(self): """Build from the root kv file""" Window.size = (1000, 800) self.title = "Movie To Watch 2.0 by Van Phuong Nguyen" self.root = Builder.load_file('app.kv') # Set category list self.category = ['Title', 'Year', 'Category', 'Unwatch'] # Default sorting option self.sort_by = self.category[0] # Set order list self.order = ['Ascending Order', 'Descending Order'] # Set default order self.current_order = self.order[0] return self.root def on_start(self): """Start when program start""" self.my_collection.load_movies('movies.csv') # Separate movie list to not change to original list self.movie_to_show = self.my_collection.movies # Make sure the height is such that there is something to scroll. self.root.ids.movie_list.bind(minimum_height=self.root.ids.movie_list.setter('height')) # Show welcome message self.root.ids.message.text = 'Let\'s watch some movies :)' # Load movies self.load_movies() # Show watch and unwatch count self.count_watch() def on_stop(self): """Close program and save movies to the file""" self.my_collection.save_movies('movies.csv') def count_watch(self): """Count movie based on watch and unwatch""" self.root.ids.watch_count.text = 'To watch: {}. Watched: {}'.format(self.my_collection.count_unwatch(), self.my_collection.count_watch()) def sort_movies(self, key): """Sort movie based on key""" # Change current sort_by key based on the key from the sort spinner self.sort_by = key # Load movies based on key provided self.load_movies() def handle_order(self, element): """Sort movie based on order""" # Change current order for loading self.current_order = element # Load movie based on current order self.load_movies() def handle_add_movie(self, title, year, category): """Add movie to movie list""" # Only add movie when title, year, category are provided if title and year and category: # Make sure that title input is correct title_check = self.handle_input(title, is_title=True) # Make sure that category is on category list category_check = self.handle_input(category, is_category=True) # Make sure that year is a number >= 0 year_check = self.handle_input(year, is_year=True) if year_check and category_check and title_check: # Make the input prettier clean_title = ' '.join(title.split()) pretty_title = capwords(clean_title) pretty_category = capwords(category) # Check if movie is already exist if self.check_exist(title_check, year_check, category_check): self.show_popup_message('The movie is already exist') else: # Add movie to list, then reload movie list self.my_collection.add_movie(Movie(title_check, year_check, category_check)) self.load_movies() self.show_popup_message('{} have been add to movie list'.format(pretty_title)) self.handle_clear_button(is_add=True) else: # Show error if any field blank self.show_popup_message('All fields are required') def load_movies(self): """Load movie to the GUI movie list""" # First clear the current movie on list self.root.ids.movie_list.clear_widgets() # Check the current order desc = self.current_order == 'Descending Order' # Add movies based on current sort_by and order to movie to show list self.movie_to_show = self.my_collection.sort_movies(self.sort_by, desc) # Add buttons based on movie list for index, movie in enumerate(self.movie_to_show): watch_mark = 'watched' if movie.is_watched else '' btn = Button(text='{} ({} from {}) {}'.format(movie.title, movie.category, movie.year, watch_mark), size_hint_y=None, height=30) # Save movie object to btn btn.movie = movie # If pressed, execute handle_watch_movie function btn.bind(on_press=self.handle_watch_movie) # If movie is watched, change background color if watch_mark: btn.background_color = (1, 0.5, 0.5, 1) # Add btn to movie_list id self.root.ids.movie_list.add_widget(btn) def handle_watch_movie(self, instance): """Handle watch movie if user click on movie""" # Movie object is saved to btn.movie >> instance.movie current_movie = instance.movie # Toggle between watch/unwatch current_movie.is_watched = not current_movie.is_watched # Load movie to the GUI list for immediate sorting self.load_movies() # Show message and reload the count watch watch_mark = 'watched' if current_movie.is_watched else 'unwatched' self.root.ids.message.text = 'You have {} {}'.format(watch_mark, current_movie.title) self.count_watch() def show_popup_message(self, text): """Handle show popup message""" self.root.ids.popup_message.text = text self.root.ids.popup.open() def handle_close_popup(self): """Close the popup""" self.root.ids.popup_message.text = '' self.root.ids.popup.dismiss() def handle_clear_button(self, is_add=False, is_search=False): """Clear input when pressed""" # If is_add, clear the add movie input if is_add: self.root.ids.title.text = '' self.root.ids.year.text = '' self.root.ids.category.text = '' # If is_search, clear the search input elif is_search: self.root.ids.title_search.text = '' self.root.ids.year_search.text = '' self.root.ids.category_search.text = '' self.root.ids.watch_search.text = '' # Else clear all else: self.root.ids.title.text = '' self.root.ids.year.text = '' self.root.ids.category.text = '' self.root.ids.title_search.text = '' self.root.ids.year_search.text = '' self.root.ids.category_search.text = '' self.root.ids.watch_search.text = '' def handle_search(self, title, year, category, watch): """Search for movie in list""" # Only search when at least on field is provided if title or category or watch or year: # Check for valid year, category and title title_check = self.handle_input(title, is_title=True, blank=True) year_check = self.handle_input(year, is_year=True, blank=True) category_check = self.handle_input(category, is_category=True, blank=True) watch_check = self.handle_input(watch, is_watch=True, blank=True) # If all are valid, then search if title_check and year_check and category_check and watch_check: # If is_watched is provided, change to bool, else None is_watched = None if watch: is_watched = watch.lower() == 'y' # Search movie method self.my_collection.search_movies(title.strip(), year, category, is_watched) # If found, show movie count and display in GUI movie list if self.my_collection.search_list: self.movie_to_show = self.my_collection.search_list self.show_popup_message('We have found: {} movies'.format(len(self.movie_to_show))) self.load_movies() # Clear the input when completed self.handle_clear_button(is_search=True) # If no movie found, show error message else: self.show_popup_message('No movie found!') else: # If no field is fill in, show error message self.show_popup_message('Your must at least fill in one field') def handle_clear_search(self): """Clear the search and return the original list""" # Set search list to empty self.my_collection.search_list = [] self.handle_clear_button(is_search=True) self.load_movies() def check_exist(self, title, year, category): """Check if movie is existed""" # Filter method based on title, year, category def find_duplicate(movie): filter_title = title.lower() == movie.title.lower() filter_year = int(movie.year) == int(year) filter_category = movie.category.lower() == category.lower() return filter_title and filter_year and filter_category return list(filter(find_duplicate, self.my_collection.movies)) def handle_input(self, input_data, is_title=False, is_year=False, is_category=False, is_watch=False, blank=False): """Handle input data""" # Check if year > 0 and is a number if blank and not input_data: return True else: if is_year: try: year = int(input_data) if year < 0: raise ValueError() return input_data.strip() except ValueError: self.show_popup_message('Your year must be a number and greater than 0') # Check if input in category list elif is_category: # Check if category is in the category list if input_data.lower().strip() not in ['action', 'comedy', 'documentary', 'drama', 'fantasy', 'thriller']: self.show_popup_message('Please enter a correct category ' '(Action, Comedy, Documentary, Drama, Fantasy, Thriller)') else: return input_data.strip() # Check if valid watch elif is_watch: if input_data.lower() not in ['y', 'n']: self.show_popup_message('Your watch field must be Y or N') else: return True # Check if title is blank elif not input_data.strip() and is_title: self.show_popup_message('Your title must not be blank') else: return input_data.strip() if __name__ == '__main__': # Execute GUI program MoviesToWatchApp().run()
#!/usr/bin/env python """ DESCRIPTION This script is for reorganizing and sorting given addresses and postal codes and sorting the strings into a more visual appealing format. AUTHOR Travis Vanos <Travis.vanos@gmail.com> LICENSE This script is in the public domain, free from copyrights or restrictions. The script is for EDUCATIONAL PURPOSES ONLY VERSION Version: 1.1 """ #Libraries required for execution import sys, os import re import shutil #Folder for Submission folder_name = (r'C:\temp\Tvanos9307D1\d1ProcData') #If path does not exist the folder is created proper structure if not os.path.exists(folder_name): os.makedirs(folder_name) #Else folder structure exists so deletes folder tree and recreate contents else: shutil.rmtree(folder_name) os.makedirs(folder_name) #Copying the data from d1RawListOfFarms.txt into new text file for reading in C:\temp\Tvanos9307D1\d1ProcData folder shutil.copyfile(r'C:\temp\d1RawListOfFarms.txt', folder_name + r'\d1RawListOfFarms.txt') #Opens created text file, populated with data, for reading farm_data = open(folder_name + r'\d1RawListOfFarms.txt', 'r') #Creates a text file ready to populate with final output of values f = open(folder_name + r'\Final_List_Of_Farms.txt', 'w') #String list to write headers to output file header_list = ["FarmID\t", "Street #\t", "Street\t", "Suffix\t", "Dir\t", "City\t", "Province\t", "Postal Code\t\n"] #For Loop to write header_list to output file for item in header_list: f.write(item) f.close() #Logical counter for number of records in d1RawListOfFarms.txt raw data farm_ID = 0 #Sorted_data will be final list of sorted lines sorted_data = [] #Loops through each line of the input file and preforms search for each line for eachline in farm_data: #Defines the regex search pattern used for string check & Validation province_check = re.search ("\s\w\w\s", eachline) #If statement for function only if pattern is found if province_check is not None: #Saves first result found of regex check x = province_check.group(0) if x == " AB " or x == " BC " or x == " MB " or x == " NB " or x == " NL " or x == " NS " or x == " NT " or x == " NU " or x == " ON " or x == " PE " or x == " QC " or x == " SK " or x == " YT ": #Province saved as first item found in pattern check is saved as province province = province_check.group(0) #strips whitespace and commas province = province[1:-1] #If unmatched set to Null else: province = '' #Defines the regex search pattern used for string check & Validation postal_code_check = re.search("[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]", eachline , re.IGNORECASE ) #If statement for function only if pattern is found if postal_code_check is not None: #Saves first result found of regex check postal_code = postal_code_check.group(0) #If unmatched set to Null else: postal_code = '' #Defines the regex search pattern used for string check & Validation address_check = re.search("\s\d*\s\w*\s\w*\s*\w*,", eachline , re.IGNORECASE ) #If statement for function only if pattern is found if address_check is not None: #Saves first result found of regex check address = address_check.group(0) #Strips commas/whitespace matched in search address = address[1:-1] #If unmatched set to Null else: address = '' #Defines the regex search pattern used for string check & Validation city_check = re.search(",\s*\S*(\.?\s*)?\w*," , eachline , re.IGNORECASE | re.DOTALL) #If statement for function only if pattern is found if city_check is not None: #Saves first result found of regex check city = city_check.group(0) city = city[2:-1] #If unmatched set to Null else: city = '' #Sorted data into list of results of regex searches sorted_data = [farm_ID, address, city, province, postal_code] #Splits address into a list of elements seperated on whitespace characters address = sorted_data[1].split() #If address list has three elements and no directional value #Concatenate Roads that have spaces if farm_ID >= 1 and len(address) == 4 and str(address[-1]) != "N" and str(address[-1]) != "W" and str(address[-1]) != "E" and str(address[-1]) != "S": address[1] = address[1] + ' ' + address[2] address.pop(2) if len(address) == 3: #Adding null value for lack of direction address.append('') #Removes element from sorted_data and reinserts new address list with [4] elements sorted_data.pop(1) #Logical counter for loop iterations i = 0 #Sperate address string for item in address: i += 1 #Inserts list elements in the proper order from address list sorted_data.insert(i, item) print sorted_data #Does not write first line of input file if farm_ID >= 1: #Open file for appending f = open(folder_name + r'\Final_List_Of_Farms.txt', 'a') #Write each element to file appending a tab character to each element for item in sorted_data: f.write(str(item)) f.write('\t') f.write('\n') #Increase Farm_ID by one to for counting farm identifies in output file farm_ID += 1
# tic-tac-toe game = [[0, 0, 0], [0, 0, 0], [0, 0, 0],] def game_board(player: int=0, row: int=0, column: int=0, just_display: bool=False): print(" a b c") if not just_display: game[row][column] = player for count, row in enumerate(game): print(count, row) game_board(just_display=True) game_board(player=1, row=1, column=1)
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: abekthink from python3 import ListNode class Solution: # 1st version: # def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # p1, p2 = l1, l2 # head, tail = None, None # carry = 0 # while p1 or p2: # if p1: # num1 = p1.val # p1 = p1.next # else: # num1 = 0 # p1 = None # # if p2: # num2 = p2.val # p2 = p2.next # else: # num2 = 0 # p2 = None # # num3 = num1 + num2 + carry # if num3 >= 10: # carry = 1 # num3 = num3 - 10 # else: # carry = 0 # # node = ListNode(num3) # if head is None: # head = node # tail = node # else: # tail.next = node # tail = tail.next # if carry > 0: # tail.next = ListNode(carry) # return head # 2nd version: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = tail = ListNode(0) carry = 0 while l1 or l2: num = carry if l1: num += l1.val l1 = l1.next if l2: num += l2.val l2 = l2.next tail.next = ListNode(num % 10) tail = tail.next carry = num // 10 if carry > 0: tail.next = ListNode(carry) return head.next
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: abekthink from python3 import List class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ length = len(nums) for i in range(length - 1, 0, -1): if nums[i] > nums[i - 1]: j = i + 1 while j < length and nums[j] > nums[i - 1]: j += 1 nums[i - 1], nums[j - 1] = nums[j - 1], nums[i - 1] nums[i:] = nums[length - 1:i - 1:-1] return nums.reverse() def main(): s = Solution() nums = [1, 2, 3] print(s.nextPermutation(nums), nums) nums = [3, 2, 1] print(s.nextPermutation(nums), nums) nums = [1, 1, 5] print(s.nextPermutation(nums), nums) nums = [1, 3, 2] print(s.nextPermutation(nums), nums) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: abekthink class Solution: # def strStr(self, haystack: str, needle: str) -> int: # i, m, n = 0, len(haystack), len(needle) # while i < m - n + 1: # j = 0 # while j < n and haystack[i + j] == needle[j]: # j += 1 # if j == n: # return i # i += 1 # return -1 if needle else 0 def strStr(self, haystack: str, needle: str) -> int: m, n = len(haystack), len(needle) for i in range(m - n + 1): if haystack[i:i+n] == needle: return i return -1 if needle else 0 def main(): s = Solution() print(s.strStr("hello", "ll")) print(s.strStr("aaaaa", "bba")) print(s.strStr("aaa", "aaaa")) print(s.strStr("hello", "")) print(s.strStr("", "ab")) if __name__ == '__main__': main()
import time import sys from random import randint # Delay printing def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.1) class Pokemon: def __init__(self, name: str, poke_type: str, moves: list, health=100, level=1): self.name = name self.type = poke_type self.moves = moves self.level = level self.health = health def show(self): print("Name: ", self.name) print("Type: ", self.type) print('Moves:') for i, x in enumerate(self.moves): print(f"{i}.", x) print("Level: ", self.level) print("Health: ", self.health) def show_moves(self): print('Moves:') for i, x in enumerate(self.moves): print(f"{i + 1}.", x) def choose_move(self): choice = int(input('Choose move\n')) for i in range(len(self.moves)): if choice == i + 1: print(f"{self.name} used {self.moves[i]}") def inflict_damage(self): damage = randint(1, 10) self.health = self.health - damage def attack(self): line = f"{self.name} turn to attack\n" delay_print(line) self.show_moves() self.choose_move() def show_health(self): line1 = f"{self.name} Health: {self.health}\n" delay_print(line1) def fight(self, pokemon2): print(f'Battle between {self.name} and {pokemon2.name}') while True: if self.health > 0 and pokemon2.health > 0: self.attack() pokemon2.inflict_damage() self.show_health() pokemon2.show_health() time.sleep(3) pokemon2.attack() self.inflict_damage() self.show_health() pokemon2.show_health() elif self.health <= 0: line3 = f"{pokemon2.name} is the winner!!!" delay_print(line3) break elif pokemon2.health <= 0: line4 = f"{self.name} is the winner!!!" delay_print(line4) break pikachu = Pokemon(name='Pikachu', poke_type='Electric', moves=['Quick Attack', 'Thundershock', 'Thunderbolt', 'Thunderpunch'], ) squirtle = Pokemon(name='Squirtle', poke_type='Water', moves=['Water Gun', 'Skull Bash', 'Bubble', 'Withdraw']) pikachu.fight(pokemon2=squirtle)
from flask import Flask, render_template, request#, redirect, url_for import sqlite3 app = Flask(__name__) #x=0 #conn = sqlite3.connect("blog.db") #p ="create table posts(post_id integer, post_title text, post_author text, post_content text);" #comm = "create table comments(comment_id integer, comment_content text, comment_author text,p_id integer);" #c = conn.cursor() #c.execute(p) #c.execute(comm) #conn.commit(); @app.route("/") def home(): newpost = request.args.get ("new_post", None) title = request.args.get ("title", None) author = request.args.get ("author", None) post = request.args.get ("post", None) conn = sqlite3.connect("blog.db") c = conn.cursor() if newpost == "Post": q = "Insert Into posts Values('" + title + "','" + author + "','" + post + "');" c.execute(q) #x = x + 1 #link = '/'+ title + '' s = "Select title From posts" t = "Select author From posts" u = "Select content From posts" title_list = [] author_list = [] post_list = [] titles = c.execute(s) title_list = [(str(x)[3:])[:-3] for x in titles] authors= c.execute(t) author_list = [(str(x)[3:])[:-3] for x in authors] posts= c.execute(u) post_list = [(str(x)[3:])[:-3] for x in posts] conn.commit() print title_list print author_list print post_list return render_template ("index.html", #ignore link #link = link, title_list = title_list, author_list = author_list, post_list = post_list) @app.route("/<title>") ##check if title is unique def post(title): t = title.replace ("+", " ") nc = request.args.get ("new_comment", None) commentor = request.args.get ("commentor", None) comment = request.args.get ("comment", None) print commentor print comment conn = sqlite3.connect("blog.db") c = conn.cursor() if nc == "Post": q = "Insert Into comments Values('" + t + "','" + commentor + "','" + comment + "');" c.execute(q) commentor_list = [] comment_list = [] a = "select author from posts where title = '" + t + "'" author = c.execute (a) authorstr = author= [(str(x)[3:])[:-3] for x in author] print authorstr p = "select content from posts where title = '" + t + "'" post = c.execute (p) poststr = [(str(x)[3:])[:-3] for x in post] print poststr x = "select commentor from comments where title == '" + t + "';" y = "select comment from comments where title == '" + t + "';" commentors = c.execute (x) commentor_list = [(str(x)[3:])[:-3] for x in commentors] comments = c.execute (y) comment_list = [(str(x)[3:])[:-3] for x in comments] conn.commit() print commentor_list print comment_list return render_template ("post.html", title = t, author = authorstr[0], post = poststr[0], commentor_list = commentor_list, comment_list = comment_list) if __name__ == "__main__": app.debug = True app.run(host="0.0.0.0",port=8888)
# -*- coding: utf-8 -*- """ Created on Sat Jan 30 19:49:49 2021 @author: Kinga Kalinowska """ import random class Card: def __init__(self,CardSuit,CardValue): self.Card_suit=CardSuit self.Card_value=CardValue def show(self): print("{} of {}".format(self.Card_value,self.Card_suit)) def get_card_value(self): return self.Card_value def get_card_suit(self): return self.Card_suit class CardDeck(Card): def __init__(self): #Card.__init__(self) self.cards=[] self.build() self.shuffle() def build(self): for s in ["Spades","Clubs","Diamonds","Hearts"]: for v in [ '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13','14']: self.cards.append(Card(s,v)) def show(self): for c in self.cards: c.show() def shuffle(self): random.shuffle(self.cards) def get_cards(self): return self.cards class War_Game(CardDeck): def __init__(self): CardDeck.__init__(self) cards=self.get_cards() number_of_cards=int(len(cards)/2) self.a_cards=cards[:number_of_cards] self.b_cards=cards[number_of_cards:] def play_war_game(self): round=1 while self.a_cards and self.b_cards: a_card=self.a_cards.pop() b_card=self.b_cards.pop() card_on_stash=[] while a_card.get_card_value()==b_card.get_card_value(): if len(self.a_cards)>=2 and len(self.b_cards)>=2: card_on_stash= card_on_stash + [a_card,b_card,self.a_cards.pop(),self.b_cards.pop()] a_card = self.a_cards.pop() b_card=self.b_cards.pop() elif len(self.b_cards)==0: card_on_stash= card_on_stash + [a_card,b_card,self.a_cards.pop(),self.a_cards.pop()] a_card = self.a_cards.pop() b_card=self.a_cards.pop() elif len(self.a_cards)==0: card_on_stash= card_on_stash + [a_card,b_card,self.b_cards.pop(),self.b_cards.pop()] a_card = self.b_cards.pop() b_card=self.b_cards.pop() elif len(self.b_cards)==1: card_on_stash= card_on_stash + [a_card,b_card,self.a_cards.pop(),self.b_cards.pop()] a_card = self.a_cards.pop() b_card=self.a_cards.pop() elif len(self.a_cards)==1: card_on_stash= card_on_stash + [a_card,b_card,self.a_cards.pop(),self.b_cards.pop()] a_card = self.b_cards.pop() b_card=self.b_cards.pop() if a_card.get_card_value() > b_card.get_card_value(): self.a_cards=card_on_stash + [a_card] + [b_card] +self.a_cards elif b_card.get_card_value() > a_card.get_card_value(): self.b_cards=card_on_stash + [a_card] + [b_card]+self.b_cards print("round: %s, a_cards: %s, b_cards: %s" % (round, len(self.a_cards), len(self.b_cards))) round += 1 Once_again='' if round>10000: print("Too many rounds, shuffling cards and playing one more time") Once_again = input('Do you want to play again (Y/N): ').upper() if Once_again == 'Y': self.__init__() self.play_war_game() else: break if Once_again == 'N': break def main(): deck= CardDeck() deck.show() war_game=War_Game() war_game.play_war_game() main()
# -*- coding: utf-8 -*- """ Created on Wed Jan 27 20:22:18 2021 @author: Komputer """ class FractionCheck(Exception): def __init__(self,message="Nominator and denominator should be integers"): self.message=message super().__init__(self.message) class Fraction: def __init__(self,top,bottom): if bottom<0 and top>0: self.num = - top self.den = - bottom else: self.num = top self.den = bottom if type(self.num)!=int or type(self.den)!=int: raise FractionCheck() def getNum(self): return self.num def getDen(self): return self.den def show(self): print(self.num,"/",self.den) #In Python, all classes have a set of standard methods. #__str__ is the method to convert an object into string # def __str__(self): # return str(self.num)+"/"+str(self.den) def __repr__(self): return repr(self.num)+"/"+repr(self.den) #overloading of operator + def __add__(self,otherfraction): if type(otherfraction) in [int,float]: return otherfraction+self else: newnum = self.num*otherfraction.den + self.den*otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum,newden) return Fraction(newnum//common,newden//common) # a function to obtain deep equality #normally by default we have shallow equality (two objects of the class are eqaul #if they are references to the same object) def __eq__(self, other): firstnum = self.num * other.den secondnum = other.num * self.den return firstnum == secondnum #multiplication of two objects def __mul__(self,otherfraction): new_num=self.num*otherfraction.num new_den = self.den*otherfraction.den common=gcd(new_num,new_den) return(Fraction(new_num//common,new_den//common)) def __sub__(self,otherfraction): newnum = self.num*otherfraction.den - self.den*otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum,newden) return Fraction(newnum//common,newden//common) def __truediv__(self,otherfraction): newnum=self.num*otherfraction.den newden = self.den*otherfraction.num common = gcd(newnum,newden) return Fraction(newnum//common,newden//common) # // - floor division def __gt__(self,otherfraction): newnum1=self.num*otherfraction.den newnum2=self.den*otherfraction.num if newnum1>newnum2: return True else: return False def __ge__(self,otherfraction): newnum1=self.num*otherfraction.den newnum2=self.den*otherfraction.num if newnum1>=newnum2: return True else: return False def __lt__(self,otherfraction): newnum1=self.num*otherfraction.den newnum2=self.den*otherfraction.num if newnum1<newnum2: return True else: return False def __le__(self,otherfraction): newnum1=self.num*otherfraction.den newnum2=self.den*otherfraction.num if newnum1<=newnum2: return True else: return False def __ne__(self,otherfraction): newnum1=self.num*otherfraction.den newnum2=self.den*otherfraction.num if newnum1!=newnum2: return True else: return False # adding number and instance of the fraction class def __radd__(self,other): return Fraction(int(other)*self.den + self.num, self.den) # overloading of self+=number def __iadd__(self,number): return number + self myfraction = Fraction(3,5) myfraction.show() print(myfraction) f1=Fraction(1,-5) f2=Fraction(1,4) f3=f1+f2 print(f3) f1>=f2 #Greatest Common Divisor - Euclid's Algorith def gcd(m,n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n print(gcd(20,10)) print(f1==f2) f3=f1*f2 print(f3) # noninstance + instance f=Fraction(1,2) a=2 b=a+f print(b) c=f+a print(c) f+=2 print(f) #################################################### #Inheritance class LogicGate: def __init__(self,n): self.label = n self.output = None def getLabel(self): return self.label # performGateLogic is a virtual method. This is a method that will use code that does't exist yet. def getOutput(self): self.output = self.performGateLogic() return self.output class BinaryGate(LogicGate): def __init__(self,n): LogicGate.__init__(self,n) self.pinA = None self.pinB = None def getPinA(self): if self.pinA == None: return int(input("Enter Pin A input for gate " + self.getLabel()+"-->")) else: return self.pinA.getFrom().getOutput() def getPinB(self): if self.pinB == None: return int(input("Enter Pin B input for gate " + self.getLabel()+"-->")) else: return self.pinB.getFrom().getOutput() def setNextPin(self,source): if self.pinA == None: self.pinA = source else: if self.pinB == None: self.pinB = source else: raise RuntimeError("Error: NO EMPTY PINS") class UnaryGate(LogicGate): # calling a constructor of parent class def __init__(self,n): LogicGate.__init__(self,n) self.pin = None def getPin(self): if self.pin == None: return int(input("Enter Pin input for gate "+self.getLabel()+"-->")) else: return self.pin.getFrom().getOutput() def setNextPin(self,source): if self.pin == None: self.pin = source else: print("Cannot Connect: NO EMPTY PINS on this gate") class AndGate(BinaryGate): #Python also has a function called super which can be used in place of explicitly naming the parent class. #Useful when a class inherits from more than one parent class def __init__(self,n): BinaryGate.__init__(self,n) def performGateLogic(self): a = self.getPinA() b = self.getPinB() if a==1 and b==1: return 1 else: return 0 class OrGate(BinaryGate): #Python also has a function called super which can be used in place of explicitly naming the parent class. #Useful when a class inherits from more than one parent class def __init__(self,n): super(OrGate,self).__init__(n) def performGateLogic(self): a = self.getPinA() b = self.getPinB() if a==1 or b==1: return 1 else: return 0 class NotGate(UnaryGate): def __init__(self,n): super(NotGate,self).__init__(n) def performGateLogic(self): if self.getPin(): return 0 else: return 1 # Creating circuit (connecting gates together) #To do this we implement a new class called Connector #It is called the HAS-A Relationship. #Connector HAS-A LogicGate meaning that connectors will have instances of the LogicGate class within them #but are not part of the hierarchy. #HAS-A relationship = no inheritance class Connector: def __init__(self, fgate, tgate): self.fromgate = fgate self.togate = tgate tgate.setNextPin(self) def getFrom(self): return self.fromgate def getTo(self): return self.togate a1 = AndGate("1") a2 = AndGate("2") a3 = OrGate("3") a4 = NotGate("4") #result from a1 goes to a3 as first parameter c1=Connector(a1,a3) #result from a2 goes to a3 as second parameter c2 = Connector(a2,a3) #result from a3 goes to a4 as parameter c3 = Connector(a3,a4) a3.getOutput() a4.getOutput() a2.getOutput()
class Hund: # Name in großge. CamelCase species = 'Canis lupus familiaris' # Klassenattri. zaehler = 0 # soll mitzählen wieviele Objekte gerade leben @classmethod def get_anzahl_hunde(cls): return cls.zaehler def __init__(self, name: str, age: str): # Zum Initialisieren self.name = name # Instanzattribut self.age = age Hund.zaehler += 1 def __del__(self): Hund.zaehler -= 1 def gib_laut(self): print(f'{self.name} bellt') def __repr__(self): return f'Hund(name={self.name}, age={self.age})' def __str__(self): return f'{self.name} ist ein Hund und ist {self.age} Jahre alt.' if __name__ == '__main__': rex = Hund("Kommissar Rex", 14) lassie = Hund("Lassie", 10) lassie.gib_laut() print(lassie.__str__()) print(lassie.__repr__()) print(lassie) # print verwendet __str__ Funktion wenn vorhanden, sonst __repr__ # lassie.gib_laut() wird intern eigentlich # Hund.gib_laut(lassie) --> niemand schreibt es so # for element in [rex, lassie]: # print(element) print(Hund.get_anzahl_hunde()) del lassie # ich brauch es nicht mehr print(Hund.get_anzahl_hunde())
class Duck: def quack(self): print("quack quack") def fly(self): print("Flies through the sky") class WoodDuck: def quack(self): print("*silence*") def fly(self): print("Gets thrown") class Human: def quack(self): print("*awkward silence* *quack quack*") def fly(self): print("*ouch*") if __name__ == '__main__': d = Duck() w = WoodDuck() h = Human() # check presence of method - should not do it normally but this is the preferred way print(hasattr(h, 'fly')) l = [d, w, h] # duck typing for duckling in l: duckling.quack() duckling.fly() print("---")
class Pila(): def __init__ (self): self.cima = None self.contador = 0 def push(self, comida): snack = comida if (self.cima == None): self.cima = snack self.contador += 1 else: snack.abajo = self.cima self.cima = snack self.contador += 1 def pop(self): if (self.cima == None): self.cima = None else: temp = self.cima nuevo = self.cima.abajo self.cima = nuevo temp.abajo = None self.contador -= 1 return temp def peek(self): return self.cima
def bitError(str1, str2): """ Compute the bit error rate between two strings. parameters: str1 (string): First string to be compared str2 (string): Second string to be compared return value: (int) the bit error rate of two strings in percent """ lenStr1 = len(str1) lenStr2 = len(str2) if lenStr1 != lenStr2: print("Inputs are of unequal length.") return else: count = 0 for i in range(lenStr1): if str1[i] != str2[i]: count += 1 return str((count/lenStr1) * 100) + "%"
x = 5 y = 7 z = 10 if x%2 != 0: largest = x if y%2 != 0: if y > largest: largest = y if z%2 != 0: if z%2 != 0: largest = z print (largest)
class Exitgate: """CLASS FOR THE EXIT GATE. WHEN LEMMINGS HIT THE EXITGATE, THEY WILL DISSAPEAR FROM THE GAME AND ADD ONE SCORE UP ON THE "SAVED" SCOREBOARD """ def __init__ (self, myx, myy): #position attributes self.exitgate_x = myx self.exitgate_y = myy @property def exitgate_x(self): return self.__exitgate_x @exitgate_x.setter def exitgate_x(self, myx): self.__exitgate_x = myx @property def exitgate_y(self): return self.__exitgate_y @exitgate_y.setter def exitgate_y(self, myy): self.__exitgate_y = myy
class Cell: """ THIS CLASS IS MADE TO CREATE A CELL OBJECT, IN ORDER TO CREATE THE BOARD WHERE THE GAME WILL RUN. IT HAS A X AND Y COORDINATE AND IT IS NOT VISIBLE IN THE GAME, ITS JUST A POSITIONAL REPRESENTATION OF ALL THE THINGS CONTAINED ON THE BOARD""" def __init__(self, x, y): # IMPORTANT COMMENT: THIS IS APPROACHED IN POSITIONS OF A MATRIX, NOT IN PIXELS #position attributes self.cellx=x self.celly=y # VERY IMPORTANT ATTRIBUTE. This will allow us to "see" whats inside a cell # on the board, so we can interact with other parts of the program related # to lemming collisions, tools placements... self.cellclass = None @property def cellx(self): return self.__cellx @cellx.setter def cellx(self, cellx): self.__cellx = cellx @property def celly(self): return self.__celly @celly.setter def celly(self, celly): self.__celly = celly @property def cellclass(self): return self.__cellclass @cellclass.setter def cellclass(self, cellclass): self.__cellclass = cellclass
import getpass import psycopg2 import time def newuser(): conn = psycopg2.connect("dbname=abc user=postgres password=postgres") cursor = conn.cursor() username = input("Enter Your Name : ") cursor.execute("SELECT username from test WHERE username=%s",(username,)) row = cursor.fetchall() if len(row)>0: print("Username exist") else: pin = getpass.getpass("Enter 4 Digit Pin for ATM : ") if len(pin)!=4: print("Pleasse Proivde Correct Pin") else: cnfpin = getpass.getpass("Enter Pin Again : ") if pin == cnfpin : balance = int(input("Enter Balance : ")) else: print("Pin doest not match....Register Again !!") cursor.execute("INSERT INTO test (username,pin,balance) VALUES (%s,%s,%s)",(username,pin,balance)) conn.commit() cursor.execute("SELECT username,balance,accno from test where username=%s",(username,)) row = cursor.fetchall() for r in row: print("Welcome Mr.",r[0],) print("Your Account No is :",r[2],) print("Your Balance is :",r[1],) print("Select Service : ") b = int(input("1-Withdraw Money 2-Get Balance 3-Add Cash :")) if b == 1: transaction = "Withdrawl" date = time.strftime('%Y-%m-%d %H:%M:%S') money = int(input("Enter Amount to Withdraw in multiple of 100 or 1000 only : ")) userpin = getpass.getpass("Enter Pin : ") if userpin == pin: if money <= balance : if money%100==0 and money < 1000 : notes = int(money/100) balance = balance - money print("Amount of Rs",money,"Withdrawn Successfully...! ") print("You Got Cash as : ") print("Notes of Rs 100 : ",notes) print("Remaining balance is : ",balance ) try: cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,money,)) conn.commit() except Exception as err: print("Error is :",err) elif money%100==0 and money > 1000 : notes = money/1000 balance = balance - money print("Amount of Rs",money,"Withdrawn Successfully...! ") knotes = int(notes) print("Yot Got Cash as : ") print("Notes of 1000 : ",knotes) notes = str(notes).split('.')[1] if int(notes)>0: print("Notes of 100 : ",notes) else: pass print("Remaining balance is : ",balance ) try: cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,money,)) cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) conn.commit() except Exception as err: print("Error is :",err) else: print("Cannot Dispense Cash") else: print("Insufficient Balance") else : print("Enter Correct Pin") elif b == 2: print("Balance is Rs : ",balance) elif b == 3: transaction = "Credit" date = time.strftime('%Y-%m-%d %H:%M:%S') addcash = int(input("Enter Amount to Add")) balance = balance + addcash try: cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,addcash,)) cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) conn.commit() print("Amount of Rs",addcash,"addedd Successfully...!!") except Exception as err: print("Error is Addcash:",err) else : print("Please Select Correct Option") cursor.close() conn.close() def existinguser(): try: conn = psycopg2.connect("dbname=abc user=postgres password=postgres") cursor = conn.cursor() userinput = input("Enter username to Search :") cursor.execute("SELECT username from test WHERE username=%s",(userinput,)) row = cursor.fetchall() if len(row)==0: print("Username does not exist") else: userpin = getpass.getpass("Enter Pin") conn = psycopg2.connect("dbname=abc user=postgres password=postgres") cursor = conn.cursor() cursor.execute("SELECT username,balance,accno from test WHERE username=%s AND pin=%s",(userinput,userpin)) row = cursor.fetchall() while len(row)==0: attempt = 2 while attempt >=1: print("Wrong Pin Entered...Attempt Left",attempt) userpin = getpass.getpass("Enter Pin") cursor.execute("SELECT username,balance,accno from test WHERE username=%s AND pin=%s",(userinput,userpin)) row = cursor.fetchall() if len(row)==0: attempt = attempt-1 else: break else : print("Attempt Exceeded") break else: print("Pin Accepted Logging You into system please wait...!!") for r in row: print("Welcome Mr.",r[0]) print("Your Account Number is :",r[2]) print("Your Account Balance is Rs",r[1]) username = r[0] balance = int(r[1]) date = time.strftime('%Y-%m-%d %H:%M:%S') print("Select Service : ") b = int(input("1-Withdraw Money 2-Get Balance 3-Add Cash 4-View Past Transactions: ")) if b == 1: transaction = "Withdrawl" money = int(input("Enter Amount to Withdraw in multiple of 100 or 1000 only : ")) if money <= balance : if money%100==0 and money < 1000 : notes = int(money/100) balance = balance - money print("Amount of Rs",money,"Withdrawn Successfully...! ") print("You Got Cash as : ") print("Notes of Rs 100 : ",notes) print("Remaining balance is : ",balance ) try: cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,money,)) cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) conn.commit() except Exception as err: print("Error is :",err) elif money%100==0 and money > 1000 : notes = money/1000 balance = balance - money print("Amount of Rs",money,"Withdrawn Successfully...! ") knotes = int(notes) print("Yot Got Cash as : ") print("Notes of 1000 : ",knotes) notes = str(notes).split('.')[1] if int(notes)>0: print("Notes of 100 : ",notes) else: pass print("Remaining balance is : ",balance ) cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,money,)) cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) conn.commit() else: print("Cannot Dispense Cash") else: print("Insufficient Balance") elif b == 2: print("Balance is Rs : ",balance) elif b==3: transaction = "Credit" date = time.strftime('%Y-%m-%d %H:%M:%S') addcash = int(input("Enter Amount to Add :")) balance = balance + addcash try: cursor.execute("INSERT INTO test1 (username,transaction,date,amount) VALUES (%s,%s,%s,%s)",(username,transaction,date,addcash,)) cursor.execute("UPDATE test SET balance=%s WHERE username=%s",(balance,username)) conn.commit() print("Amount of Rs",addcash,"addedd Successfully...!!") except Exception as err: print("Error is Addcash:",err) elif b==4: cursor.execute("SELECT username,transaction,date,amount from test1 WHERE username=%s",(username,)) row = cursor.fetchall() if len(row)>0: print("Transaction Details :") print (" Date Type Amount") for r in row: print(r[2],r[1],r[3],) else: print("No Transactions Found") else : print("Please Select Correct Option") finally: cursor.close() conn.close() print("Welcome to ABC ATM ") a = int(input("Are You new here ? Press 1 for New User Press 2 for Existing User : ")) if a == 1: newuser() elif a == 2: existinguser() else : print("Wrong Input") print("Thank You for using ABC ATM")
# Given a string, your task is to count how many palindromic substrings in this # string. # # The substrings with different start indexes or end indexes are counted as # different substrings even they consist of same characters. # # Example 1: # # Input: "abc" # Output: 3 # Explanation: Three palindromic strings: "a", "b", "c". # # Example 2: # # Input: "aaa" # Output: 6 # Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". class PalindromicSubstrings: def __init__(self, input, output_expected): self.input = input self.output_expected = output_expected # ========== Expand From Center ================================================ # The center of a palindrome exists at a single letter (if the palindrome has an # odd number of characters) or between two letters (if the palindrome has an even # number of letters). # # In this approach, the FOR loop iterates over a range of numbers with an iterator # that points to either a character in the 'input' string, -or- the idea of a # 'space' between each character. The iterator represents the center of a # potential palindrome substring. # # For example, for a string with an odd number of characters like 'abc', that string # would contain a range of 2 * 3 - 1 = 5 possible palindromic 'centers', where 5 # accounts for 3 characters and 2 spaces. # # For a string with an even number of characters like 'abcd', that string would # contain a range of 2 * 4 - 1 = 7 possible palindromic 'centers', where 7 # represents 4 characters and 3 spaces. # # The pointers L and R are designed to point to locations on the string and, # unlike the range in the FOR loop, the pointers ignore the idea of a "space" # between characters -- they actually move across the string in a pattern that # resembles walking, were the L pointer moves forward, then the R pointer moves # forward, over and over again across the length of the string. This puts them in # a position where, if the conditions for a palindrome are met, they can start # to expand outward. # # Time complexity: O(n^2) - As the L and R pointers walk across the string, as if # they were being dragged by 'i' acting as a puppet master, they can potentially # visit each character in the entire string for each corresponding 'center' # character or space-between-characters in the range of 2 * N - 1. # # Space complexity: O(1) - We're only using a few variables and pointers. def expandFromCenter(self): input, output_expected = self.input, self.output_expected result = 0 # result = int N = len(input) for i in range(2 * N - 1): L = i // 2 R = L + i % 2 while L >= 0 and R < N and input[L] == input[R]: result += 1 L -= 1 R += 1 print(result == output_expected, output_expected, result) # ========== Manacher's Algorithm ============================================= # This algorithm basically has one purpose, which is to find the longest # palindrome substring in O(n), or linear time. In the 'expand at the center' # algorithm we visit each character in the string potentially N^2 times; however, # since palidromes are symmetric about their center (whether the center is a # character or a space between characters), during iteration if we have found a # palindromic center then we know -something- about the remaining characters in # the string that we have not yet visited -- we know that some of them will mirror # the previous characters that have already been visited, since the definition of # a palindrome is that the characters on the left of its center mirror the # characters on the right. # # The first step involves using the concept of 'separation', which basically # involves putting hash symbols, #, between characters to account for the idea of # 'spaces' between characters, as well as putting hash symbols at the beginning # and end of the string. # # The second step involves 'mirroring'. This step involves using an array with # numbers that somehow correspond to the string which has had hash characters # inserted between each pair of characters in the string in order to represent # spaces between characters, ie. a string represented via 'separation'. For # example: # # string: abaabc # string w/separation: # a # b # a # a # b # c # # array 'p': 0 1 0 3 0 1 4 1 0 1 0 1 0 # mirroring: 1 0 3 0 1 # # So in this example, an array named 'p' has numbers that somehow correspond to # the 'separated' string. Part of the array 'p' has numbers that seem to 'mirror' # around a central number, in this case the number 3 (there are also other # mirrors, but 1 0 3 0 1 is the biggest and is easy to use for this example). # # For the rest of the explanation, watch this: # https://www.youtube.com/watch?v=nbTSfrEfo6M # # Time complexity: O(n) # # Space complexity: O(n) def manachers(self): input, output_expected = self.input, self.output_expected result = 0 # Pre-process the string using the concept of 'separation' -- basically, # add some hash marks between characters, and also to the beginning and # end of the string. separated_str = '' for char in input: separated_str += '#' + char separated_str += '#' print(separated_str) # print(result == output_expected, output_expected, result) # ========== Tests ============================================================ def test(test_file, fn): with open(test_file) as tf: lines = tf.readlines() for i, line in enumerate(lines): if i % 2 == 0: input = line.strip('\n') else: output_expected = int(line.strip('\n')) ps = PalindromicSubstrings(input, output_expected) if fn == 'expandFromCenter': ps.expandFromCenter() if fn == 'manachers': ps.manachers() # ========== Command Line Arguments =========================================== if __name__ == '__main__': import sys test(sys.argv[1], sys.argv[2])
# Given a string S and a string T, find the minimum window in S which will # contain all the characters in T in complexity O(n). # # Example: # # Input: S = "ADOBECODEBANC", T = "ABC" # Output: "BANC" # Note: # # If there is no such window in S that covers all characters in T, return the # empty string "". # If there is such window, you are guaranteed that there will always be only # one unique minimum window in S. class MinimumWindowSubstring: def __init__(self, input, output_expected): self.input = input self.output_expected = output_expected # ========== Practice ========================================================= def blank(self): input, output_expected = self.input, self.output_expected result = '' s, t = input[0], input[1] # blank, result = string print(result == output_expected, output_expected, result) # ========== Tests ============================================================ def test(test_file, fn): with open(test_file) as tf: lines = tf.readlines() for i, line in enumerate(lines): if i % 2 == 0: input = line.strip('\n').split(', ') else: output_expected = line.strip('\n') mws = MinimumWindowSubstring(input, output_expected) if fn == 'blank': mws.blank() # ========== Command Line Arguments =========================================== if __name__ == '__main__': import sys test(sys.argv[1], sys.argv[2])
# Given a string s that consists of only uppercase English letters, # you can perform at most k operations on that string. # # In one operation, you can choose any character of the string and # change it to any other uppercase English character. # # Find the length of the longest sub-string containing all repeating # letters you can get after performing the above operations. # # Note: # Both the string's length and k will not exceed 104. # # Example 1: # # Input: # s = "ABAB", k = 2 # # Output: # 4 # # Explanation: # Replace the two 'A's with two 'B's or vice versa. # # Example 2: # # Input: # s = "AABABBA", k = 1 # # Output: # 4 # # Explanation: # Replace the one 'A' in the middle with 'B' and form "AABBBBA". # The substring "BBBB" has the longest repeating letters, which is 4. class LongestRepeatingCharacterReplacement: def __init__(self, input, output_expected): self.input = input self.output_expected = output_expected # ========== Sliding Window ========================================= def slidingWindow(self): input, output_expected = self.input, self.output_expected s = input[0] k = input[1] longest_window = 0 from collections import defaultdict window_counts = defaultdict(int) l = 0 for r in range(len(s)): window_counts[s[r]] += 1 print(window_counts.values(), max(window_counts.values())) while r - l + 1 - max(window_counts.values()) > k: window_counts[s[l]] -= 1 l += 1 longest_window = max(longest_window, r - l + 1) return longest_window # ========== Tests ================================================== def test(test_file, fn): with open(test_file) as tf: lines = tf.readlines() for i, line in enumerate(lines): if i % 2 == 0: s = line.strip('\n').split(', ')[0] k = int(line.strip('\n').split(', ')[1]) input = [s, k] else: output_expected = int(line.strip('\n')) lrcr = LongestRepeatingCharacterReplacement(input, output_expected) lrcr.slidingWindow() # ========== Command Line Arguments ================================= if __name__ == '__main__': import sys test(sys.argv[1], sys.argv[2])
# Reverse a linked list. class Node: def __init__(self, data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def create_node(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def display_nodes(self): ptr = self.head nodes = [] while ptr != None: nodes.append(ptr.data) ptr = ptr.next return nodes # ========== Practice ============================================== def iterative(ll, output_expected): ptr = ll.head prev_node = None while ptr != None: ptr.target = ptr.next ptr.next = prev_node prev_node = ptr ptr = ptr.target ll.head = prev_node print(ll.display_nodes() == output_expected, '\n', ll.display_nodes(), '\n', output_expected) # ========== Test ================================================== def test(test_file, fn): with open(test_file) as tf: lines = tf.readlines() for i, line in enumerate(lines): if i % 2 == 0: input = int(line.strip('\n')) else: output_expected = line.strip('\n').split(', ') # Create a linked list ll = LinkedList() if input > 0: for i in range(input): ll.create_node('node {}'.format(input - i)) # Reverse the linked list iterative(ll, output_expected) # ========== Command Line Arguments ================================ if __name__ == '__main__': import sys test(sys.argv[1], sys.argv[2])
# Given a 2d grid map of '1's (land) and '0's (water), count the number of # islands. An island is surrounded by water and is formed by connecting adjacent # lands horizontally or vertically. You may assume all four edges of the grid # are all surrounded by water. # # Example 1: # # Input: # 11110 # 11010 # 11000 # 00000 # # Output: 1 # Example 2: # # Input: # 11000 # 11000 # 00100 # 00011 # # Output: 3 class NumberOfIslands: def __init__(self, input, output_expected): self.input = input self.output_expected = output_expected # ========== Practice ========================================================= def bruteForce(self): grid, output_expected = self.input, self.output_expected result = 0 # blank, result = int print(result == output_expected, output_expected, result) # ========== Tests ============================================================ def test(test_file, fn): with open(test_file) as tf: lines = tf.readlines() map_2d = [] for i, line in enumerate(lines): if line.strip('\n').split(', ')[0] != 'output': row = [int(x) for x in line.strip('\n')] map_2d.append(row) else: output_expected = int(line.strip('\n').split(', ')[1]) noi = NumberOfIslands(map_2d, output_expected) map_2d = [] if fn == 'bruteForce': noi.bruteForce() # ========== Command Line Arguments =========================================== if __name__ == '__main__': import sys test(sys.argv[1], sys.argv[2])
import cv2 import numpy as np def main(): cap = cv2.VideoCapture(0) if cap.isOpened(): ret,fram = cap.read() print(ret) else: ret = False while ret: ret,fram = cap.read() hsv = cv2.cvtColor(fram,cv2.COLOR_BGR2HSV) ############################################################## #blue color low = np.array([100,10,50]) high = np.array([140,255,255]) img_mask = cv2.inRange(hsv, low, high) outputs = cv2.bitwise_and(fram,fram, mask=img_mask) #para 1 source, para 2 output , para 3 threshold mask #bitwise_and=Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar. #Result is true only if both operands are true. It can be used to set up a mask to check the values of certain bits. cv2.imshow("orginal immages" , fram) cv2.imshow('filter orginals' , outputs) print(outputs.mean()) if(outputs.mean()>20): print("BLUE "+str(outputs.mean())) else: print("Searching") ################################################################ #red color low = np.array([0,10,50]) high = np.array([0,255,255]) img_mask = cv2.inRange(hsv, low, high) output = cv2.bitwise_and(fram,fram, mask=img_mask) cv2.imshow("orginal immage" , fram) cv2.imshow('filter orginal' , output) if(output.mean()>0.2): print("RED "+str(output.mean())) else: print("") ################################################################## cv2.waitKey(1000) main()
def solution(number): sum = 0 for x in range(number): # Multiplos de 3 y 5 if x % 3 == 0 and x % 5 == 0: sum += x elif x % 3 == 0: sum += x elif x % 5 == 0: sum += x x -= 1 return(sum)
import xml.etree.ElementTree as ET #allows extraction of data from XML without worrying about #the rules of XML input = ''' <stuff> <users> <user x="2"> <id>001</id> <name>Chuck</name> </user> <user x="7"> <id>009</id> <name>Brent</name> </user> </users> </stuff> ''' stuff = ET.fromstring(input) l = stuff.findall('users/user') print 'User count:', len(l) for item in l: print ('Name: %s Id: %s Attr: %s') % \ (item.find('name').text, item.find('id').text, item.get('x'))
import sqlite3 conn = sqlite3.connect('music.sqlite3') cur = conn.cursor() ''' Insert rows into the table''' cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ? )', ('Thunderstruck', 20 )) cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ? )', ('My Way', 15)) conn.commit() #commit() writes data to database file print 'Tracks:' '''Retrieve rows from table''' # cur.execute('SELECT title, plays FROM Tracks') ''' * returns all columns for each row that matches the WHERE clause logical operators: =, <, >, <=, >=, !=, AND, OR''' # cur.execute('SELECT * FROM Tracks WHERE title = "My Way"') '''optional ORDER BY to control sorting of the returned rows''' cur.execute('SELECT title, plays FROM Tracks ORDER BY plays') for row in cur: #cursor() is iterable. Data read on demand as loop executes print row #output: u' - unicode strings capable of storing non-Latin character sets '''Update a column within 1+ rows in a table. Where specifies rows to be updated. Else all rows will be updated.''' cur.execute('UPDATE Tracks SET plays = 16 WHERE title = "My Way"') conn.commit() '''Remove rows, WHERE specifies which rows to delete''' cur.execute('DELETE FROM Tracks WHERE plays < 100') conn.commit() cur.close()
import matplotlib.pyplot as plt import numpy as np # creating a data col_count = 3 bar_width = .2 korea_scores = (554, 536, 538) canada = (518, 523, 525) china_scores = (613, 570, 580) france_scores = (495, 505, 499) # putting a data into visualization index = np.arange(col_count) k1 = plt.bar(index, korea_scores, bar_width, alpha=.4, label="Korea") c1 = plt.bar(index + 0.2, canada, bar_width, alpha=.4, label="Canada") ch1 = plt.bar(index + 0.4, china_scores, bar_width, alpha=.3, label="China") f1 = plt.bar(index + 0.6, france_scores, bar_width, alpha=.4, label="France") # configuring the data def CreateLabels(data): for item in data: height = item.get_height() plt.text(item.get_x() + item.get_width() / 2., height * 1.05, '%d' % int(height), ha='center', va='bottom') CreateLabels(k1) CreateLabels(c1) CreateLabels(ch1) CreateLabels(f1) plt.ylabel("Mean Score in PISA 2021") plt.xlabel("Subjects") plt.title("Test Scores by Country") plt.xticks(index + .3 / 2, ("Math", "Reading", "Science")) plt.legend(frameon=False, bbox_to_anchor=(1, 1), loc=2) plt.grid(True) plt.show()
from Pessoas import Pessoas try: nome: str = str(input('Qual seu nome? ')) sobrenome: str = str(input('Qual seu sobrenome? ')) idade: int = int(input('Qual sua idade? ')) p = Pessoas(nome,sobrenome,idade) print("Seu nome é " + p.retornoNomeCompleto() + " e sua idade é "+str(p.idade)) except Exception as e: print("Erro: ", e)
Frase = input("Ingrese una frase: ") for i in Frase: print(i)
#Datos de entrada dinero = int(input("Ingrese el dinero: ")) b10 = dinero//10000 dinero = dinero%10000 print("Billetes de 10.000:",b10) b5 = dinero//5000 dinero = dinero%5000 print("Billetes de 5.000:",b5) b1 = dinero//1000 dinero = dinero%1000 print("Billetes de 1.000:",b1) m500 = dinero//500 dinero = dinero%500 print("Moneda de 500:",m500) m100 = dinero//100 dinero = dinero%100 print("Moneda de 100:",m100) m50 = dinero//50 dinero = dinero%50 print("Moneda de 50:",m50) m10 = dinero//10 dinero = dinero%10 print("Moneda de 10:",m10) m5 = dinero//5 dinero = dinero%5 print("Moneda de 5:",m5) m1 = dinero print("Moneda de 1:",m1)
largo = 10 res = range(largo) ################ inicio = 2 fin = 10 res = range(inicio,fin) ################# inicio = 5 fin = 20 incremento = 5 res = range(inicio,fin,incremento) for i in res: print(i)
def validar_nombre(nombre): if len(nombre)<6: return "El nombre de usuario debe contener al menos 6 caracteres" if len(nombre)>12: return "El nombre de usuario no debe contener más de 12 caracteres" if " " in nombre: return "El nombre no puede contener espacios" if nombre.isalpha: return "Nombre de usuario correcto" ############################################ nombre = input("Ingrese un nombre de usuario: ") print(validar_nombre(nombre))
preferencias = ['Tv','Cine','Paseo','Música','Teatro'] # recorrer forma 1 #for i in range(len(preferencias)): # print(preferencias[i]) # recorrer forma 2 #for x in preferencias: # print(x) ## Recorrer todos items de la lista e imprimir letra a letra cada items. ###Permite saber el largo de un elemento #print(len(preferencias)) #Range me genera un intervalo entre 0 y número -1 for i in range(len(preferencias)): # rango 0,1,2,3,4 print("La palabra N°",i+1,"mide:", len(preferencias[i])) for j in range(len(preferencias[i])): print(preferencias[i][j]) print("") for x in preferencias: print("La palabra mide:", len(x)) for y in x: print(y) print("")
print("Bienvenido al medidor de tornillos") tamano_tornillo = float(input("Ingrese el tamaño del tornillo a medir: ")) if tamano_tornillo >= 1 and tamano_tornillo<3: print("Pequeño") elif tamano_tornillo >= 3 and tamano_tornillo<5: print("Mediano") elif tamano_tornillo >= 5 and tamano_tornillo<6.5: print("Grande") elif tamano_tornillo >= 6.5 and tamano_tornillo<8.5: print("Muy grande") else: print("Medida no valida")
horas = int(input("Ingrese las horas de trabajo: ")) pagoxhora = int(input("Ingrese el valor de la hora: ")) if horas > 45: sueldo = horas*pagoxhora*1.5 else: sueldo = horas*pagoxhora print("El sueldo es",sueldo)
#función para calcular el area de un triangulo # Def <- Indica que es una función def AreaTriangulo(base, altura): area = (base*altura)/2 return area ########################################## baseEntrada = int(input("Ingresa la base: ")) alturaEntrada = int(input("Ingresa la altura: ")) area = AreaTriangulo(baseEntrada,alturaEntrada) print(area)
lista1 = [] for i in lista1: print(i) lista2 = [1,2,3,4,5,6,7,8,9] print("Antes:",lista2) lista3 = ["Uno",1,"Dos",2,"Tres",3] #lista2[0] = 99 #print("Despues 1:",lista2) #lista2[4] = lista2[7] #print("Despues 2:",lista2) print(lista1) lista1.append(100) print(lista1)
numero = int(input("Ingresa un número ")) print(range(numero)) for i in range(numero,100,5): print (i)
cont = 1 while cont: print(cont) cont+=1 if cont==25: break cont = 0 while cont < 10: cont+=1 if cont%2==0: continue print(cont, end=" ") print("Es impar")
"""LibSPN image visualization functions.""" from libspn.data.image import ImageShape import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt def show_image(image, shape, normalize=False): """Show an image from flattened data. Args: image (array): Flattened image data shape (ImageShape): Shape of the image data. normalize (bool): Normalize data before displaying. """ if not isinstance(shape, ImageShape): raise ValueError("shape must be ImageShape") if not (np.issubdtype(image.dtype, np.integer) or np.issubdtype(image.dtype, np.floating)): raise ValueError("image must be of int or float dtype") if shape[2] == 1: # imshow wants single channel as MxN shape = shape[:2] image = image.reshape(shape) cmap = mpl.cm.get_cmap('Greys_r') if normalize: vmin = None vmax = None # imshow will normalize else: if np.issubdtype(image.dtype, np.integer): vmin = 0 vmax = 255 elif np.issubdtype(image.dtype, np.floating): vmin = 0.0 vmax = 1.0 plt.imshow(image, cmap=cmap, interpolation='none', vmin=vmin, vmax=vmax) plt.grid(False) plt.show()
""" 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ '''Solution for max min in list: [..min..max..] -> max - min [..max...min..] : [ ..max| ... | min... ] A B C only part A, B, C include answer B part can apply this function again ''' class Solution: def maxProfit(self, prices): """find max profit in a list of stock price """ # [max->min] -> 0 temp = sorted(prices)[::-1] if temp == prices: return 0 # simple situation prices_set = set(prices) max_index = prices.index(max(prices_set)) min_index = prices.index(min(prices_set)) print("Max Position: ",max_index,"\nMin Position: ",min_index) if max_index >= min_index : return prices[max_index]-prices[min_index] # 2th sitution if max_index == 0: answer_A = 0 else: answer_A = prices[max_index] - min(prices[:max_index]) print("Part B: ",prices[max_index+1:min_index]) if max_index == min_index - 1: answer_B = 0 else: answer_B = self.maxProfit(prices[max_index+1:min_index]) if min_index == len(prices)-1: answer_C = 0 else: answer_C = max(prices[min_index+1:]) - prices[min_index] return max(answer_A,answer_B,answer_C) if __name__ == "__main__": s = Solution() price1 = [7,1,5,3,6,4] price2 = [7,6,4,3,1] price3 = [11,4,7,2,1] print(s.maxProfit(price3))
""" 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。 如果有两个中间结点,则返回第二个中间结点。   示例 1: 输入:[1,2,3,4,5] 输出:此列表中的结点 3 (序列化形式:[3,4,5]) 返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。 注意,我们返回了一个 ListNode 类型的对象 ans,这样: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL. 示例 2: 输入:[1,2,3,4,5,6] 输出:此列表中的结点 4 (序列化形式:[4,5,6]) 由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/middle-of-the-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # 快慢指针:比较经典的做法是: # 使用两个指针变量,刚开始都位于链表的第 1 个结点,一个永远一次只走 1 步,一个永远一次只走 2 步,一个在前,一个在后,同时走。这样当快指针走完的时候,慢指针就来到了链表的中间位置。 # 作者:liweiwei1419 # 链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/kuai-man-zhi-zhen-zhu-yao-zai-yu-diao-shi-by-liwei/ # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: ''' ''' Node_list = [] i = 0 Node_list.append(head) while True: if not Node_list[i].next: break Node_list.append(Node_list[i].next) i+=1 return Node_list[len(Node_list)//2]
""" 给你一个整数数组 nums,将该数组升序排列。   示例 1: 输入:nums = [5,2,3,1] 输出:[1,2,3,5] 示例 2: 输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Quick sort import random class Solution: def sortArray(self, nums: list) -> list: ''' ''' self.recursive_quick_sort(nums, 0, len(nums)-1) return nums def quick_sort(self, nums, l, r): '''Quick sort implement :para l: low boundry r: high boundry nums: list :output pivot: the index of pivot ''' # get pivot pivot = random.randint(l,r) nums[pivot], nums[r] = nums[r], nums[pivot] i = l-1 for j in range(l,r): if nums[j] <= nums[r]: i+=1 nums[j], nums[i] = nums[i], nums[j] nums[i+1], nums[r] = nums[r], nums[i+1] return i+1 def recursive_quick_sort(self, nums, l, r): '''recursive part ''' if r <= l: return pivot = self.quick_sort(nums, l, r) self.recursive_quick_sort(nums, l, pivot-1) self.recursive_quick_sort(nums, pivot+1, r) if __name__ == "__main__": s = Solution() nums = [5,1,1,2,0,0] print(s.sortArray(nums))
class Solution: """ @param str: An array of char @param offset: An integer @return: nothing """ def rotateString(self, str, offset): # write your code here if str == []: return str l = len(str) #5 #print(l) if offset < 0 : return "Input Error." if offset > l: offset = offset - l * int(offset/l) m = l - offset #numbers of str need to move for i in range(offset): a = str[l - offset + i] for j in range(m): str[l - offset - j + i] = str[l - offset - j - 1 + i] str[i] = a return str M = Solution() str = ['a','b','c','d','e'] print(M.rotateString("",2))
""" 在给定的网格中,每个单元格可以有以下三个值之一: 值 0 代表空单元格; 值 1 代表新鲜橘子; 值 2 代表腐烂的橘子。 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。 返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotting-oranges 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from queue import Queue class Solution: def orangesRotting(self, grid) -> int: '''Use BFS put orange location in a set - target put rot_location and time in a quene use BFS until target is empty, return time ''' # get grid size w = len(grid[0]) h = len(grid) # get the target & rot target = set() rot = set() for i in range(h): for j in range(w): if grid[i][j] == 1: target.add(str(i)+str(j)) if grid[i][j] == 2: rot.add(str(i)+str(j)) if len(target) == 0: return 0 # print(rot) q = Queue() for i in range(len(rot)): q.put((rot.pop(),0)) # print('q',q.get()) while not q.empty(): rot_loc, time = q.get() # print('get out: ',rot_loc) for i in range(2): for add in (-1,1): # print(rot_loc) if (int(rot_loc[i])+add) < 0 or (i==0 and (int(rot_loc[i])+add)==h) or (i==1 and (int(rot_loc[i])+add)==w): continue cur = rot_loc[:i]+str(int(rot_loc[i])+add)+rot_loc[i+1:] # print(cur,i,add) if cur in target: # print("put in: ",cur) q.put((cur,time+1)) target.remove(cur) if len(target) == 0: return time+1 return -1 if __name__ == "__main__": s = Solution() grid = [[2,1,1],[1,1,0],[0,1,1]] print(s.orangesRotting(grid))
""" 输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # math question from math import floor, sqrt class Solution: def findContinuousSequence(self, target: int): '''force + math for i find sum(a,a+1,...,a+interval) = target if interval is a integer get the list else continue ''' sequence = [] for i in range(1,target-1): interval = (sqrt((2*i+1)**2-8*(i-target))-(2*i+1))/2 if interval == floor(interval): temp = [] for a in range(i,i+int(interval)+1): temp.append(a) sequence.append(temp) else: continue return sequence if __name__ == "__main__": s = Solution() print(s.findContinuousSequence(15))
""" 给定一个字符串,逐个翻转字符串中的每个单词。   示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: "  hello world!  " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good   example" 输出: "example good a" 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-words-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # class Solution: def reverseWords(self, s: str) -> str: ''' 1. remove other blanks 2. switch every words ''' words = [] s = s.replace('\xa0',' ') l = len(s) if l == 1: return s.replace(' ','') # get the list i = 0 j = 0 while i<l: if s[i] != ' ': print(i,s[i]) if i == l-1: words.append(s[i:]) for j in range(i+1,l): if s[j] == ' ': words.append(s[i:j]) i = j break if j == l-1: words.append(s[i:j+1]) i = j break i+=1 words_s = words[::-1] print(words_s) sw = ' '.join(words_s) return sw if __name__ == "__main__": s = Solution() c = s.reverseWords(" a") print('c:',c)
""" 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。 注意:两结点之间的路径长度是以它们之间边的数目表示。 """ # Wrong # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def diameterOfBinaryTree(self, root): temp_node = [] if root == None: return 0 # judge leaf def judge_leaf(node): if node.left == None and node.right == None: return True return False # dfs function def search(node): if node == None or judge_leaf(node): return 0 step = 0 search_temp_node = [] search_temp_node.append((node,0)) while len(search_temp_node) != 0: # print(len(search_temp_node)) temp, step = search_temp_node.pop() if not judge_leaf(temp): step += 1 else: continue if temp.left != None: if not judge_leaf(temp.left): search_temp_node.append((temp.left,step)) if temp.right != None : if not judge_leaf(temp.right): search_temp_node.append((temp.right,step)) # print("Search: ",node.val," has ",step) return step diameter = 0 temp_node.append(root) while len(temp_node) != 0: d_temp_node = temp_node.pop() if judge_leaf(d_temp_node): continue new_way = 0 if d_temp_node.left != None: new_way += (search(d_temp_node.left)+1) if d_temp_node.right != None: new_way += (search(d_temp_node.right)+1) diameter = max(diameter,new_way) if d_temp_node.left != None : if not judge_leaf(d_temp_node.left): temp_node.append(d_temp_node.left) if d_temp_node.right != None: if not judge_leaf(d_temp_node.right): temp_node.append(d_temp_node.right) return diameter if __name__ == "__main__": node = dict() for i in range(20): node[str(i)] = TreeNode(i) node['1'].left = node['2'] # node['1'].right = node['3'] node['2'].left = node['4'] node['2'].right = node['5'] # node['3'].left = node['6'] node['4'].left = node['7'] node['5'].right = node['8'] node['7'].left = node['9'] node['9'].left = node['10'] s = Solution() print(s.diameterOfBinaryTree(node['1']))