text
stringlengths
37
1.41M
''' 假设函数f()等概率随机返回一个在[0,1)范围上的浮点数,那么我们知道,在[0,x)区间上的数出现的概率为x(0<x≤1)。 给定一个大于0的整数k,并且可以使用f()函数,请实现一个函数依然返回在[0,1)范围上的数, 但是在[0,x)区间上的数出现的概率为x的k次方。 ''' # -*- coding:utf-8 -*- import random class RandomSeg: def f(self): return random.random() # 请通过调用f()实现 def random(self, k, x): res = 0 for i in range(k): res = max(res, self.f()) return res
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Remove: def removeNode(self, pNode): # write code here self.pNode = pNode if self.pNode.next == None: return False else: self.pNode.val = self.pNode.next.val self.pNode.next = self.pNode self.pNode = self.pNode.next return True ''' class Remove { public: ListNode* removeNode(ListNode* pHead, int delVal) { // 第一种情况:删除的节点是头节点 if (pHead->val == delVal) { ListNode *node = pHead->next; pHead->next = NULL; return node; } ListNode *previous = pHead; ListNode *current = pHead->next; while (current != NULL) { if (current->val == delVal) { previous->next = current->next; current->next = NULL; } previous = previous->next; current = current->next; } return pHead; } }; '''
import random class QuickSort: def quickSort(self,A,n): if A==[]: return [] x = A[0] left = self.quickSort([i for i in A[1:] if i<x],1) right = self.quickSort([j for j in A[1:] if j >= x ],1) res= left + [x] + right return res a = QuickSort() #out = a.quickSort([1,3,4,5,2,6]) ''' 取 a[l] 作为切分元素,然后从数组的右端向左扫描找到第一个小于它的元素,交换这两个元素。 再从数组的左端向右扫描直到找到第一个大于等于它的元素。 不断进行这个过程,就可以保证左指针 i 的左侧元素都不大于切分元素,右指针 j 的右侧元素都不小于切分元素。 当两个指针相遇时,将切分元素 a[l] 和 a[j] 交换位置。 ''' def quick_sort(L): return q_sort(L, 0, len(L) - 1) def q_sort(L, left, right): if left < right: pivot = Partition(L, left, right) q_sort(L, left, pivot - 1) q_sort(L, pivot + 1, right) return L def Partition(L, left, right): pivotkey = L[left] while left < right: while left < right and L[right] >= pivotkey: right -= 1 L[left] = L[right] while left < right and L[left] <= pivotkey: left += 1 L[right] = L[left] L[left] = pivotkey return left L = [5, 9, 1, 11, 6, 7, 2, 4] out = quick_sort(L)
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' import timeit def single_number(arr): start = timeit.default_timer() # Your code here # Store an array of double values seen in the loop. # Loop again and check if the value is in this list. # List comprehension to check for duplicated and remove the odd balls. # Can we use sets? dupes = {} for e in arr: if e not in dupes.keys(): dupes[e] = 1 else: dupes[e] += 1 for key, value in dupes.items(): if value == 1: final = timeit.default_timer() - start print(f"Time: {final:.8f}:") return key if __name__ == '__main__': # Use the main function to test your implementation arr = [1, 1, 4, 4, 5, 5, 3, 3, 9, 0, 0] print(f"The odd-number-out is {single_number(arr)}")
import random import math class Activation(object): #constructor method of Activation equation def __init__(self, input): #get the type self.get_type(input) #set dividor self.divide = 1 #set up random weight self.weight = random.uniform(-50, 50) return #decide what type of operation to do based off the input of Activation def get_type(self, input): if input == '1': self.type = 1 elif input == '2': self.type = 2 elif input == '3': self.type = 3 else: self.type = 4 return #setting up the value for self.divide def encode_divide(self, array): #getting biggest value in array lValue = self.get_biggest(array) #get number of digit of largest value sVal = self.get_size(lValue) #determine divide value if sVal > 2: self.divide = 10 ** (sVal - 2) sVal = 2 #if it is type 'e', then minimize it one more time if self.type == 4 : if sVal == 2: self.divide = self.divide * 10 if self.type == 3: if sVal == 2: self.divide = self.divide * 10 return #returns the biggest value inside an array def get_biggest(self, array): biggest = 0.0 #biggest value in array size = len(array) #size of the array for i in range(size): if biggest < array[i][0]: biggest = array[i][0] return biggest #return number of digit of number def get_size(self, nval): count = 0 number = int(nval) while(number > 0): number = int(number / 10) count = count + 1 return count #set up type 2 def set_two(self, array): size = len(array) for i in range(size): array[i][0] = array[i][0] ** 2 return #set up type 3 def set_three(self, array): size = len(array) for i in range(size): array[i][0] = math.atan(array[i][0]) return #set up type e def set_e(self, array): sArray = len(array) #update values in array for i in range(sArray): array[i][0] = 1 / (1 + (math.e ** (-1 * array[i][0]))) return #Properly Divide each value based off divide base def mDivide(self, array): size = len(array) for i in range(size): array[i][0] = array[i][0] / self.divide #Multiply Weight into array def mWeight(self, array): size = len(array) for i in range(size): array[i][0] = self.weight * array[i][0] #training the model def train(self, oArray): #copy the array array = self.copy_array(oArray) #making values inside array reasonable self.encode_divide(array) self.mDivide(array) #perform operation if self.type == 2: self.set_two(array) elif self.type == 3: self.set_three(array) elif self.type == 4: self.set_e(array) self.mWeight(array) return array #test the model def test(self, oArray): #copy the array array = self.copy_array(oArray) #divide to ideal numbers self.mDivide(array) #perform operation if self.type == 2: self.set_two(array) elif self.type == 3: self.set_three(array) elif self.type == 4: self.set_e(array) self.mWeight(array) return array #get the weight def get_w(self): return self.weight #set the weigth def set_w(self, w): self.weight = w return #get the type def get_t(self): return self.type #copy the array def copy_array(self, array): cArray = [] size = len(array) for i in range(size): temp = [] temp.append(array[i][0]) cArray.append(temp) return cArray ###################################################### #TEST ###################################################### def get_d(self): return self.divide
# For PiDay 2020 - Created by Brent Hartley using the Chudnovsky Algorithm # Program called Pi.py (pronounced pie (dot) pie), using a function called PiDay, and # Run on a raspberry pi, on 3-14-2020 # Variables spell p, i, d, a, y, because, why not? # This change to the digit limited program lets the program caculate pi for a pre-defined number of seconds # Change time allotment by changing variable 'time_limit' import decimal import sys import string import time # Define start time and time limit. Time limit is equal to 3 minutes 14 seconds because 3.141. start_time = time.time() time_limit = (60 * 3) + (14) # Define the Chudnovsky Algorithm and call it PiDay because why not? def PiDay(): x, p, i, d, a, y, = 1, 0, 1, 1, 3, 3, while True: if 4*x+p-i < a*i: yield a ap = 10*(p-a*i) a = ((10*(3*x+p))//i)-10*a x *= 10 p = ap else: ap = (2*x+p)*y aa = (x*(7*d)+2+(p*y))//(i*y) x *= d i *= y y += 2 d += 1 a = aa p = ap pi_digits = PiDay() i = 0 for d in pi_digits: sys.stdout.write(str(d)) # Add 1 to the line break counter i += 1 # Print a line break after 60 digits and reset the line break counter if i == 60: print(""); i = 0; if time.time() - start_time > time_limit: sys.exit("Caculation Complete")
# Write your code here water = 200 milk = 50 beans = 15 cups = int(input("Write how many cups of coffee you will need:\n")) print(f'''For {cups} of coffee you will need: {water * cups} ml of water {milk * cups} ml of milk {beans * cups} g of coffee beans''')
def range_sum(numbers, start, end): valid_values = [num for num in numbers if start <= num <= end] return sum(valid_values) input_numbers = [int(num) for num in input().split()] a, b = [int(num) for num in input().split()] print(range_sum(input_numbers, a, b))
# Write your code here from random import randrange options = ["rock", "paper", "scissors"] usr_input = input() ai_input = options[randrange(3)] choices = {"player": usr_input, "AI": ai_input} if choices["player"] == "scissors": if choices["AI"] == "scissors": print(f"There is a draw ({choices['AI']})") elif choices["AI"] == "rock": print(f"Sorry, but the computer chose {choices['AI']}") else: print(f"Well done. The computer chose {choices['AI']}") elif choices["player"] == "rock": if choices["AI"] == "rock": print(f"There is a draw ({choices['AI']})") elif choices["AI"] == "paper": print(f"Sorry, but the computer chose {choices['AI']}") else: print(f"Well done. The computer chose {choices['AI']}") else: if choices["AI"] == "paper": print(f"There is a draw ({choices['AI']})") elif choices["AI"] == "scissors": print(f"Sorry, but the computer chose {choices['AI']}") else: print(f"Well done. The computer chose {choices['AI']}")
number_one = float(input()) number_two = float(input()) print(number_one + number_two)
def tallest_people(**people): sorted_people = sorted(people.items(), key=lambda k: (-k[1], k)) # for person in sorted_people: # print(person[0], ':', person[1]) for person in sorted_people: if person[1] == max(people.values()): print(person[0], ':', person[1])
# Don't forget to make use of lambda functions in your solution func = lambda x: "x ends with 0" if (x % 10 == 0) else "x doesn't end with 0"
# Write your code here tasks = ['Do yoga', 'Make breakfast', 'Learn basics of SQL', 'Learn what is ORM'] print('Today:') for i, task in enumerate(tasks): print(f'{i+1}) {task}')
# write your code here state = input("Enter cells: ") matrix = list(state) print("---------") print(f"| {matrix[0]} {matrix[1]} {matrix[2]} |") print(f"| {matrix[3]} {matrix[4]} {matrix[5]} |") print(f"| {matrix[6]} {matrix[7]} {matrix[8]} |") print("---------")
size = int(input()) message = "" if size < 1: message = "no army" elif size < 10: message = "few" elif size < 50: message = "pack" elif size < 500: message = "horde" elif size < 1000: message = "swarm" else: message = "legion" print(message)
class Painting: museum = "Louvre" def __init__(self, title, painter, year_of_creation): self.painter = painter self.title = title self.year_of_creation = year_of_creation painting = Painting(input(), input(), input()) print(f'"{painting.title}" by {painting.painter} ({painting.year_of_creation}) hangs in the {painting.museum}.')
class Student: courseMarks={} name="" family="" def __init__(self, name, family): self.name = name self.family = family def addCourseMark(self, course, mark): self.courseMarks[course] = mark def average(self): marks = self.courseMarks.values() average = sum(marks) / len(marks) return average e = Student("jimmy", "neutron") print e.name print e.family e.addCourseMark("EE 240", 30) e.addCourseMark("CMPUT 420", 2) print e.average()
#Sci 127 Teaching Staff #October 2017 #Count which cars got the most parking tickets #Import pandas for reading and analyzing CSV data: import pandas as pd csvFile = input('Enter CSV file name: ') #Name of the CSV file tickets = pd.read_csv(csvFile) #Read in the file to a dataframe print("The 10 worst offenders are:") print(tickets["Plate ID"].value_counts()[:10]) #Print out the dataframe print("The 10 worst offenders are:") print(tickets["Vehicle Color"].value_counts()[:10]) #Print out the dataframe
#Coin flip program #The Purpose of this program is to generate a random number from 1 to 6 and display it #As a dice face. I have then chnaged the program to continue until #it has rolled a 6 #<(^_^<) <(^_^)> (>^_^)> import random,time result = "" result2 = " " dice = ["- - - - -\n| |\n| O |\n| |\n- - - - -\n", "- - - - -\n| O |\n| |\n| O |\n- - - - -\n", "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n", #This part stores the different dice graphics into 6 different variables in a list. "- - - - -\n| O O |\n| |\n| O O |\n- - - - -\n", "- - - - -\n| O O |\n| O |\n| O O |\n- - - - -\n", "- - - - -\n| O O |\n| O O |\n| O O |\n- - - - -\n"] def roll(): print("rolling.....") global result #This part tells the user the dice is rolling and stores the result in a global variable result = random.randint(1,6) def show_dice(): print(dice[result-1]) #This prints the dice depending on the roll while result != 6: userinput = input("Press enter to continue") # This forces the user to press enter to continue the program roll() #Runs teh roll function time.sleep(1) #Pauses the program show_dice() #runs the roll dice function """ inport instead of import ; instead of , Print instead of print randing instead of randint else instead of elif multiple lack of colons (>^_^)> """
"""Make a two-player Rock-Paper-Scissors game.""" import os ch='y' while ch=='y': player1=input("Player 1/enter value 1.rock 2.paper 3.siccor :") os.system('clear') player2=input("Player 2/enter value 1.rock 2.paper 3.siccor :") os.system('clear') if player1==player2: print("same") ch=input("\nclick y if you want to continue:") continue if player1=='1': if player2=='2': print("player2 won") else: print("player1 won") ch=input("\nclick y if you want to continue:") continue if player1=='2': if player2=='3': print("player2 won") else: print("player1 won") ch=input("\nclick y if you want to continue:") continue if player1=='3': if player2=='1': print("player2 won") else: print("player1 won") ch=input("\nclick y if you want to continue:") continue
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import requests,urllib import argparse import ast class UrlFit(): def __init__(self): self.URL = "https://api.url.fit/shorten" def Shorten(self,url): target = self.URL + "?long_url=" + urllib.quote_plus(url) resp = requests.get(target, headers={'User-Agent': 'Python Library 1.0'}) return resp.json() def main(): parser = argparse.ArgumentParser(description='UrlFit -- shorten url') parser.add_argument('url', help='input url what you want to short') args = parser.parse_args() urlfit = UrlFit() short = urlfit.Shorten(str(args.url)) print "https://url.fit/"+short["url"] if __name__=="__main__": main()
# Check if an array is sorted # Given an array C[], write a program that prints 1 if array is sorted in non-decreasing order, else prints 0. ''' Example: Input 2 5 10 20 30 40 50 6 90 80 100 70 40 30 Output 1 0 ''' #-------------------------custom code---------------------------------------- t=int(input("Enter Test Cases: ")) for i in range(t): A=[] N=int(input("Enter The Size of Array: ")) print("Enter Array Elemnt: ") for i in range(N): a=int(input()) A.append(a) print(A) sortedarray=sorted(A) if A==sortedarray: print(1) else: print(0) #-----------------------------second method custom code-------------------------- # t=int(input("Enter Test Cases: ")) # for i in range(t): # A=[] # N=int(input("Enter The Size of Array: ")) # print("Enter Array Elemnt: ") # for i in range(N): # a=int(input()) # A.append(a) # print(A) # A1=A[:] # A1.sort() # if A1==A: # print(1) # else: # print(0) #---------------------------------------GFG code------------------------ # t=int(input()) # for i in range(t): # n=int(input()) # A=list(map(int,input().split())) # sorted_array=sorted(A) # if A==sorted_array: # print(1) # else: # print(0)
# Compete the skills ''' A and B are good friend and programmers. They are always in a healthy competition with each other. They decide to judge the best among them by competing. They do so by comparing their three skills as per their values. Please help them doing so as they are busy. Set for A are like [a1, a2, a3] Set for B are like [b1, b2, b3] Compare ith skill of A with ith skill of B if a[i] > b[i] , A's score increases by 1 if a[i] < b[i] , B's score increases by 1 Input : The first line of input contains an integer T denoting the test cases. For each test case there will be two lines. The first line contains the skills of A and the second line contains the skills of B Output : For each test case in a new line print the score of A and B separated by space. Example: Input : 2 4 2 7 5 6 3 4 2 7 5 2 8 Output : 1 2 0 2 ''' #-----------------------------------custom code------------------------- t=int(input("Enter Test Cases: ")) for i in range(t): A=[] B=[] print("Enter A and B values: ") for i in range(3): a=int(input("Enter A values: ")) A.append(a) b=int(input("Enter B values: ")) B.append(b) print(A) print(B) counterA=0 counterB=0 for i in range(3): if A[i] > B[i]: counterA+=1 elif A[i] < B[i]: counterB+=1 else: counterA+=0 counterB+=0 print(counterA,"",counterB) #-------------------------------------GFG code------------------------------------------ # t=int(input()) # for i in range(t): # A=list(map(int,input().split())) # B=list(map(int,input().split())) # counterA=0 # counterB=0 # for i in range(len(A)): # if A[i] > B[i]: # counterA+=1 # elif A[i] < B[i]: # counterB+=1 # else: # counterA+=0 # counterB+=0 # print(counterA,counterB)
a= [] #declaring list n=int(input("Enter number of leads you need to sort: "))#number of leads for i in range(n): #input the leads values using for loop a.append(input("Enter the leads ")) def list(lead_email): #recursive function to sort the list with respective company domain emails={ } domains={ } #Dictionaries for the leadlist for l in lead_email: domainname=l[l.index('@')+1:l.index('.')] #Regular expression to to extract domain name leads=l #to store leads if(domainname not in emails): #check whether domainname matches leads emails emails[domainname]=[ ] #create list with domainname emails[domainname].append(leads) #append the matching emails domains[domainname]=1 else: emails[domainname].append(leads) domains[domainname]+=1 #append emails matching with domainname return emails, domains print(list(a)) #recursive function for displaying the seperated domainname and leads
i = 0 while i <= 10: print(i) i += 2 for j in 'hello world': if j == 'w': continue print(j * 2, end='') for y in 'hello world': if y == 'w': break print(y * 3, end='') for t in 'hello world': if t == 'a': break else: print("Буквы нет")
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") m_name=name1.lower() y_name=name2.lower() combine_name=m_name+y_name a=0 b=0 a+=combine_name.count("t") a+=combine_name.count("r") a+=combine_name.count("u") a+=combine_name.count("e") b+=combine_name.count("l") b+=combine_name.count("o") b+=combine_name.count("v") b+=combine_name.count("e") score=int(f"{a}{b}") if score<10 or score>90: print(f"Your score is {score}, you go together like coke and mentos.") elif score>=40 and score<=50: print(f"Your score is {score}, you are alright together.") else: print(f"Your score is {score}.")
print("Welcome to Python Pizza Deliveries! ") bill=0 size=input("What size pizza do you want? S,M or L ") if size=="Y": bill+=15 print("Small size pizza price is: $15") elif size=="M": bill += 20 print("Medium size pizza price is: $20") elif size=="L": bill += 25 print("Large size pizza price is: $25") else: print("Not such size!") add_pepperoni=input("Do you want pepperoni? Y or N ") if add_pepperoni=="Y": if size=="S": bill+=2 print("extra amount for pepperoni: $2 for small pizza") else: bill+=3 print("extra amount for pepperoni: $3 for medium or large pizza") extra_cheese=input("Do you want extra cheeze? Y or N ") if extra_cheese=="Y": bill+=1 print("extra amount for extra cheese: $1") print(f"your final bill is: ${bill}")
row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") #1st Method # if position[0]=='1': # if position[1]=='1': # row1[0]='X' # elif position[1]=='2': # row2[0]='X' # elif position[1]=='3': # row3[0]='X' # else: # print("row doesn't exist!") # elif position[0]=='2': # if position[1]=='1': # row1[1]='X' # elif position[1]=='2': # row2[1]='X' # elif position[1]=='3': # row3[1]='X' # else: # print("row doesn't exist!") # elif position[0]=='3': # if position[1]=='1': # row1[2]='X' # elif position[1]=='2': # row2[2]='X' # elif position[1]=='3': # row3[2]='X' # else: # print("row doesn't exist!") # else: # print("Wrong position Selected") #2nd Method map[int(position[1])-1][int(position[0])-1]='X' print(f"{row1}\n{row2}\n{row3}")
def Create(i): print("1.Personal Acc") print("2.loan Acount") ch=int(input()) f=1 while(f): fnme=input("enter First name:") lnme=input("enter last name:") if fnme.isalpha() and lnme.isalpha(): name.append(fnme+" "+lnme) f=0 else: if not fnme.isalpha(): while(f): print("Invalid first name format") fnme=input("enter first name correctly:") if fnme.isalpha(): f=0 if not lnme.isalpha(): f1=1 while(f1): print("Invalid last name format") lnme=input("enter last name correctly:") if lnme.isalpha(): f1=0 f=1 while(f==1): dob=input("Enter date of Birth in dd/mm/yyyy format:") if dob[len(dob)-4:]<='2000' and dob[:2]<='31' and dob[3:5]<='12': Dob.append(dob) f=0 else: if dob[:2]>'31': print("invalid date.") elif dob[3:5]>'12': print("invalid month.") elif dob[len(dob)-4:]>'2000': print("below 18") br=input("DOB is wrong....press y to re-enter:") if br=='y': continue else: name.pop() login() break address.append(input("Enter address:")) f=1 while(f): aa=int(input("enter Aadhar:")) while len(str(aa))!=12 or not str(aa).isnumeric(): print("Enter valid Aadhar number") aa=int(input("enter Aadhar number:")) if aa not in Aadhar: Aadhar.append(aa) f=0 elif ch!=2: print("Aadhar number already linked with another Account") f=1 while(f): cel=input("Enter Mobile number:") if len(str(cel))==10 and str(cel).isnumeric(): cell.append(int(cel)) f=0 else: print("Invalid mobile number") Acc.append(328601494500+i) if ch==2: Typ.append("loan") lt.append(Acc[-1]) lt.append(input("Enter Loan Name:")) loan.append(lt) bal.append(-float(input("Enter Amount to be Sanctioned:"))) print("............",lt[-1],"LOAN SANCTIONED SUCESSFULLY...........") else: while f!=1: ch3=int(input('''enter what type of persnal Account 1.savings 2.current ''')) if ch3==1: Typ.append("savings") f=1 elif ch3==2: Typ.append("current") f=1 else: print("Enter Valid option") bal.append(0.00) print(".........",Typ[-1],"ACCOUNT SUCCESSFULLY CREATED.........") print() print("***************** Passbook as follows ***********") print() Cdisplay(ch) def Cdisplay(chois): print(" STATE BANK OF INDIA") print(" BRANCH: Vidyanikethan") print("NAME :",name[-1]) print("DOB :",Dob[-1]) print("ADDRESS :",address[-1]) print("ACCOUNT NUMBER :",Acc[-1]) print("AADHAR NUMBER :",Aadhar[-1]) print("TYPE OF ACC :",Typ[-1]) print("MOBILE NUMBER :",cell[-1]) if chois==2: print("TYPE OF LOAN :",lt[-1]) print("SanctionedAmount: ",-(bal[-1])) else: print("BALANCE : ",bal[-1]) print() def Balance(count): print("1.Acc number") print("2.Aadhar") xx=int(input()) if xx==1: a=int(input("Enter Acc.Number:")) if a in Acc: ind=Acc.index(a) print("Name:",name[ind]) if Typ[ind]=='loan': print("Payable amount:",-(bal[ind])) else: print("balance:",bal[ind]) count=0 print() else: print("ACC not exists or wrong Acc.number") count+=1 b=input("want to continue....press y") if count<2 and b=='y': Balance(count) else: print("Limit exceeded...visit bank manager you") print() else: a=int(input("Enter Aadhar Number:")) if a in Aadhar: ind=Aadhar.index(a) print("Name: ",name[ind]) print("ACC num:",Acc[ind]) print("balance:",bal[ind]) count=0 print() else: print("ACC not exists or wrong Aadhar number") count+=1 b=input("want to continue....press y") if count<2 and b=='y': Balance(count) else: print("Limit exceeded...visit bank manager you") print() def Deposit(count): a=int(input("Enter Acc.Number:")) if a in Acc: ind=Acc.index(a) dep=float(input("enter amount to deposit:")) while(dep<0): print("Invalid amount") dep=float(input("Re-enter the amount amount to deposit:")) k=list(str(dep).split(".")) if len(k[1])>2: print("Invalid amount") Deposit(count) bal[ind]+=dep b=input("Deposited successfully........do you want to check balance enter y:") if(b=='y'): print("BALANCE:",bal[ind]) print() else: print("ACC not exists (or) enter correct Acc.number:") count+=1 if count<2: Balance(count) else: print("Limit exceeded.......meet bank manager you!") print() def Withdrawl(count): a=int(input("Enter Acc.Number:")) for j in range(len(loan)): if loan[j][0]==a: break if a in Acc: ind=Acc.index(a) if Typ[ind]=="loan": print("since its a ",loan[j][1], "loan Account...withdrawl operation cant be performed") else: wit=float(input("Enter amount to withdrawl:")) k=list(str(wit).split(".")) if len(k[1])>2 or wit<0: print("Invalid amount") else: if bal[ind]>=wit+500 and wit>0: bal[ind]-=wit b=input("Withdrawl success.........do you want to check balance enter y:") if(b=='y'): print("balance: ",float(format(round(bal[ind],2)))) else: print("Insufficient funds/invalid amount/you should maintain minimum balance 500") print() else: print("ACC not exists (or) enter correct Accoun number:") count+=1 if count<2: Withdrawl(count) else: print("Limit exceeded........meet bank manager you!") def status(count): a=int(input("enter Acc.Number:")) for j in range(len(loan)): if loan[j][0]==a: break if a in Acc: p=Acc.index(a) print("*****************STATE BANK OF INDIA*********************") print(" BRANCH: Vidyanikethan") print("NAME :",name[p]) print("DOB :",Dob[p]) print("ADDRESS :",address[p]) print("ACCOUNT NUMBER :",a) print("AADHAR NUMBER :",Aadhar[p]) print("TYPE OF ACC :",Typ[p]) if Typ[p]=="loan": print("LOAN TYPE :",loan[j][1]) print("PAYBLE Amount :",-bal[p]) else: print("BALANCE :",bal[p]) print("MOBILE NUMBER :",cell[p]) else: print("ACC not exists or enter correct Acc.number:") count+=1 if count<=2: status(count) else: print("Limit exceeded........meet bank Manager you!") def Transfer(): af=int(input("Enter Acc number to transfer from:")) at=int(input("enter Acc number to transfer to:")) if af in Acc and at in Acc: amt=int(input("Enter the Amounnt:")) if bal[Acc.index(af)]>=amt+500: bal[Acc.index(af)]-=amt bal[Acc.index(at)]+=amt print("Transfered successfully") print() else: print("Insuffientfunds.......") else: print("Invalid Account number(s).......Re-enter Account numbers") Transfer() def delete(count): a=int(input("Enter Account number to delete:")) if a not in Acc or len(Acc)==0: print("Account not exists/No Accounts Available to Delete") else: xxx=Acc.index(a) name.pop(xxx) Acc.pop(xxx) address.pop(xxx) bal.pop(xxx) Aadhar.pop(xxx) if Typ[xxx]==loan: loan.pop(xxx) Typ.pop(xxx) ch2=input("Account deleted successfully.....:") def Add(): un=input("Enter username") psw=input("entre password") Access[un]=psw print("Accountant %s Added Successfully" %un) c=input("Enter y to re-login:") if c=='y': login() def login(): t=0 i=0 while(t<2): print("Enter your username:") na=input() print("Enter access key:") acckey=input() if acckey not in Access and na not in Access: print("HEY DONGA.....DONGA.....DONGA...") print("POYINDI POOO MOTHHAM POYINDI POO...") exit(1) elif Access[na]==acckey: t=3 print("LOGGED IN AS",na,"..........") while(1): print("1.Create Account") print("2.Balance Enquiry") print("3.Deposit") print("4.Withdrawl") print("5.Status Of Account") print("6.Transfer") print("7.Delete Account") print("8.Add Accountant") print("9.Exit/Stop/logout") n=int(input()) if n==1: i+=1 Create(i) lt=[] elif n==2: Balance(0) elif n==3: Deposit(0) elif n==4: Withdrawl(0) elif n==5: status(0) elif n==6: Transfer() elif n==7: delete(0) elif n==8: Add() elif n==9: exit(0) else: print("enter valid option") print() elif ((na not in Access)and (acckey in Access))or((acckey not in Access)and (na in Access)): print("One word missing.......Try to think to get yourself out.") t+=1 elif (acckey in Access and na in Access)and Access[na]!=acckey: print("Accesskey dose not matched with your username") print() t+=1 if t==2: print("limit exceeded....!") name=[] address=[] Dob=[] Acc=[] bal=[] Aadhar=[] Typ=[] lt=[] loan=[] cell=[] Access={'vishnu':'vardhan','anil':'kumar','sunil':'sunny','muni':'jyo'} login()
if __name__ == '__main__': a=12+11 tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5) list1 = ["a", "b", "c", "d","e"] list2=['e','f'] set1={1,2,3} set2={1,3,2} list3=list1+list2 tup4=tup1+tup2 x='asdf' print(set2*2)
# coding: utf-8 # In[1]: ##playing with arrays in Numpy # In[3]: import numpy as np # In[7]: # passing lists mylist = [1,2,3] x = np.array(mylist) x # In[11]: y = np.array([4,5,6]) y # In[14]: # stacking lists vertically to build a (2,3) array z = np.vstack((x,y)) z # In[15]: np.shape(z) # In[17]: linear = np.linspace(0,4,9) print linear # In[18]: print linear.reshape(3,3) # In[19]: print linear.resize(3,3) # In[20]: print linear # In[21]: print z.resize(2,3) # In[22]: print z.resize(3,2) # In[23]: print z # In[25]: np.ones((3,2)) # In[26]: np.zeros((2,2)) # In[27]: np.diag(y) # In[30]: np.repeat([1,2,3],3) # In[31]: np.array([1,2,3]*3) # In[32]: p=np.ones([2,3],int) p # In[33]: np.array(p*2) # In[34]: #notice the difference between operations in a list and array #for example [1,2,3]*3 is different than array([1,2,3])*3 # In[35]: np.array([1,2,3])*3 # In[36]: np.array([1,2,3]*3)
# -*- coding: utf-8 -*- """ Created on Mon Nov 14 16:20:13 2016 @author: hg happy number takes a number and returns true if number is happy and false if number is unhappy """ def happy_number(n): ''' test conditions, if number is happy cycle ends in 1 by definition if the number is unhappy it enters a cycle containing 4''' testconditions = [1,4] while n not in testconditions: total = 0 n = list(str(n)) for i in n: total += int(i)**2 n = total if n == 4: return False elif n == 1: return True #generates array with all happy numbers in range array = [] for i in range(1,1000001): if happy_number(i) == True: array.append(i) print(array)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Chương trình chuyển đổi từ Tiếng Việt có dấu sang Tiếng Việt không dấu """ import re import unicodedata def no_accent_vietnamese(s): # s = s.decode('utf-8') s = re.sub(u'Đ', 'D', s) s = re.sub(u'đ', 'd', s) return unicodedata.normalize('NFKD', s).encode('ASCII', 'ignore') if __name__ == '__main__': # print(no_accent_vietnamese("Việt Nam Đất Nước Con Người")) # print(no_accent_vietnamese("Welcome to Vietnam !")) # print(no_accent_vietnamese("VIỆT NAM ĐẤT NƯỚC CON NGƯỜI")) with open('VNTQcorpus-small.txt', encoding='utf-8') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [str(x.strip()) for x in content] no_accent_content = [] print("Strip accent") for line in content: no_accent_content.append(no_accent_vietnamese(line)) file = open("VNTQcorpus-small_no_accent.txt", "w") print("write file") for line in no_accent_content: print(line) file.write(line.decode("utf-8")+"\n") # file.write(bytes("\n")) file.close()
print('Enter the number, operation and the second number') n1=int(input()) op=str(input()) n2=int(input()) def calc(n1,op,n2): if op=='+': return int(n1)+int(n2) elif op=='-': return int(n1)-int(n2) elif op=='*': return int(n1)*int(n2) elif op=="/": return int(n1) / int(n2) else: return 'Unknown operation' print(calc(n1,op,n2))
import pandas as pd from pathlib import Path def merge_csv_to_excel(csv_files, sheet_names, sep=';', output='merged.xlsx'): """ Merge `csv_files` into a single excel file. Parameters: ----------- csv_files: List of Path Paths to the csv files to be merged. sheet_names: List of str Names of excel worksheets corresponding to the `csv_files` sep: str Delimeter of the csv file. output: Path or str Output of the merged excel file. """ writer = pd.ExcelWriter(output, engine='xlsxwriter') for csv, sheet_name in zip(csv_files, sheet_names): df = pd.read_csv(csv, sep=sep) df.to_excel(writer, sheet_name=sheet_name, index=False) writer.save() if __name__ == "__main__": PATH = Path() DATA_PATH = PATH/'test_data' CSVs = list(DATA_PATH.glob('*.csv')) names = [f.stem for f in CSVs] merge_csv_to_excel(CSVs, names, sep=';')
import json filename = "understanding.json" while True: value = raw_input("Did you understand(Yes:1, No:0)") understandingObject = {"understanding":value} with open(filename, 'w') as understandingfile: json.dump(understandingObject, understandingfile)
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # # # Program: tictactoe.py # # Written by: Eric Cox # # Copyright: (C) 2017, Eric Cox. All Rights Reserved. # # Purpose: Create an AI to play TicTacToe in a means with will allow it to # # win or end the game in a draw. # # # ############################################################################### class TicTacToeGame: playerSymbols = ['X', 'O'] totalOutcomes = 0 turnWins = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] turnMoves = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] turn9Wins = 0 def __init__(self, gBoard, turn): self.gameBoard = gBoard self.turn = turn TicTacToeGame.totalOutcomes += 1 TicTacToeGame.turnMoves[self.turn] += 1 self.winner = '' self.winnerChildX = 0 self.winnerChildO = 0 self.gameOver = self.isGameOver() self.childMoves = [] if self.gameOver is False: self.populateChildMoves(self.gameBoard) for child in self.childMoves: self.winnerChildX += child.winnerChildX self.winnerChildO += child.winnerChildO else: TicTacToeGame.turnWins[self.turn] += 1 if self.winner == 'X': self.winnerChildX += 1 elif self.winner == 'O': self.winnerChildO += 1 def populateChildMoves(self, gb): # print("Turn: "+str(self.turn)) for x in range(len(gb)): if gb[x] == ' ': next_turn = self.turn+1 game_move = [] for loc in gb: game_move.append(loc) game_move[x] = TicTacToeGame.playerSymbols[self.turn % 2] childGame = TicTacToeGame(game_move, next_turn) #print("Position: "+str(x)+" Board:"+str(game_move)) self.childMoves.append(childGame) def getChildMoves(self): return self.childMoves def isGameOver(self): if self.gameBoard[0] == self.gameBoard[1] and self.gameBoard[1] == self.gameBoard[2] and self.gameBoard[0] != ' ': self.winner = self.gameBoard[0] return True elif self.gameBoard[3] == self.gameBoard[4] and self.gameBoard[3] == self.gameBoard[5] and self.gameBoard[3] != ' ': self.winner = self.gameBoard[4] return True elif self.gameBoard[6] == self.gameBoard[7] and self.gameBoard[6] == self.gameBoard[8] and self.gameBoard[6] != ' ': self.winner = self.gameBoard[7] return True elif self.gameBoard[0] == self.gameBoard[3] and self.gameBoard[3] == self.gameBoard[6] and self.gameBoard[0] != ' ': self.winner = self.gameBoard[0] return True elif self.gameBoard[1] == self.gameBoard[4] and self.gameBoard[4] == self.gameBoard[7] and self.gameBoard[1] != ' ': self.winner = self.gameBoard[1] return True elif self.gameBoard[2] == self.gameBoard[5] and self.gameBoard[5] == self.gameBoard[8] and self.gameBoard[2] != ' ': self.winner = self.gameBoard[2] return True elif self.gameBoard[0] == self.gameBoard[4] and self.gameBoard[4] == self.gameBoard[8] and self.gameBoard[0] != ' ': self.winner = self.gameBoard[0] return True elif self.gameBoard[2] == self.gameBoard[4] and self.gameBoard[4] == self.gameBoard[6] and self.gameBoard[2] != ' ': self.winner=self.gameBoard[2] return True else: return False def printBoard(gameArray): letterArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] gameString="┌─┬─┬─┐ ┌─┬─┬─┐\n│0│1│2│ │a│b│c│\n├─┼─┼─┤ ├─┼─┼─┤\n│3│4│5│ │d│e│f│\n├─┼─┼─┤ ├─┼─┼─┤\n│6│7│8│ │g│h│i│\n└─┴─┴─┘ └─┴─┴─┘" if len(gameArray) == 9: for x in range(len(gameArray)): gameString = gameString.replace(letterArray[x],gameArray[x]) gameString = "Number: Board: \n"+gameString return gameString else: return "Error: Array mismatch" def main(): print("Loading AI") game1 = TicTacToeGame([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], 0) print(str(TicTacToeGame.totalOutcomes)) print(TicTacToeGame.turnMoves) print(TicTacToeGame.turnWins) while game1.gameOver is False and game1.gameBoard.count(' ')>0: print(printBoard(game1.gameBoard)) nexLoc = input("Where should 'X' play?: ") if int(nexLoc)>=0 and int(nexLoc)<9 and game1.gameBoard[int(nexLoc)]==' ': tempBoard=[] for space in game1.gameBoard: tempBoard.append(space) tempBoard[int(nexLoc)]='X' for child in game1.childMoves: if child.gameBoard == tempBoard: game1=child #Below is where the AI starts, it works by picking the move with the smallest difference between X and O victories print(printBoard(game1.gameBoard)) if game1.gameOver is False and game1.gameBoard.count(' ')>0: maxWinO=0 minWinX=1000000 minDiff=3000 newMove=game1.childMoves[0] for child in game1.childMoves: print("X:"+str(child.winnerChildX)+" O:"+str(child.winnerChildO)+" Diff:"+str(abs(child.winnerChildX-child.winnerChildO))) for child in game1.childMoves: #print("X:"+str(child.winnerChildX)+" O:"+str(child.winnerChildO)) if child.winnerChildX==0 and child.winnerChildO>0: newMove=child print("a") break #The diff cannot be equal to 196 because on the first move the lowest diff can be this when X goes on 1,3,5,7 and # the AI response was to pic a corner which would allow an X win in 2 moves elif abs(child.winnerChildX-child.winnerChildO)<minDiff and abs(child.winnerChildX-child.winnerChildO)!=196: tempMinDiff=minDiff tempNewMove=newMove for cPrime in child.childMoves: if cPrime.gameOver and cPrime.winner=='X': minDiff=tempMinDiff newMove=tempNewMove print("b") break elif child is not None: minDiff=abs(child.winnerChildX-child.winnerChildO) newMove=child #Use this code to make a competitive but beatable AI """ elif child.winnerChildX<minWinX: tempMinWinX=minWinX tempNewMove=newMove for cPrime in child.childMoves: if cPrime.gameOver and cPrime.winner=='X': minWinX=tempMinWinX newMove=tempNewMove print("c") break elif child is not None: minWinX=child.winnerChildX newMove=child """ game1 = newMove print("\n\n\n\n\n"+printBoard(game1.gameBoard)) print("Game Over!") if game1.gameOver: print(game1.winner+" Won!") else: print("Game is a draw.") if __name__ == "__main__": main()
class Celsius: def __init__(self, temperature): self.__temperature = self.__to_fahrenheit(temperature) def __to_fahrenheit(self, valor): return (valor* 1.8) + 32 @property def temperature(self): print("Obteniendo valor") return self.__temperature @temperature.setter def temperature(self, value): if value < -273: print("Temperature below -273 is not possible") print("Colocando valor") self.__temperature = value temp_obj = Celsius(-275) print(temp_obj.temperature) temp_obj.temperature = -274 print(temp_obj.temperature)
''' CREAR UNA CLASE GATO QUE LLEGUE A DORMIR COMER JUGAR gatito''' from random import randrange, choice class Gato(): conducta = 'bien' comida = True _raza = 'felino' def __init__(self,color='cafe',edad=2,genero='macho'): self.color = color self.edad = edad self.genero = genero def comer(self): if self.tiene_hambre(): print('Esta comiendo') else: print('No tiene hambre') if self.jugar() == 'bien': print('Se porto {}'.format(self.conducta)) print('Merece comer mucho...') elif self.jugar() == 'regular': print('Se porto regular') elif self.jugar() == 'malo': print('Se porto mal') def jugar(self): return self.conducta def dormir(self): print('Esta durmiendo') def tiene_hambre(self): return self.comida bandera = True salir = 0 while bandera: gato_defecto = input('Quieres ingresar datos de gato? (S/N)-->') gato_defecto = gato_defecto.upper() if gato_defecto == 'S': color_gato= input('Color del gato-->') edad_gato= int(input('Edad del gato-->')) genero_gato= input('Genero del gato-->') minino = Gato(color_gato,edad_gato,genero_gato) comportamiento =choice(['bien', 'regular', 'malo']) Gato.conducta = comportamiento minino.comer() bandera = False elif gato_defecto =='N': minino = Gato() comportamiento =choice(['bien', 'regular', 'malo']) bandera = False else: print('Digite las opciones qu se le dio...') salir +=1 if salir == 3: print('Se le dio {} intentos'.format(salir)) bandera = False #Gato.comida = False #Gato.conducta = comportamiento #minino.dormir() #minino.jugar() #minino.comer() #print(minino.color) #print(minino._raza)
# CON VARIABLES GLOBALES def suma(): global resultado def validar(): return numero_dos > 0 and numero_uno > 0 if validar(): resultado = numero_uno + numero_dos #solo se validaran si son mayores a cero numero_uno = 2 numero_dos = 2 sumando = suma() print('resultado-->{}'.format(resultado))
#DECORADOR VARIABLE GLOBAL # SOLO DEBO UAR VARIABLES GLOBALES # CUANDO SE DECLARE UNA CONSTANTE O ALGO SENCILLO def decorador(mi_funcion): def nueva_funcion(*args, **kwargs): resultado = mi_funcion(*args, **kwargs) return nueva_funcion @decorador def sumar(n_uno, n_dos): resultado = n_uno + n_dos print('Resultado-->{}'.format(resultado)) num_uno = 15 num_dos = 20 sumar(num_uno, num_dos)
class Usuario: def __init__(self,usuario,contrasena,correo): self.usuario = usuario self.__contrasena = self.__encriptar(contrasena) self.correo = correo def __encriptar(self, contrasena): return contrasena.upper() # ME RETORNE ATRIBUTOS PRIVADOS def get_contrasena(self): return self.__contrasena usuario_empresa = Usuario('mario','secreto','[email protected]') print('usuario',usuario_empresa.usuario) #usuario_empresa.__contrasena = 'Aqui cambio contraseña' #print('contraseña',usuario_empresa.contrasena) print('correo',usuario_empresa.correo) print('correo',usuario_empresa.get_contrasena())
'''def halve_evens_only(nums): return [i/2 for i in nums if not i % 2] numeros = [1,2,3,4,5,6,7,8,9,0,67,34,234,34,2,2,2] resultado = halve_evens_only(numeros)''' def animal(nombre): if nombre == 'Rigoberto': print ('Se llama --> {}'.format(nombre)) mensaje = 'Tiene hambre' return mensaje elif nombre == 'Pupi': print ('Se llama -->{}'.format(nombre)) mensaje = 'Esta dormido' return mensaje else: mensaje = 'No se encuentra el nombre' return mensaje nombre = 'Pupi' mostrar_animal = animal(nombre) print (mostrar_animal)
class MiClase: def __init__(self,midato): self.set_dato(midato) def get_dato(self): return self.__dato def set_dato(self,midato): if isinstance(midato,(int,float)): if midato < 0: print('entro dato') self.__dato = 0 elif midato > 10: self.__dato = 10 else: self.__dato = midato else: raise ValueError('Dato no valido') def cuadrado(self): return self.__dato**2 a = MiClase(10) print('el cuadrado es',a.cuadrado()) a.set_dato(7) print('el cuadrado es',a.cuadrado())
# CLOUSER DE SUMA def clou_ser(): def validar(): return numero_uno > 0 and numero_dos > 0 return validar def sumar(mi_clouser): if mi_clouser(): resultado = numero_uno + numero_dos print('resultado-->{}'.format(resultado)) #solo se validaran si son mayores a cero numero_uno = 2 numero_dos = 2 nuevo_clouser = clou_ser() sumando = sumar(nuevo_clouser)
Que es Python? python es un lenguaje de programacion interpretado, que a diferencia de otros lenguajes de programacion como java, go, sharp no necesita ser compilado, simplemente ejecutamos nuestro programa. python es multiparadigma ya que python podemos trabajar con programacion estructurada, orientada a objetos , funcional entre otros, no necesitamos cambiar modificar archivos. python es de tipado dinamico, si manejamos una variable con un argumento y un atributo de tipo entero, en la siguiente linea de codigo podemos cambiar sus atributo y el argumento python es de sintaxis simple, de codigo legible, como si fuera pseudocodigo, y que nos ayuda a que terceros puedan entender nuestro codigo python es multiplataforma, puede ser ejecutada en los tres sistemas operativos windows mac linux. Porque aprender Python? porque tiene una curva de aprendizaje baja. y lo podemos apreciar desde el primer programa que es hola mundo que puede ser ejecutada en una sola linea de codigo a diferencia de otros programas que necesitan mas lineas de codigo. Lo cual para muchos puede ser hasta frustrante si no se llegara a ejecutar. Y resulta ser mas tedioso. es de codigo legible se peude usar en muchas ocasiones, si bien python es una herramienta de trabajo, y como herramienta de trabajo no puede ser usada en todos los ambitos, pero si abarca gran cantidad de ellos, como programacion web, de escritorio, programacion artificial, baterias incluidas, que tiene varios sripts como el munpy para matematicas que nos ayudaran en nuestro script. variable: Una variable es un espacio en la memoria ram que almacena datos. haci que cuando se termine de ejecutarse las varibles se perderan. Almacenamos , caracteres, enteros, numeros reales,booleanos numro enteros, son aquellos que no tienen punto decimal numeros flotantes, son aquellos que tienen punto decimal numero complejos son numeros imaginarios. string en un conjunto de caracteres unido s entre si string listas cadaa caracter se encuentra en una posicion ESTO ES UNA LISTA DE caracteres METODOS DE CADENAS maneja upper lower find replace pero no invertir LISTAS siempre manejaran corchetes TUPLAS al igual que las listas nos permitiran almacenar elemtos pero estas son inmutables
# REALIZAR UNA LISTA QUE AGREGE INSERTE ETC. mi_lista = [0, True, 'Pajarito', 12.5] mis_enteros = [1,2,3,66,1,0,10,100,50] mi_lista.append('Agregando') mi_lista.insert(3,'Insertado') mi_lista.extend(mis_enteros) print('Lista-->{}'.format(mi_lista))
superhero = { "name": "Wonder Woman", "alias": "Diana Prince", "gear": [ "Lasso of Truth", "Bracelets of Submission" ], "vehicle": { "title": "Invisible Jet", "speed": "2000 mph", } } lasso = superhero["gear"][0] print(lasso) for item in superhero["gear"]: print("%s has %s" % (superhero["name"], item))
user_input = int(input("Please enter a number under 50 for how many time you want it to loop. ")) n1, n2 = 0, 1 count = 0 if user_input <= 0: print("Please enter a positive number.") elif user_input == 1: for i in range(2, user_input): print(i, end=', ') print("Fibonacci sequence upto", range, ":") print(n1) elif user_input >= 51: print("That is too high a number.") else: print("Fibonacci sequence:") while count < user_input: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1
class Position: """Wannabe Immutable position/vector class that handels the needed add and multiply methods""" x: int y: int # The x and y values are not to be below 0 or above the below values. max_x: int = None max_y: int = None def __init__(self, x, y, max_x = None, max_y = None): self.max_x = max_x self.max_y = max_y self.x = self._within_bounds(x, self.max_x) self.y = self._within_bounds(y, self.max_y) def __add__(self, other): return Position(self.x + other.x, self.y + other.y, max_x=self.max_x, max_y=self.max_y) def __mul__(self, const): return Position(self.x * const, self.y * const, max_x=self.max_x, max_y=self.max_y) def _within_bounds(self, a, max_a): if max_a: if a < 0: a = 0 elif a >= max_a: a = max_a - 1 return a def __repr__(self): return f'{self.x} {self.y}' directions = { 'u' : Position(0,1), 'd' : Position(0,-1), 'r' : Position(1,0), 'l' : Position(-1,0) } while True: w, l = (int(x) for x in input().strip().split()) if w == 0 and l == 0: break segments = int(input().strip()) robot = Position(0,0) actual = Position(0,0, max_x=w, max_y=l) for _ in range(segments): d, dist = input().strip().split() dist = int(dist) change = directions[d] * dist robot += change actual += change print(f"Robot thinks {robot}") print(f"Actually at {actual}") print("")
from collections import defaultdict m, n = (int(x) for x in input().split()) # find all haywords worth = defaultdict(int) for i in range(m): line = input().split() worth[line[0]] = int(line[1]) # job descriptions for i in range(n): job_desc = "" while True: line = input() job_desc += line + ' ' if line == '.': break points = 0 for word in job_desc.split(): points += worth[word] print(points)
order = [] order.extend(map(int, input().split())) order.extend(map(int, input().split())) order.extend(map(int, input().split())) def distance(a, b): import math diff_x = a[0] - b[0] diff_y = a[1] - b[1] return math.sqrt(diff_x ** 2 + diff_y ** 2) def index_to_pos(index): return (index % 3, index // 3) # find the total travel dist. 1 unit grid. dist = 0 for num in range(1, 9): current = order.index(num) derp = order.index(num + 1) current_pos = index_to_pos(current) next_pos = index_to_pos(derp) d = distance(current_pos, next_pos) dist += d print(dist)
from collections import defaultdict def get_distance(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def get_grid(lowest_x, lowest_y, highest_x, highest_y, points): for i in range(lowest_x, highest_x + 1): for j in range(lowest_y, highest_y + 1): yield i, j def is_infinite(lowest_x, lowest_y, highest_x, highest_y, point, distances): x, y = point[0], point[1] infinite = True while x >= lowest_x: if distances[x, y] != point: infinite = False x -= 1 if infinite: return True x, y = point[0], point[1] infinite = True while y >= lowest_y: if distances[x, y] != point: infinite = False y -= 1 if infinite: return True x, y = point[0], point[1] infinite = True while x <= highest_x: if distances[x, y] != point: infinite = False x += 1 if infinite: return True x, y = point[0], point[1] infinite = True while y <= highest_y: if distances[x, y] != point: infinite = False y += 1 if infinite: return True return False def main(): point_to_distances = {} position_counter = defaultdict(list) with open('input.txt') as f: points = [] lowest_x = None lowest_y = None highest_x = None highest_y = None for line in f: x, y = line.split(',') x, y = int(x), int(y) if lowest_x is None: lowest_x = x else: lowest_x = min(x, lowest_x) if highest_x is None: highest_x = x else: highest_x = max(x, highest_x) if lowest_y is None: lowest_y = y else: lowest_y = min(y, lowest_y) if highest_y is None: highest_y = y else: highest_y = max(y, highest_y) points.append((x,y)) for x, y in get_grid(lowest_x-1, lowest_y-1, highest_x+1, highest_y+1, points): for point in points: distance = get_distance(point, (x,y)) position_counter[(x, y)].append((point, distance)) closest_counter = defaultdict(int) result = {} for key, value in position_counter.items(): value.sort(key=lambda x: x[1]) if value[0][1] != value[1][1]: closest_counter[value[0][0]] += 1 result[key] = value[0][0] else: result[key] = None max_distance = -1 for key, value in closest_counter.items(): if value > max_distance and not is_infinite(lowest_x, lowest_y, highest_x, highest_y, key, result): max_distance = value # Part 1 print(max_distance) # Part 2 result = 0 for key, value in position_counter.items(): total = sum(x[1] for x in value) if total < 10000: result += 1 print(result) if __name__ == '__main__': main()
def factorial(num): if (num == 1): return 1 elif(num == 0): return 1 else: return num*factorial(num-1) print(factorial(5))
class Empty(Exception): pass class ArrayQueue: def __init__(self): self._data= [] self._size = 0 self._front = 0 def __len__(self): #AQ_size 가 0이다 왜냐하면 위에 self._data = 빈 리스트기때문에 return self._size def is_empty(self): # 지금 빈리스트라 트루를 반환함 if self._size ==0: return True def enqueue(self, e): self._data.append(e) def dequeue(self): eng = self._data[0] #eng 를 가장 먼처들어간 데이터라고보고 del self._data[0] # 가장먼저들어온 데이터 삭제 (큐의 특징) return eng #삭제된후 리스트 반환 def first(self): if len(self._data) == 0: #데이터의 길이가 0일때 즉 빈리스트일때 에러값을 띄움 raise Empty("큐는 없다 ") else: return self._data[0] # 빈리스트가 아니면 처음들어간 데이터를 반환한다. AQ = ArrayQueue() print(len(AQ)) print(AQ.is_empty()) print(AQ._data.append(2)) print(AQ._data) print(AQ._data.append(3)) print(AQ._data.append(4)) print(AQ._data) print(AQ.dequeue()) print(AQ._data) print(AQ.first())
def factorial(n): if n == 0: return 1 elif n == 1 : return 1 return n * factorial(n-1) def factor(n): u = 1 if n == 0 or n == 1: return 1 for i in range(2,n+1): u *= i return u print(factor(3)) def hanoi(n): if n == 1 : return 1 if n == 2: return 3 return hanoi(n-1) + 1 + hanoi(n-1) def hanoi_path(n, start=1, end=2): the = 6-start-end res = "" if n: res = hanoi_path(n-1,start, the) res += "%s번 디스크를 %s번 폴대에서 %s폴대로 이동하세요\n" %(n, start, end) res += hanoi_path(n-1,the, end) return res print(hanoi_path(4))
def find(n): result = [] for char in n: list = ['h', 'e'] #print(char) if char in list: result.append(char) return result n = "heooooooooolllooohhhhhllooollololo" # result = [] # for c in find(n): # result.append(c) print(find(n))
class Empty(Exception): pass class ArrayQueues: def __init__(self): self.data = [] def __len__(self): return len(self.data) def enqueue(self, num): return self.data.append(num) def dequeue(self): how_long=len(self.data) if how_long==0: return "Error" else : re_data = self.data[0] self.data = self.data[1:len(self.data)] return re_data def is_empty(self): if len(self.data)==0: return True else : return False def first(self): if len(self.data)==0: return False else : return self.data[0] Q = ArrayQueues() Q.enqueue(5) Q.enqueue(3) print(len(Q)) print(Q.dequeue()) print(Q.is_empty()) print(Q.dequeue()) print(Q.is_empty()) print(Q.dequeue()) Q.enqueue(7) Q.enqueue(9) print(Q.first()) Q.enqueue(4) print(len(Q)) print(Q.dequeue())
class Empty(Exception): pass class ArrayQueue: def __init__(self): self._data = [] def __len__(self): return len(self._data) def is_empty(self): if len(self._data): return False else: return True def first(self): if len(self._data) == False: raise Empty("error") else: return self._data[0] def dequeue(self): val = self._data[0] del self._data[0] return val def enqueue(self, e): self._data.append(e) Q = ArrayQueue() Q.enqueue(5) Q.enqueue(3) print(len(Q)) print(Q.dequeue()) print(len(Q)) print(Q.first())
def hanoi_tower(num): if num is 1: return 1 else: return 2*hanoi_tower(num-1)+1 print(hanoi_tower(3)) print(hanoi_tower(2)) print(hanoi_tower(10)) def hanoi_instruction(num, startPeg=1, endPeg=3): if num: hanoi_instruction(num-1,startPeg,6-startPeg-endPeg) print("{}번 디스크를 {}번 막대에서 {}번 폴대로 이동시키시오.".format(num, startPeg, endPeg)) hanoi_instruction(num-1,6-startPeg-endPeg,endPeg) hanoi_instruction(3) """ 하노이강의 있음 열혈강의 자료구조 강의 쿠폰 등록해놨습니다. 로그인 하시면 들으실 수 있어요. 아이디는 fastcampus 이고 비밀번호는 자료구조 입니다. 영타로 자료구조 라고 쓰시면 됩니다. 책도 필요하신 분 있음 가져갈게요. 공공재로 씁시다. 어차피 사놓고 1년 동안 들여다 보지도 않았네요ㅋㅋ http://www.orentec.co.kr/teachlist/DA_ST_1/teach_sub1.php """
def hanoiTower(n): if (n == 1): return 1 else: return hanoiTower(n-1)*2 + 1 print(hanoiTower(10)) # def hanoi(n,start,end,mid): # # if(n == 1): # print("%d번 디스크를 %d에서 %d로 옮기시오" %(n,start,end)) # # else: # hanoi(n-1, start, mid, end) # hanoi(1, start, end, mid) # hanoi(n-1, mid , end, start) # # print(hanoi(2,1,3,2)) def hanoi(n,start,end,mid): if n: hanoi(n-1, start, mid, end) print("%d 디스크를 %d에서 %d로 옮기시오" %(n, start, end)) hanoi(n-1, mid , end, start) print(hanoi(3,1,3,2))
import tkinter as tk import os import sys import sqlite3 import argon2 ph = argon2.PasswordHasher() buttonValues = [] checkValues = [] #Connection to database connect = sqlite3.connect('users.db') cr = connect.cursor() command = """CREATE TABLE IF NOT EXISTS users(user_id INTEGER PRIMARY KEY, username TEXT, password TEXT)""" cr.execute(command) def change(button): """ State of clickable buttons. """ colour = 'white' if buttons[button]['bg'] == 'white': buttons[button].configure(bg='grey') colour = 'grey' else: pass buttons[button].configure(state='disabled') nrButton = str(button) value = nrButton + colour buttonValues.append(value) def checkUsername(username): """ Checks if username is available. """ cr.execute("SELECT username FROM USERS") usernames = cr.fetchall() for row in usernames: for names in row: if names == username: wrongInput.grid(column= 1, row=15) username = None return username def changeCheck(button): """ State of clickable check buttons. """ colour = 'white' if buttonsCheck[button]['bg'] == 'white': buttonsCheck[button].configure(bg='grey') colour = 'grey' else: pass buttonsCheck[button].configure(state='disabled') nrButton = str(button) value = nrButton + colour checkValues.append(value) def getUserName(): """ Gets username from user entry. """ username = userEntry.get() return username def click(): userName = getUserName() buttonValues.sort() checkValues.sort() condition = 0 if buttonValues == checkValues: values = ''.join(buttonValues) username = checkUsername(userName) while True: if username != None: if userName == username: hash = ph.hash(values) try: ph.verify(hash, values) condition = 1 break except: pass else: wrongInput.grid(column= 1, row=15) break if condition == 1: cr.execute("INSERT INTO users (username, password) VALUES (?,?)",(userName, hash)) connect.commit() window.destroy() else: wrongInput.grid(column= 1, row=15) else: wrongInput.grid(column= 1, row=15) def reset(): """ Resets the user entry by restarting the program. """ os.execl(sys.executable, sys.executable, *sys.argv) window = tk.Tk() window.geometry("300x400") tk.Label(font=('Arial', 10), text='Register a new user', padx=10, pady=10).grid(columnspan=2, row=0, sticky='n') frameUser = tk.Canvas(window, width=300, height=100) frameUser.grid(columnspan=3) framePassword1 = tk.Canvas(window, width=10, height=10) framePassword1.grid(columnspan=4) frameLabel = tk.Canvas(window, width=10, height=1) frameLabel.grid(columnspan=2) framePassword2 = tk.Canvas(window, width=10, height=10) framePassword2.grid(columnspan=4) tk.Label(frameUser, font=('Arial', 10), text='Username:', padx=10, pady=10).grid(column=0, row=2, sticky='e') content = tk.StringVar() userEntry = tk.Entry(frameUser, width=10) userEntry.grid(column=1, row=2, columnspan=3, sticky='w') aaBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(0)) aaBtn.grid(column=0, row=4, sticky='nse') abBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(1)) abBtn.grid(column=1, row=4, sticky='nsew') acBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(2)) acBtn.grid(column=2, row=4, sticky='nsew') adBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(3)) adBtn.grid(column=3, row=4, sticky='nsew') baBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(4)) baBtn.grid(column=0, row=5, sticky='nse') bbBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(5)) bbBtn.grid(column=1, row=5, sticky='nsew') bcBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(6)) bcBtn.grid(column=2, row=5, sticky='nsew') bdBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(7)) bdBtn.grid(column=3, row=5, sticky='nsew') caBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(8)) caBtn.grid(column=0, row=6, sticky='nse') cbBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(9)) cbBtn.grid(column=1, row=6, sticky='nsew') ccBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(10)) ccBtn.grid(column=2, row=6, sticky='nsew') cdBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(11)) cdBtn.grid(column=3, row=6, sticky='nsew') daBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(12)) daBtn.grid(column=0, row=7, sticky='ne') dbBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(13)) dbBtn.grid(column=1, row=7, sticky='new') dcBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(14)) dcBtn.grid(column=2, row=7, sticky='new') ddBtn = tk.Button(framePassword1, width=2, height=1, bg='white', command = lambda: change(15)) ddBtn.grid(column=3, row=7, sticky='new') tk.Label(frameLabel, font=('Arial', 10), text='Re-enter password:', padx=10, pady=10).grid(columnspan=2, row=3) #Check buttons eeBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(0)) eeBtn.grid(column=0, row=10, sticky='se') efBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(1)) efBtn.grid(column=1, row=10, sticky='sew') egBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(2)) egBtn.grid(column=2, row=10, sticky='sew') ehBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(3)) ehBtn.grid(column=3, row=10, sticky='sew') feBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(4)) feBtn.grid(column=0, row=11, sticky='nse') ffBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(5)) ffBtn.grid(column=1, row=11, sticky='nsew') fgBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(6)) fgBtn.grid(column=2, row=11, sticky='nsew') fhBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(7)) fhBtn.grid(column=3, row=11, sticky='nsew') geBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(8)) geBtn.grid(column=0, row=12, sticky='nse') gfBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(9)) gfBtn.grid(column=1, row=12, sticky='nsew') ggBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(10)) ggBtn.grid(column=2, row=12, sticky='nsew') ghBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(11)) ghBtn.grid(column=3, row=12, sticky='nsew') heBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(12)) heBtn.grid(column=0, row=13, sticky='nse') hfBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(13)) hfBtn.grid(column=1, row=13, sticky='nsew') hgBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(14)) hgBtn.grid(column=2, row=13, sticky='nsew') hhBtn = tk.Button(framePassword2, width=2, height=1, bg='white', command = lambda: changeCheck(15)) hhBtn.grid(column=3, row=13, sticky='nsew') buttons = [aaBtn, abBtn, acBtn, adBtn, baBtn, bbBtn, bcBtn, bdBtn, caBtn, cbBtn, ccBtn, cdBtn, daBtn, dbBtn, dcBtn, ddBtn] buttonsCheck = [eeBtn, efBtn, egBtn, ehBtn, feBtn, ffBtn, fgBtn, fhBtn, geBtn, gfBtn, ggBtn, ghBtn, heBtn, hfBtn, hgBtn, hhBtn] window.grid_columnconfigure(0, weight=1) window.grid_columnconfigure(4, weight=1) submitBtn = tk.Button(text='Submit',width=5,height=1, padx=10, command=click) submitBtn.grid(column=0, row=14, sticky='w') resetBtn = tk.Button(text='Reset entries',width=6,height=1, padx=10, command=reset) resetBtn.grid(column=1, row=14, sticky='e') wrongInput = tk.Label(font=('Arial', 10), text='Entries does not match or input is invalid, please reset and enter valid input.', padx=10, pady=10) window.mainloop()
import numpy as np from keras.models import Sequential from keras.layers.core import Activation, Dense from keras.optimizers import SGD, Adam from util.callback import WeightLogger # We are going to train a model to perform either an and/or/xor based upon the first # value in a 3D input. Value 0 identifies the operation. Values 1/2 are the inputs. Value # 3 is the output. X = np.zeros((12, 3)) y = np.zeros(12) # Set up the three truth tables # And X[0] = [0, 0, 0] y[0] = 0.0 X[1] = [0, 0, 1] y[1] = 0.0 X[2] = [0, 1, 0] y[2] = 0.0 X[3] = [0, 1, 1] y[3] = 1.0 # Or X[4] = [1, 0, 0] y[4] = 0.0 X[5] = [1, 0, 1] y[5] = 1.0 X[6] = [1, 1, 0] y[6] = 1.0 X[7] = [1, 1, 1] y[7] = 1.0 # Xor X[8] = [2, 0, 0] y[8] = 0.0 X[9] = [2, 0, 1] y[9] = 1.0 X[10] = [2, 1, 0] y[10] = 1.0 X[11] = [2, 1, 1] y[11] = 0.0 model = Sequential() # This model requires two layers. The first has 3D input and 4 neurons. model.add(Dense(4, input_dim=3, init='zero')) model.add(Activation('sigmoid')) # The second and output layer has a single output neuron for the binary classification model.add(Dense(1)) model.add(Activation('hard_sigmoid')) # Gradient descent. We don't use the defaults because for a simple model like this the Keras defaults don't work sgd = SGD(lr=0.1, decay=1e-6, momentum=.9) model.compile(loss='binary_crossentropy', optimizer=sgd, class_mode="binary") # Train the model and log weights model.fit(X, y, nb_epoch=1000, batch_size=4, show_accuracy=True, verbose=1, callbacks=[WeightLogger()]) # print the truth table output for our original X print model.predict(X)
s = input("Please enter a string: ") lenOfString = len(s) #print(lenOfString) maxLen = lenOfString // 2 #print(maxLen) numRepeat=0 for length in range(1, maxLen): subString = s[:length] #print(subString) for index in range[0,len(s), length]: segment = s[index: index + length] if subString != segment: numRepeat = 0 break else: numRepeat
n = int(input("Input a dimension: ")) for i in range (1, (n//2) + 1): for j in range(1, n+1): print(j**i, end="\t") print()
#Problem 4 lst = ['2','4','6','8','10'] def create_prefix_lists(lst): outlst = [[]] inlst = [] for i in range(len(lst)): inlst.append(lst[i]) outlst.append(inlst[:]) #inlst[:] is a copy of inlst and thus removes the issue of the changing inlst #print(inlst,'in') #print(outlst,'out') #inlst.append(lst[i]) print(outlst) create_prefix_lists(lst)
def sum_of_squares(lst): sum = 0 for element in lst: sum += element**2 print(sum) sum_of_squares([1,2,3,4,5])
#Problem 1 print("Kevin") #Problem 2 int1 = input("Please enter the first integer: ") int2 = input("Please enter the second integer: ") sum = int(int1) + int(int2) diff = int(int1) - int(int2) prod = int(int1)* int(int2) print("Their sum is: " , str(sum) + "," , "their difference is: " , str(diff) +"," , "their product is: ", str(prod)) #Problem 3 tempF = int(input("Please enter a Fahrenheit temperature: ")) tempC = int((tempF - 32) * (5/9)) print("In Celsius it is: " , str(tempC)+ ".", "In Fahrenheit it is: " + str(tempF) + ".") #Problem 4 weightlb = int(input("Please enter a weight in pounds: ")) weighto = int(weightlb * 16) weightkg = int(weightlb / 0.45) print((weightlb) , " pounds is equivalent to " , (weighto) , " and " , (weightkg) , " kilograms") #Problem 7 feet1 = int(input("Please enter the first length's feet: ")) feet2 = int(input("Please enter the second length's feet: ")) yard1 = int(input("Please enter the first length's yard: ")) yard2 = int(input("Please enter the second length's yard: ")) feetSum = int(feet1 + feet2) feetYard = int(feetSum/3) yardSum = int(feetYard + yard1 + yard2) feetLeft = int(yardSum % 3) print ("The sum is: " + str(yardSum) + " yards and " + str(feetLeft) + " feet") print("Finished with lab 1 :)")
def find_max_even_index(lst): max = 0 index = -1 for i in range(len(lst)): if lst[i] % 2 == 0: if lst[i] > max: max = lst[i] index = i print(index) find_max_even_index([56, 24, 58, 10, 33, 95]) find_max_even_index([3,5])
#Problem 3: Write a program that asks for the user’s name and prints a personalized welcome message for him. name = input("Please enter your name: ") print("Hi "+ name + ", Welcome to CS-UY 1114")
#Problem 2 n = int(input("Please enter an integer n: ")) times = 0 hold = n for i in range(n): times = (2*n) - 1 n = n - 1 print( (i * " ") + times * "*") while(n < hold): n = n + 1 times = (2*n) - 1 print((i * " ") + times * "*") i = i - 1
lst = [1,2,3,4,5,6,7,8] def circular_shift_list1(lst,k): newLst =[] newLst.extend(lst[-k:]) newLst.extend(lst[:-k]) print(newLst) circular_shift_list1(lst,3)
#Problem 3: Given sides and an angle in between calculate the third side and then make a turtle print the resulting triangle import math import turtle #inputs side1 = int(input("Please enter the length of side 1: ")) side2 = int(input("Please enter the length of side 2: ")) angle1 = int(input("Please enter the angle in between these two sides: ")) #calculations ( math.cos() takes radians!!!!! ) angle2Rad = math.radians(angle1) side3 = math.sqrt(side1**2 + side2**2 - 2*side1*side2*(math.cos(angle2Rad))) angle2 = math.degrees(math.acos( (side2**2 + side3**2 - side1**2) / (2*side2*side3) )) #turtle movements turtle.forward(side1) turtle.left(180 - angle1) turtle.forward(side2) turtle.left(180 - angle2) turtle.forward(side3) turtle.hideturtle() turtle.done()
#Problem 2 lst = ["a", "b", "10", "bab", "a"] val = "a" def find_all(lst,val): newlst = [] for i in range(len(lst)): if lst[i] == val: newlst.append(i) #newlst += [i] print(newlst) (find_all(lst,val))
#Problem 4: Write a program that takes years as input (as a integer) and prints out an estimated population (as an integer). year = int(input("Please enter the year: ")) currentYear = 2017 currentPop = 307357870 birth = int(31536000 / 7) death = int(31536000 / 13) immigrants = int(31536000 / 35) popChange = int( (year - currentYear) * ((birth + immigrants) - death) ) estPop = int(currentPop + popChange) print("The estimated population during", str(year), "is", str(estPop) + ".") #print(currentPop,popChange,estPop)
from datetime import timedelta TIME_ANGLE_RATIO = 0.25 # 90 degree for 360 minutes of time def sun_angle(time: str): sunrise = timedelta(hours=6, minutes=0) sunset = timedelta(hours=18, minutes=0) ar = time.split(":") now = timedelta(hours=int(ar[0]), minutes=int(ar[1])) angle = ((now - sunrise).total_seconds() / 60) * TIME_ANGLE_RATIO return angle if sunrise <= now <= sunset else "I don't see the sun!" if __name__ == '__main__': print("Example:") print(sun_angle("07:00")) # These "asserts" using only for self-checking and not necessary for auto-testing assert sun_angle("07:00") == 15 assert sun_angle("12:15") == 93.75 assert sun_angle("06:00") == 0 assert sun_angle("18:00") == 180 assert sun_angle("01:23") == "I don't see the sun!" assert sun_angle("00:00") == "I don't see the sun!" print("Coding complete? Click 'Check' to earn cool rewards!")
# https://py.checkio.org/mission/army-battles/publications/Phil15/python-3/army-with-3-properties-is_alive-warrior-pop/ class Warrior: def __init__(self, health=50, attack=5): self.health = health self.attack = attack @property def is_alive(self) -> bool: return self.health > 0 def __str__(self): return "H: " + str(self.health) + "; A: " + str(self.attack) class Knight(Warrior): def __init__(self): super().__init__(50, 7) class Army: def __init__(self): self.soldiers = [] def add_units(self, warrior: Warrior, count: int): self.soldiers += [warrior() for _ in range(count)] @property def is_alive(self) -> bool: """Does the army have a living warrior?""" return self.soldiers != [] @property def soldier(self) -> Warrior: """First warrior alive of the army""" return self.soldiers[0] @property def pop(self): """Pop a dead warrior out of the list""" self.soldiers.pop(0) def fight(unit_1, unit_2): """Duel fight: is unit 1 stronger than unit 2 ?""" while unit_1.is_alive and unit_2.is_alive: unit_2.health -= unit_1.attack unit_1.health -= unit_2.attack if unit_2.is_alive else 0 return unit_1.is_alive class Battle: def fight(self, army: Army, enemy: Army) -> bool: while army.is_alive and enemy.is_alive: if fight(army.soldier, enemy.soldier): enemy.soldiers.pop(0) else: army.soldiers.pop(0) return army.is_alive if __name__ == '__main__': # fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False # battle tests my_army = Army() my_army.add_units(Knight, 3) enemy_army = Army() enemy_army.add_units(Warrior, 3) army_3 = Army() army_3.add_units(Warrior, 20) army_3.add_units(Knight, 5) army_4 = Army() army_4.add_units(Warrior, 30) battle = Battle() assert battle.fight(my_army, enemy_army) == True assert battle.fight(army_3, army_4) == False print("Coding complete? Let's try tests!")
# https://py.checkio.org/mission/army-battles/publications/martin.pilka/python-3/army_1unitspop0/ class Warrior: """ Class Warrior, the instances of which will have 2 parameters - health (equal to 50 points) and attack (equal to 5 points), and 1 property - is_alive, which can be True (if warrior's health is > 0) or False (in the other case). """ def __init__(self, health: int = 50, attack: int = 5): self.health = health self.attack = attack @property def is_alive(self) -> bool: return self.health > 0 def fight(self, enemy): """ Every turn one of the warriors will hit another one and the last will lose his health in the same value as the attack of the first warrior. After that, the second warrior will do the same to the first one. If in the end of the turn the first warrior has > 0 health and the other one doesn’t, the function should return True, in the other case it should return False. """ while True: # we attack enemy.health -= self.attack if enemy.health <= 0: return True # enemy attacks self.health -= enemy.attack if self.health <= 0: return False class Knight(Warrior): """Knight, which should be the subclass of the Warrior but have the increased attack - 7.""" def __init__(self, health: int = 50, attack: int = 7): super().__init__(health, attack) class Army: """ The new class should be the Army and have the method add_units() - for adding the chosen amount of units to the army. """ def __init__(self): self.units = [] def add_units(self, unit, n): self.units.extend([unit() for _ in range(n)]) class Battle: """ Also you need to create a Battle() class with a fight() function, which will determine the strongest army. """ def fight(self, army_1: Army, army_2: Army) -> bool: """ The battles occur according to the following principles: at first, there is a duel between the first warrior of the first army and the first warrior of the second army. As soon as one of them dies - the next warrior from the army that lost the fighter enters the duel, and the surviving warrior continues to fight with his current health. This continues until all the soldiers of one of the armies die. In this case, the battle() function should return True, if the first army won, or False, if the second one was stronger. Note that army 1 have the advantage to start every fight! """ warrior_1 = army_1.units[0] if len(army_1.units) > 0 else None warrior_2 = army_2.units[0] if len(army_2.units) > 0 else None while warrior_1 and warrior_2: if warrior_1.fight(warrior_2): army_2.units.pop(0) warrior_2 = army_2.units[0] if len(army_2.units) > 0 else None else: army_1.units.pop(0) warrior_1 = army_1.units[0] if len(army_1.units) > 0 else None return warrior_1 is not None def fight(unit_1: Warrior, unit_2: Warrior): return unit_1.fight(unit_2)
# https://py.checkio.org/mission/double-substring/publications/StefanPochmann/python-3/4-problems-1-solution/share/af71a294ba1313bced37c36f80d834aa/ def longest_substring(string, predicate): n = len(string) for length in range(n, -1, -1): for start in range(n - length + 1): substring = string[start:start + length] if predicate(substring): return substring def repeat_inside(line): return longest_substring(line, lambda s: s in (s + s)[1:-1]) def non_repeat(line): return longest_substring(line, lambda s: len(s) == len(set(s))) def long_repeat(line): return len(longest_substring(line, lambda s: len(set(s)) < 2)) def double_substring(line): return len(longest_substring(line, lambda s: line.count(s) > 1 or not s)) if __name__ == '__main__': assert double_substring('aaaa') == 2, "First" assert double_substring('abc') == 0, "Second" assert double_substring('aghtfghkofgh') == 3, "Third" print('"Run" is good. How is "Check"?')
def checkio(matrix): return matrix == [list(map((-1).__mul__, reversed(sub))) for sub in list(reversed(matrix))] if __name__ == '__main__': assert checkio([ [0, 1, 2, 3, 4], [-1, 0, 5, 6, 7], [-2, -5, 0, 8, 9], [-3, -6, -8, 0, 0], [-4, -7, -9, 0, 0]]) == True, "4th example" # assert checkio([ # [0, 1, 2], # [-1, 0, 1], # [-2, -1, 0]]) == True, "1st example" # assert checkio([ # [0, 1, 2], # [-1, 1, 1], # [-2, -1, 0]]) == False, "2nd example" # assert checkio([ # [0, 1, 2], # [-1, 0, 1], # [-3, -1, 0]]) == False, "3rd example" print("Coding complete? Click 'Check' to earn cool rewards!");
from typing import List def checkio(puzzle: List[List[int]]) -> str: """ Solve the puzzle U - up D - down L - left R - right """ return "ULDR" if __name__ == '__main__': print("Example:") print(checkio([[1, 2, 3], [4, 6, 8], [7, 5, 0]])) #This part is using only for self-checking and not necessary for auto-testing GOAL = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] MOVES = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)} def check_solution(func, puzzle): size = len(puzzle) route = func([row[:] for row in puzzle]) goal = GOAL x = y = None for i, row in enumerate(puzzle): if 0 in row: x, y = i, row.index(0) break for ch in route: swap_x, swap_y = x + MOVES[ch][0], y + MOVES[ch][1] if 0 <= swap_x < size and 0 <= swap_y < size: puzzle[x][y], puzzle[swap_x][swap_y] = puzzle[swap_x][swap_y], 0 x, y = swap_x, swap_y if puzzle == goal: return True else: print("Puzzle is not solved") return False assert check_solution(checkio, [[1, 2, 3], [4, 6, 8], [7, 5, 0]]), "1st example" assert check_solution(checkio, [[7, 3, 5], [4, 8, 6], [1, 2, 0]]), "2nd example" print("Coding complete? Click 'Check' to earn cool rewards!")
def lesser(v1, v2): return v1 < v2 def greater(v1, v2): return v1 > v2 def find_min_max(comparator, *args, **kwargs): args = list(args[0]) if len(args) == 1 else args key = kwargs.get("key", lambda x: x) res = None for item in args: if res is None or comparator(key(item), key(res)): res = item return res min = lambda *args, **kwargs: find_min_max(lesser, *args, **kwargs) max = lambda *args, **kwargs: find_min_max(greater, *args, **kwargs) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert max(3, 2) == 3, "Simple case max" assert min(3, 2) == 2, "Simple case min" assert max([1, 2, 0, 3, 4]) == 4, "From a list" assert min("hello") == "e", "From string" assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items" assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key" print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
# https://py.checkio.org/mission/army-battles/publications/JimmyCarlos/python-3/army-battles/ class Warrior(object): def __init__(self): self.health = 50 self.attack = 5 @property def is_alive(self): """Boolean property to test if health is above 0.""" return self.health > 0 ################################################################################################### ################################################################################################### class Knight(Warrior): def __init__(self): self.health = 50 self.attack = 7 @property def is_alive(self): """Boolean property to test if health is above 0.""" return self.health > 0 ################################################################################################### ################################################################################################### class Army(object): def __init__(self): self.soldiers = [] def add_units(self,soldierToAdd,soldierToAdd_amount): """Adds in a soldier object to the army.""" if soldierToAdd == Warrior: for soldierToAdd_i in range(soldierToAdd_amount): self.soldiers.append(Warrior()) elif soldierToAdd == Knight: for soldierToAdd_i in range(soldierToAdd_amount): self.soldiers.append(Knight()) def __len__(self): return len(self.soldiers) ################################################################################################### ################################################################################################### class Battle(object): def __init__(object): pass def fight(self,army1,army2): """Simulate a battle between two soldiers. Return True if army1 won or False if army2 won.""" # Use assertion statements to check correct classes were passed in. assert type(army1) == Army assert type(army2) == Army while len(army1) > 0 and len(army2) > 0: is_soldier1_won = fight(army1.soldiers[0],army2.soldiers[0]) if is_soldier1_won: army2.soldiers.pop(0) else: army1.soldiers.pop(0) if len(army1) > 0: return True else: return False ################################################################################################### ################################################################################################### def fight(soldier1,soldier2): """Simulate a battle between two soldiers. Return True if soldier1 won or False if soldier2 won.""" # Use assertion statements to check correct classes were passed in. assert type(soldier1) in {Warrior,Knight} assert type(soldier2) in {Warrior,Knight} warriorNextToAttack = "soldier1" roundIndex = 0 while True: roundIndex += 1 if warriorNextToAttack == "soldier1": damageDealt = soldier1.attack soldier2.health -= damageDealt warriorNextToAttack = "soldier2" if not soldier2.is_alive: return True else: damageDealt = soldier2.attack soldier1.health -= damageDealt warriorNextToAttack = "soldier1" if not soldier1.is_alive: return False
# https://py.checkio.org/mission/speechmodule/publications/veky/python-3/first/ # migrated from python 2.7 def checkio(number): l=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"] d=dict(enumerate(l)) d.update({30:"thirty",40:"forty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety"}) h=number//100 if h: return (d[h]+" hundred "+checkio(number%100)).strip() if number in d: return d[number] return d[number//10*10]+" "+d[number%10] if __name__ == '__main__': assert checkio(4) == 'four', "First" assert checkio(133) == 'one hundred thirty three', "Second" assert checkio(12)=='twelve', "Third" assert checkio(101)=='one hundred one', "Fifth" assert checkio(212)=='two hundred twelve', "Sixth" assert checkio(40)=='forty', "Seventh, forty - it is correct" print('All ok')
# Basim Siddiqui # PSID: 1517778 #class from lab 10.17 class ItemToPurchase: def __init__(self, item_name = 'none', item_price = 0, item_quantity = 0, item_description = 'none'): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity self.item_description = item_description def print_item_cost(self): print(self.item_name + ' '+ str(self.item_quantity) + " @ $" + str(self.item_price) + " = $" + str(self.item_price * self.item_quantity)) def print_item_description(self): print(self.item_name + ": " + self.item_description) #new class class ShoppingCart: def __init__(self, customer_name = 'none', current_date = 'January 1, 2016', cart_items = []): self.customer_name = customer_name self.current_date = current_date self.cart_items = cart_items def add_item(self, new_item): self.cart_items.append(new_item) def remove_item(self): print('REMOVE ITEM FROM CART') remove_name = input("Enter name of item to remove:\n") for items in self.cart_items: if items.item_name == remove_name: self.cart_items.remove(items) iteration = True break else: iteration = False if iteration == False: print("Item not found in cart. Nothing removed.") def modify_item(self): print('CHANGE ITEM QUANTITY') name = input('Enter the item name:\n') new_num = int(input('Enter the new quantity:\n')) for items in self.cart_items: if (items.item_name == name): items.item_quantity = new_num iteration = True break else: iteration = False if (iteration == False): print("Item not found in cart. Nothing modified.") def get_num_items_in_cart(self): num_items = 0 for items in self.cart_items: num_items = num_items + items.item_quantity return num_items def get_cost_of_cart(self): total_cost = 0 for items in self.cart_items: item_cost = (items.item_quantity * items.item_price) total_cost += item_cost return total_cost def print_total(self): total_cost = self.get_cost_of_cart() if total_cost == 0: print('SHOPPING CART IS EMPTY') else: self.output_shopping_cart() def print_descriptions(self): print('\nOUTPUT ITEMS\' DESCRIPTIONS') print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date), end='\n') print('\nItem Descriptions') for items in self.cart_items: print('{}: {}'.format(items.item_name, items.item_description), end='\n') def output_shopping_cart(self): new = ShoppingCart() print('OUTPUT SHOPPING CART') print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date), end='\n') print('Number of Items:', new.get_num_items_in_cart(), end='\n\n') self.total_cost = self.get_cost_of_cart() if (self.total_cost == 0): print('SHOPPING CART IS EMPTY') else: pass tc = 0 for items in self.cart_items: print('{} {} @ ${} = ${}'.format(items.item_name, items.item_quantity, items.item_price, (items.item_quantity * items.item_price)), end='\n') tc += (items.item_quantity * items.item_price) print('\nTotal: ${}'.format(tc), end='\n') def print_menu(ShoppingCart): customers_cart = new_cart string = '' menu = ('\nMENU\n' 'a - Add item to cart\n' 'r - Remove item from cart\n' 'c - Change item quantity\n' "i - Output items' descriptions\n" 'o - Output shopping cart\n' 'q - Quit\n') command = '' while (command != 'q'): string = '' print(menu, end='\n') command = input('Choose an option:\n') while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'): command = input('Choose an option:\n') if (command == 'a'): print('ADD ITEM TO CART') item_name = input("Enter the item name:\n") item_description = input("Enter the item description:\n") item_price = int(input("Enter the item price:\n")) item_quantity = int(input("Enter the item quantity:\n")) new_item = ItemToPurchase(item_name, item_price, item_quantity, item_description) customers_cart.add_item(new_item) if (command == 'o'): customers_cart.output_shopping_cart() if (command == 'i'): customers_cart.print_descriptions() if (command == 'r'): customers_cart.remove_item() if (command == 'c'): customers_cart.modify_item() if __name__ == "__main__": customer_name = str(input("Enter customer's name:")) current_date = str(input("\nEnter today's date:\n")) print('\nCustomer name:', customer_name, end='\n') print("Today's date:", current_date, end='\n') new_cart = ShoppingCart(customer_name, current_date) print_menu(new_cart)
# def lista(txt): # i=0 # l=len(txt) # lisdev=[] # while i<l: # if len(txt[i:i+2])<2: # lisdev.append(txt[i:i+2]+"_") # else: # lisdev.append(txt[i:i+2]) # i=i+2 # return lisdev # a="algun perr" # print(lista(a)) # def dividirdeados(cadena): # lista=list() # # if len(cadena)%2!=0 :cadena.append("_") # for i in range(0,len(cadena)-1,2): # lista.append(cadena[i:i+2]) # if len(cadena)%2!=0 :lista.append(cadena[-1]+"_") # return lista # print(dividirdeados("Un ejemplo")) # print(dividirdeados("Este es un ejemplo")) # print(dividirdeados("Un ejemplar")) # def fun1Recursivo(param): # if len(param)<=2: # return [(param+"_")[:2]] # else: # return [param[:2]]+fun1Recursivo(param[2:]) # print(fun1Recursivo("Un ejemplo")) # print(fun1Recursivo("Este es un ejemplo")) # print(fun1Recursivo("Un ejemplar")) # def imprimeDeADos(cadena): # lista = [] # for i in range(0, len(cadena), 2): # lista.append(cadena[i:i+2].ljust(2, "_")) # return lista # cadena = "esta es una caden" # print(imprimeDeADos(cadena)) def cantidad_de_puntos_al_inicio(cadena): i=0 while(cadena[i]=="."): i+=1 return i # print(cantidad_de_puntos_al_inicio(".....casa")) cadena=".....casa" def puntos(cadena): largo=0 for i in cadena: if i == '.': largo+=1 else: break return largo # print(puntos(".....casa")) def cantidad_puntos_al_inicio(cadena): count_puntos = 0 for item in cadena: if item == "." : count_puntos += 1 else: return count_puntos # print(cantidad_puntos_al_inicio(".....casa")) # def contarPuntos(cadena): # i=0 # i=cadena.count(".") # return i # cadena="...c...adena" # cantidadDePuntos=contarPuntos(cadena) # print("Cantidad de Puntos: ", cantidadDePuntos) def devolverNumCercano(conjunto,numero): i=0 listaValor=[] listaResu=[] for d in conjunto: res=abs(numero-d) if (res)>=0: listaValor.append(d) listaResu.append(res) else: return d i+=1 valorMinimo=min(listaResu) indiceDelMinimo=listaResu.index(valorMinimo) valorCercano=listaValor[indiceDelMinimo] return valorCercano # conj1=[12,108, 232,33422,34,5,56] # conj1=[140, 130, 120] # valor=109 # valorCercano=devolverNumCercano(conj1,valor) # print("Valor Cercano: ",valorCercano) def invierte_cadena(cadena): #salida=[str(item) for item in cadena[::-1]] salida = "".join([str(item) for item in cadena[::-1]]) return salida # print(invierte_cadena("asdfg hjkl")) # print("asdfg hjkl"[::-1]) def invertir_palabras(cadena): cadenainvertida ="" for palabra in cadena.split(): cadenainvertida = cadenainvertida + " " + palabra[::-1] return cadenainvertida.strip() # cadena="Esto es un ejemplo" # print(invertir_palabras(cadena)) def contarDigitos(cadena): digitos=0 for i in cadena: if i.isdigit(): digitos+=1 return digitos def cantidad_de_digitos(cadena): cantidaddedigitos=0 for palabra in cadena.split(): if palabra.isnumeric(): cantidaddedigitos+=len(palabra) return cantidaddedigitos # print(contarDigitos("Acá tenemos 223 dígi333to00s")) # print(cantidad_de_digitos("Acá tenemos 223 dígi333to00s")) def encontrar_caros(cantidad, *lista): listaordenada = sorted(lista, key=lambda i: i["pre"], reverse=True) return listaordenada[:cantidad] # print(encontrar_caros(2,{"prod":"pan", "pre": 100}, {"prod":"arroz", "pre": 50}, {"prod":"leche", "pre": 90}, {"prod":"carne", "pre": 300})) # print(encontrar_caros(5,[{"prod":"pan", "pre": 100}, {"prod":"arroz", "pre": 50}, {"prod":"leche", "pre": 90}, {"prod":"carne", "pre": 300}])) # print(encontrar_caros(1,[{"prod":"pan", "pre": 100}, {"prod":"arroz", "pre": 50}, {"prod":"leche", "pre": 90}, {"prod":"carne", "pre": 300}])) # print(encontrar_caros(0,[{"prod":"pan", "pre": 100}, {"prod":"arroz", "pre": 50}, {"prod":"leche", "pre": 90}, {"prod":"carne", "pre": 300}])) def segundaOcurrencia(c1, c2): import re l2= [m.start() for m in re.finditer(c2, c1)] if (len(l2)>=2): return (l2[1]) else: return None # s1 = 'Esta es una frase que queremos encontrar' # s2 = 'que' # print(segundaOcurrencia(s1,s2)) def busco_cadena(cadena1,cadena2): if cadena1.count(cadena2) <= 1: retorno="None" else: indice=cadena1.find(cadena2)+1 retorno=cadena1.find(cadena2,indice) return retorno # print(busco_cadena("Esto es una estatua", "st")) s1 = 'Esta es una frase que queremos encontrar' s2 = 'que' print(busco_cadena(s1,s2))
print("What do you like to purchase: ") search = input() itemList=["Dalmot", "Chauchau", "Chips","Juice"] itemPrice = {'Dalmot' :100, 'Chauchau' :20, 'Chips':50, 'Juice':100 } if search in itemList: print("Available") print("Price of: " + search + " is " + str(itemPrice[search])) else: print("Sorry! Not Available")
from typing import List, Dict class Solution: # O(log(n)) - time, O(1) - space def binarySearchIterate(self, nums: List[int], target: int): left=0 right=len(nums) - 1 if left > right: return -1 while left <= right: middle = (left + right) // 2 match = nums[middle] if target == match: return middle elif target < match: right = middle - 1 else: left = middle + 1 return -1 # O(log(n)) - time, O(log(n)) - space def binarySearchRecurse(nums: List[int], target: int): return binarySearchRecurseUtil(nums, target, 0, len(nums) - 1) def binarySearchRecurseUtil(nums: List[int], target: int, left, right): if left > right: return -1 middle = (left + right) // 2 match = nums[middle] if target == match: return middle elif target < match: return binarySearchRecurseUtil(nums, target, left, middle - 1) else: return binarySearchRecurseUtil(nums, target, middle + 1, right)
import numpy as np import random def print_header(): print("\t What is the number you want the computer to guess?!") print("\t Your number must be between 1 and 100") print("\t If your number is higher type h, if your number is lower type l.") def main(): # prints the greeting banner print_header() your_number = int(input("What is your number:")) computer_guess = np.random.randint(1, 100) max_guess = 101 min_guess = 0 while True: print("The computer guess is:", computer_guess, "Your number is:", your_number) response = input() response.lower() if response == "h": min_guess = computer_guess computer_guess = ((min_guess + 1 + max_guess - 1) // 2) if response == "l": max_guess = computer_guess computer_guess = ((min_guess + 1 + max_guess - 1) // 2) if response == "You got it!": print("I knew I would out smart you!") print("Thanks for playing!") break
import random import sys #print(sys.getrecursionlimit()) sys.setrecursionlimit(11000000) #print(sys.getrecursionlimit()) def ordenamiento_de_burbuja(lista): n = len(lista) for i in range(n): for j in range(0, n-i-1): # O(n) * O(n) = O(n*n) =O(n)**2 if lista[j] > lista[j + 1]: lista[j], lista[j+1] = lista[j+1], lista[j] return lista if __name__ == '__main__': list_size = int(input('De que tamano sera la lista? ')) lista = [random.randint(0, 100) for i in range(list_size)] print(lista) lista_ordenada = ordenamiento_de_burbuja(lista) print(lista_ordenada)
##balance = 4213 ##annualInterestRate = .2 ##monthlyPaymentRate = .04 ##numberMonths = 12 ##i = 0 ##totalPaid = 0 ## ##while i < numberMonths: ## minMonthPay = balance*monthlyPaymentRate ## balance = (balance - minMonthPay)* (1 + annualInterestRate/12) ## i += 1 ## totalPaid = totalPaid + minMonthPay ## print('Month:' + str(i)) ## print('Minimum monthly payment: ' + str(round(minMonthPay,2))) ## print('Remaining balance: ' + str(round(balance,2))) ## ##print('Total paid: ' + str(round(totalPaid,2))) ##print('Remaining balance: ' + str(round(balance,2))) ##balance = 3329 ##annualInterestRate = .2 ##minMonthPay = 10 ##totalPaid = 0 ##unpaid = balance ##numberMonths = 12 ##while unpaid > 0: ## i = 0 ## minMonthPay = minMonthPay + 10 ## print(minMonthPay) ## print(i) ## print('balance is ' + str(balance)) ## unpaid = balance ## totalPaid = 0 ## while i < numberMonths: ## ## ## unpaid = (unpaid - minMonthPay)* (1 + annualInterestRate/12) ## i += 1 ## totalPaid = totalPaid + minMonthPay ## print('totalPaid is ' + str(totalPaid)) ## print('unpaid is ' + str(unpaid)) ## ##print('Lowest Payment: ' + str(minMonthPay)) ## ## Bisection method balance = 320000 annualInterestRate = .2 lowerBound = balance/12 upperBound = (balance*(1 + annualInterestRate/12.0)**12)/12 totalPaid = 0 unpaid = balance numberMonths = 12 ans = (upperBound + lowerBound)/2.0 while abs(unpaid) > 0.01: i = 0 unpaid = balance while i < numberMonths: unpaid = (unpaid - ans)* (1 + annualInterestRate/12) i += 1 totalPaid = totalPaid + ans ## print('totalPaid is ' + str(totalPaid)) ## print('unpaid is ' + str(unpaid)) ## print(unpaid) ## print('upper is' + str(upperBound)) ## print('lower is' + str(lowerBound)) if unpaid > 0: lowerBound = ans ## print('lower is' + str(lowerBound)) ans = (upperBound + lowerBound)/2.0 else: upperBound = ans ## print('upper is' + str(upperBound)) ans = (upperBound + lowerBound)/2.0 ## print(ans) ## print('balance is ' + str(balance)) totalPaid = 0 ## print(unpaid) print('Lowest Payment: ' + str(round(ans,2)))
#2794 arr=[] for i in range(3): line=input('').split(' ') arr.append(int(line[0])) arr.append(int(line[1])) for elem in arr: if arr.count(elem)==1: if arr.index(elem)%2==0: x=elem else: y=elem print(x,y)
s1=input('') s2=input('') if s1[0]==s2[-1]: print('YES') else: print('NO')
word1 = input('') sentence1 = input('') if word1 in sentence1: print(1) else: print(0)
def compare(string1, string2): i=0 while len(string1)>0 and len(string2)>0: if string1[i]>string2[i]: string2=string2[i+1:] elif string1[i]<string2[i]: string1=string1[i+1:] else: string1=string1[i+1:] string2=string2[i+1:] string1=string1[::-1] string2=string2[::-1] string1=string1[::-1] string2=string2[::-1] return string1 if len(string1)>0 else 'Both strings are empty!' if len(string2)==0 else string2 # output = compare('ali', 'salib') # 'las' # output = compare('amin', 'nima') # 'Both strings are empty!' # print(output)
a = str(input('')) b = str(input('')) # if a==b: # print("{} = {}".format(a,b)) # else: # print("{} {} {}".format(max(a,b),'<',min(a,b))) a1=list(a) a1.reverse() b1=list(b) b1.reverse() a2=int(''.join(a1)) b2=int(''.join(b1)) # print(a2,b2) if a2<b2: print("{} < {}".format(a,b)) if b2<a2: print("{} < {}".format(b,a)) if a2==b2: print("{} = {}".format(a,b))
s=list(input('')) count=0 for i in s: if i=='a' or i=='e' or i=='i' or i=='o' or i=='u': count=count+1 print(2**count)
n = int(input('')) mainStr = input('') artStudentStr = input('') numberOfFailure = 0 for index in range(len(mainStr)): if mainStr[index]!=artStudentStr[index]: numberOfFailure = numberOfFailure+1 print(numberOfFailure)
n = int(input('')) arr = [] for i in range(n): arr.append(int(input(''))) average = sum(arr)//n times =0 for val in arr: times = times + ((val-average) if (val-average)>0 else 0) print(times)
## https://leetcode.com/problems/reverse-bits/ class Solution: def reverseBits(self, n: int) -> int: reverse = bin(n)[::-1][:-2] reverse += "0"*(32-len(reverse)) return int(reverse,2) ####### Another approach ###### ## https://leetcode.com/problems/reverse-bits/ class Solution: def reverseBits(self, n: int) -> int: rev = "" while n: if n % 2 == 1: rev += "1" else: rev += "0" n >>= 1 rev += "0" * (32-len(rev)) return int(rev,2) ### Another approach ### class Solution: def reverseBits(self, n: int) -> int: i = 0 rev = 0 while i < 31: bit = n & 1 rev = rev | bit n >>= 1 rev <<= 1 i += 1 return rev