text
stringlengths
37
1.41M
from tkinter import * root=Tk() root.title("Calculator") #creating title of gui root.geometry("500x500") #dimension of gui root.minsize(500,500) root.maxsize(500,500) root.iconbitmap('D:\pes.ico') #icon strvalue=StringVar() #string variable strvalue.set("") #value is intially null text1=Label(text="Let's calculate",fg="black",font="lucida 15 italic") text1.pack() screen=Entry(root,textvar=strvalue,font="lucida 33 bold",borderwidth=5,relief=SUNKEN) #screen of calculator screen.pack(fill=X,ipadx=5,pady=5,padx=5) #packing the gui root.mainloop()
#Program that Remove Duplicates from the Array #Here are the Names original_names = ["Alex", "John", "Mary", "Steve", "John", "Steve"] #Loop through each Name, drop that name into a new array if the new array does not already contain that name (value). final_names = [] for i in original_names: if i not in final_names: final_names.append(i) print(final_names)
from cards import Card from deck import Deck deal_amount = [] def lucky_card(): d = Deck() d.shuffle() try: user = input("Hello! What's your name? ") deal_amount = int(input(f"How many random cards would you like to be dealt {user}? ")) if deal_amount >= 53: print("There are only 52 cards in a deck!") elif deal_amount == 1: print(f"Here is your lucky card {user} ", d._deal(deal_amount)) elif deal_amount <= 1: print("You have to enter positive number, there isn't a negative suit.") elif 52 >= deal_amount > 1: print(f"Here are your {deal_amount} lucky cards {user}", d._deal(deal_amount)) except ValueError: print("Next Time Enter a Number!") lucky_card() #CODE BELOW WAS ME TROUBLE SHOOTING AND I DECIDED TO INCLUDE IT IN THIS FILE #LEARNING OOP HAS BEEN FUN AND I WANT TO LOOK BACK AT MISTAKES. # def user_name(): # user = input("Hello! What's your name? ") # deal_amount = int(input(f"How many random cards would you like to be dealt {user}? ")) # if deal_amount > 52: # print("There are only 52 cards in a deck!") # return deal_amount # d = Deck() # d.shuffle() # # x # print("Here are your ", user_name(), " lucky cards! ", d._deal(user_name())) # print(user_name()) # print(f"There are {user_name()} cards left in the thing") # The below code I could not get to display the ValueError code. # def lucky_card(): # d = Deck() # d.shuffle() # user = input("Hello! What's your name? ") # deal_amount = int(input(f"How many random cards would you like to be dealt {user}? ")) # if deal_amount == ValueError: # print("You have to enter a number!") # elif deal_amount >= 53: # print("There are only 52 cards in a deck!") # elif deal_amount == 1: # print(f"Here is your lucky card {user} ", d._deal(deal_amount)) # elif deal_amount <= 1: # print("You have to enter positive number, there isn't a negative suit.") # elif 52 >= deal_amount > 1: # print(f"Here are your {deal_amount} lucky cards {user}", d._deal(deal_amount)) # lucky_card() #tried this too # elif deal_amount.isalnum: # print("You have to enter a number!") # elif deal_amount.isalpha: # print("You have to enter a number!")
file_name = "emails.txt" duplicate_free_emails = [] with open(file_name) as file_object: content = file_object.read() # print(content) emails = content.split(", ") # print(emails) for email in emails: if email not in duplicate_free_emails: duplicate_free_emails.append(email) print(duplicate_free_emails) #Run our own local test to see if split function works. # fake_emails = "Johndoe@gmail.com, maryjoe@gmail.com" # print(fake_emails.split(", "))
i1=input('enter radius:') r=float(i1) c=2*3.14*r print('circumference of circle=',c)
""" 1281. Subtract the Product and Sum of Digits of an Integer """ def sum_product(nums): sum=0 product = 1 final_op=0 for i in nums: sum = sum + i product = product * i final_op=sum + product return final_op if __name__ == '__main__': nums = 234 op = sum_product(nums) print(op)
def binary_search(elem,val,low,high,mid): while(low <=high): mid = low + high // 2 if mid == val: return val elif mid < val : low = mid + 1 else: high = mid -1 return -1 if __name__=="__main__": elem = [22,1,45,78,25] low =0 mid =0 val =10 high = len(elem) - 1 number =binary_search(elem,val,low,high,mid) print(number)
""" 1304. Find N Unique Integers Sum up to Zero """ class Solution: def sumZero(self, n: int): if n==1: return [0] elif n%2==0: result=[] for i in range(1,n//2+1): result.append(i) result.append(-i) else: result=[] for i in range(1,n//2+1): result.append(i) result.append(-i) result.append(0) return result s=Solution() print(s.sumZero(5))
""" Design an OrderedStream """ class OrderedStream: def __init__(self, n: int): self.n=n def insert(self, idKey: int, value: str) -> List[str]: res=[] for i in range(self.value): if idkey==i: if len(res)>0: return res else: return value else: res.append(value)
""" 9. Palindrome number """ def palindrome_check(n,x): if n==x: return True else: return False class Solution: def isPalindrome(self, x: int) -> bool: rev,pop=0,0 y=x if x < 0: return False while x > 0: pop = x%10 x=x//10 rev = rev*10+ pop return palindrome_check(rev,y) s=Solution() print(s.isPalindrome(10))
""" 1403. Minimum Subsequence in Non-Increasing Order """ class Solution: def minSubsequence(self, nums): temp=[] nums.sort(reverse=True) for i in range(len(nums)): if sum(nums[:i+1]) > sum(nums[i+1:]): temp.append(nums[:i+1]) return temp[0] s=Solution() print(s.minSubsequence([4,3,10,9,8]))
""" 10. Regular Expression Matching """ def all_check(s): for i in s: if i == '*': class Solution: def isMatch(self, s: str, p: str) -> bool: if len(s) < 0 or len(s) > 20: return 'false' if len(p) < 0 or len(p) > 30: return 'false' if s.isupper: return 'false' if p.isupper: return 'false' for i in p:
#program to rotate array by n index print("Enter the index rotation value") n = 2 array_no = [1,2,3,4,5] ar_len = len(array_no) print(ar_len) last = array_no[-1] for i in range(ar_len-1): array_no[i+1] = array_no[i] array_no[0] = last print(array_no)
""" There are n flights, and they are labeled from 1 to n. We have a list of flight bookings.The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive. Return an array answer of length n, representing the number of seats booked on each flight in order of their label. """ class Solution: def corpFlightBookings(self, bookings,n): flight_number={} for i in bookings: for j in range(len(i)): value =0 value_temp = i[-1] * j value = value + value_temp flight_number[j]=value return flight_number s1=Solution() detail=s1.corpFlightBookings([[1,2,10],[2,3,20],[2,5,25]],5) print(detail)
""" divisor Game """ class Solution: def divisorGame(self, N: int) -> bool: return N%2==0 s=Solution() print(s.divisorGame(3))
""" Three Sum Problem """ class Solution: def threeSum(self, nums): nums.sort() res=set() for i in range(len(nums)-2): x=i+1 y=len(nums)-1 while x<y: if nums[x]+nums[y]+nums[i]==0: res.add((nums[x],nums[y],nums[i])) x+=1 y-=1 elif nums[x]+nums[y]+nums[i]<0: x+=1 else: y-=1 return list(res) s=Solution() print(s.threeSum([-1,0,1,2,-1,-4]))
""" 1299. Replace Elements with Greatest Element on Right Side """ class Solution: def replaceElements(self, arr): res=[] for i in range(1,len(arr)): sort_ele=max(arr[i:]) res.append(sort_ele) print(sort_ele) res.append(-1) return res s=Solution() print(s.replaceElements([17,18,5,4,6,1]))
class Node: def __init__(self,data): self.data =data self.next = None class Queue: def __init__(self): self.head = None def push_ele(self,data): newnode = Node(data) if self.head = None: self.head = newnode else: newnode.next = self.head self.head = newnode
""" Trie Data Structure """ class TrieNode: def __init__(self): self.children=None self.iswordend=False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root=TrieNode() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ currnode=self.root for ch in word: #dic.get(parameter, default value) node=currnode.children.get(ch,TrieNode()) currnode.children[ch]=node currnode=node currnode.iswordend=True def search(self, word: str) -> bool: """ Returns if the word is in the trie. we will start from root node and check for all the characters if we could not find a node for a character we will return False there once we iterate through all character we will check if that is a word end """ currnode=self.root for ch in word: node=currnode.children.get(ch) if node is None: return False return currNode.isWordEnd def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ currnode=self.root for ch in prefix: node=currnode.children.get(ch) if not node: return False currnode=node return True
""" 1078. Occurrences After Bigram """ class Solution: def findOcurrences(self, text: str, first: str, second: str): text=text.split(" ") res=[] for i in range(len(text)-2): if first==text[i] and second==text[i+1]: res.append(text[i+2]) return res s=Solution() print(s.findOcurrences("alice is a good girl she is a good student","a","good"))
""" Heap and operation """ import heapq arr=[1,1,1,2,2,3,-2,-3] k=3 heapq.heapify(arr) print(heapq.nlargest(k,arr)) print(heapq.nsmallest(k,arr))
#Create an Array of Five Students #Name, Age, GPA - Unique GPAs ''' testArray = [["Adam", 25, 3.0], ["Carl", 24, 4.0], ["Bart", 23, 3.5], ["Deng", 22, 2.5], ["Eden", 21, 2.0]] ''' #Name, Age, GPA - GPA gets repeated. Sorting on Name ''' testArray = [["Adam", 25, 3.0], ["Bart", 24, 4.0], ["Carl", 23, 4.0], ["Deng", 22, 2.0], ["Eden", 21, 2.0]] ''' #Name, Age, GPA - GPA gets repeated. Sorting on Name and Age testArray = [["Adam", 25, 3.0], ["Bart", 24, 4.0], ["Carl", 23, 4.0], ["Deng", 22, 2.0], ["Deng", 21, 2.0]] #Sort by GPA in Increasing Order. Implies that the Lowest GPA should come first sorted_list = sorted(testArray, key=lambda x:(x[2], x[0], x[1])) print "Test Array is: ", testArray print "Sorted List is: ", sorted_list
#Student Class class Student(object): #Defining the Init Method def __init__(self, name, gpa, age): self.name = name self.gpa = gpa self.age = age #__str__() def __str__(self): print "_str__ Invoked" return "Data is: {" + str(self.name) + "," + str(self.gpa) + "," + str(self.age) + "}" #__lt__ def __lt__(self, other): print "__lt__ Invoked" return self.gpa < other.gpa #__eq__() def __eq__(self, other): print "__eq__ invoked" return ((self.name.lower(), self.gpa, self.age) == (other.name.lower(), other.gpa, other.age)) #__hash__() def __hash__(self): print "__hash__ invoked" return hash(self.name and self.gpa and self.age) def __cmp__(self, other): print "__cmp__ invoked" if self.gpa < other.gpa: return self.gpa else: return cmp(self.gpa, other.gpa) def __repr__(self): return '{}: {} {} {}'.format(self.__class__.__name__,self.name,self.gpa,self.age) ################################## print "--------------------------------" #Dict Function Test with the Student Object print "DICT TEST" student0_1 = Student("Adam", 4.0, 25) print "Dict Test Result: ", student0_1.__dict__ print "--------------------------------" print "--------------------------------" #Hash Function Test with Sorted: print "HASH TEST" studentList_1 = [ Student("Bart", 2.0, 21), Student("Carl", 3.0, 23), Student("Adam", 4.0, 25) ] print "Hash Test Result: ", sorted(studentList_1, key=Student.__hash__) print "--------------------------------" print "--------------------------------" #Sort Function Test: print "SORT TEST" studentList_2 = [Student("Bart", 2.0, 21), Student("Carl", 3.0, 23), Student("Adam", 4.0, 25)] print "Sort Test Result: ", studentList_2.sort() studentList_2.sort() studentSortResult = "" for student in studentList_2: studentSortResult += "%s " % student print studentSortResult print "--------------------------------" print "--------------------------------" #Test Case for String: print "STRING TEST" studentString = Student("Adam", 4.0, 25) print "String Test Result: ", str(studentString) print "--------------------------------" #Test Case for LESS THAN Test: print "--------------------------------" print "LESS THAN TEST" student1_1 = Student("Bart", 3.0, 23) student1_2 = Student("Adam", 4.0, 25) print "Expecting FALSE. Result is: ", student1_2 < student1_2 print "Expecting TRUE. Result is: ", student1_1 < student1_2 print "--------------------------------" print "--------------------------------" #Test Case for EQUAL Test: print "EQUAL TEST" student3 = Student("Bart", 3.0, 23) student4 = Student("Adam", 4.0, 25) student5 = Student("Adam", 4.0, 25) print "Expecting FALSE. Result is: ", student4 == student3 print "Expecting TRUE. Result is: ", student4 == student5 print "--------------------------------"
from lib.tree import BinaryTree def height(node): height = 0 while node.parent is not None: node = node.parent return height def lowest_common_ancestor(node1, node2): h1, h2 = height(node1), height(node2) if h1 > h2: h1, h2 = h2, h1 node1, node2 = node2, node1 for _ in range(h2 - h1): node2 = node2.parent while node1 is not node2: node1 = node1.parent node2 = node2.parent return node1 tree = BinaryTree('4,10,12,14,15,16,20,21') a = tree.root.left.left b = tree.root.right.right assert lowest_common_ancestor(a, b).data == '14'
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 13:54:13 2019 @author: AbeerJaafreh """ print('Q1------------------------------------------------') class Employee(): def __init__(self, EmpNumber, Name,Address,Salary,jobTitle): self.empNumber=EmpNumber self.__name=Name self.__address=Address self.__salary=Salary self.__job=jobTitle def getName(self): return self.__name def getAddress(self): return self.__address def getSalary(self): return self.__salary def getJobTitle(self): return self.__job def setAddress(self,newAddress): self.__address=newAddress def __del__(self): print(self.getName(),'have been deleted') def getPrint(self): return self.empNumber return self.__name return self.__address return self.__salary return self.__job emp=Employee(1,"Abeer","Amman",300,"programmer") print("ID : ",emp.empNumber) print("Name : ",emp.getName()) print("Address :",emp.getAddress()) emp.setAddress("Karak") print("New Address :",emp.getAddress()) print("Salary : ",emp.getSalary()) print("Job Title : ",emp.getJobTitle()) del emp print("\n \n") print('Q2 create new Object------------------------------------------------') Employee1=Employee(1,"Mohammad Khalid","Amman, Jordan",500,"Consultant") Employee2=Employee(2,"Hala Rana","Aqaba, Jordan",750,"Manager") print("\n \n") print('Q3------------------------------------------------') print("Employee 1 Information ") print(" Employee Number : ",Employee1.empNumber) print(" Name : ",Employee1.getName()) print(" Address : ",Employee1.getAddress()) print(" Salary : ",Employee1.getSalary()) print(" Job Title : ",Employee1.getJobTitle(),"\n") print("Employee 2 Information ",end="") print(" Employee Number :",Employee2.empNumber,end="") print(" Name :",Employee2.getName(),end="") print(" Address :",Employee2.getAddress(),end="") print(" Salary :",Employee2.getSalary(),end="") print(" Job Title :",Employee2.getJobTitle()) print("\n \n") print('Q4------------------------------------------------') Employee1.setAddress("USA") print("\n \n") print('Q5------------------------------------------------') print("Employee 1 New Address :",Employee1.getAddress()) print("\n \n") print('Q6------------------------------------------------') del Employee1,Employee2
# The deal_cards function deals a specified numberr of cards from the deck def deal_cards(deck, number): # Initialize an accumulator for the hand value. hand_value = 0 # Make sure the number of cards to deal is not geater tham the number of cards in the deck. if number > len(deck): number = len(deck) # Deal the cards and accumulate their values for count in range(number): card, value = deck.popitem() print(card) hand_value += value #Display the value of the hand. print('Value of this hand:', hand_value) # Call the main function main()
""" ###function_demo #This program demonstates a function. #First, we define a function named message. def message(): print('I am Arthur.') print('King of the Britons.') #call the message function. message() """ """ ##two_functions #This program has two functions. First we define the main function. def main(): print('I have a messgae for you. ') message() print('Goodbye!') #Next we define the message function. def message(): print('I am Arthut. ') print('King of the Britons.') #calll the main function. main() """ """ ##bad_local #Definition of the main function. def main(): get_name() print('Hello', name) # This causes an error! # Definition of the get_name function. def get_name(): name = input('Enter your name: ') #call the main function main() """ """ ##Birds. #This program demonstrates two functions that have local variable with the same name def main(): # Call the texas function. texas() # Call the california function. california() # Definition of the texas function. It creates a local variable named birds. def texas (): birds = 5000 print('texas has', birds, 'birds.') #Definition of the california function. It also creates a local variable named birds. def california(): birds = 8000 print('california has', birds, 'birds.') #Call the main function main() """ """ ##pass_args #This program demonstrates an argument being passed to a function def main(): value = 5 show_double{value} #The show_double function accepts an argument and displays double its value def show_double(number): result = number* 2 print(result) # Call the main function main() """ """ ##cups_to_ounces #This program converts cups to fluid ounces def main(): #display the intro screen intro() #Get the number of cups. cups_needed = int(input('Enter the numbe rof cups: ')) # Convert the cups to onuces. cups_to_ounces(cups_needed) #The intro function displays an introductory screen. def intro(): print('This program converts measurements in cups to fluid ounces.') print('For your reference the formula is: 1 cup = 8 fluid ounces) print() #The cups_to_ounces function accepts a number of cupa and displays the eqivalent number of ounces def cups_to_ounces(cups): ounces = cup * 8 print('That converts to', ounces, 'ounces.') # Call the main function. main() """ """ ##Multiple_args #This program demonstrates a function that accepts two arguments def main(): print('The sum of 12 and 45 is' ) show_sum(12, 45) # The show_sumfunction accepts two arguments and displays their sum. def show_sum(num1, num2): result = num1 + num2 print(result) # Call the main function main() ###String_args #This program demonstrates passing two string arguments to a function. def main(): first_name = input('Enter your first name: ') last_name = input('Enter yout last name: ') print('Your name reversed is') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) # Call the main function main() """ """ ##keyword_args def main(): # Show the amount of simple interest, using 0.01 as interest rate per period. 10 as the number of periods. # and $10,000 as the principal. show_interest(rate=0.01, periods=10, principal=10000.0) # The show_interest function displays the amount of simple interst for a given principal, interest rate per period, and number of periods. def show_interest(principal, rate, periods): interest = principal * rate * periods print('The simple interest will be $', format(interest, ',.2f'),sep='') # Call the main function main() """ """ # This program demonstrates passing two strings as keyword arguments to a function. def main(): first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your name reversed is') reverse_name(last=last_name, first=first_name) def reverse_name(first, last): print(last, first) # Call the main function. main() """ """ ## Global1 #Create a global variable. my_value = 10 # The show_value function prints the value of the global variable. def show_value(): print(my_value) #call the show_value function show_value() """ """ ##Global2 # Create a global varible. number = 0 def main(): global number number = int(input('Enter a number: ')) show_number() def show_number(): print('The number you entered is'. number) # Call the main function main() """ """ ## Retirement # The folowing is used as a global constant # the contribution rate. CONTRIBUTION_RATE = 0.05 def main(): gross_pay = float(input('Enter the gross pay: ')) bonus = float(input('Enter the amount of bounses: ')) show_pay_contrib(gross_pay) show_bonus_contrib(bonus) # The show_pay_contrib function accepts the gross pay as an argument and displays the retirement contribution for that amont of pay. def show_pay_contrib(gross): contrib = gross * CONTRIBUTION_RATE print('Contribution for gross pay: $', format(contrib, ',.2f'), sep='') # The show_bonus_contrib function accepts the bonus amount as an argument and displays the retirement contribution for that amount of pay. def show_bonus_contrib(bonus): contrib = bonus * CONTRIBUTION_RATE print('Contribution for bonuses: $', format(contrib, ',.2f'), sep='') # Call the main function. main() """ """ ##Random_numbers #This program displays a random number in the range of 1 through 10. import random def main(): #Get a random number. number = random.randint(1, 10) # Display the number print('The number is'. number) # Call the main function. main() """ """ ##random_numbers #This program displays five random numbers in the range of 1 through 100 import random def main(): for count in range(5): #Get a random number. number = random.randint(1, 100) #Display the number print(number) #Call the main function. main() """ """ ## random_numbers3 # This program displays five random numbers in the range of 1 through 100 import random def main(): for count in range(5): print(random randint(1, 100)) # Call the main function. main() """ """ ##Dice #This program the rolling of dice import random #Constants fpr the minimum and maximum random numbers MIN = 1 MAX = 6 def main(): #Create a variable to control the loop. again = 'y' #Simulate rolling the dice. while again == 'y' or again == 'Y': print('Rolling the dice.....') print('Their values are:') print(random.randint(MIN, MAX)) print(random.randint(MIN,MAX)) #Do another rol of the dice? again = input('Roll them again? (y = yes): ') # Call the main function main() """ """ ##Coin_toss #This program simulaes 10 tosses of a coin. import random #Constants HEAD = 1 TAILS = 2 TOSSES = 10 def main(): for toss in range(TOSSES): #Simulate the coin toss. if random.randint(HEADS, TAILS) == HEADS: print('Heads') else: print('Tails') # Call the main function. main() """ """ ##TOTAL_AGES #This program uses the return value of a function def main(): # Get the user's age. first_age = int(input('Enter your age: ')) #Get the user's best friend's age. second_age = int(input("Enter your best friend's age: ")) #Get the sum of both ages. total = sum(first_age, second_age) #Display the total age. print('Together you are', total, 'years old.') #The sum function accepts two numeric arguments and returns the sum of those arguments. def sum(num1, num2): result = num1 + num2 return result # Call the main function main() """ """ ##Sale_price #This program calculates a retail item's sale price #DISCOUNT_PERCENTAGE is used as a global constant for the discount percentage. DISCOUNT_PERCENTAGE - 0.20 #The main function def main(): #Get the item's regular price. reg_price = get_regular_price() #Calculate the sale price. sale_price - dicount(reg-price) #Display the sale price. print('The sale price is $', format(sale_price, ',.2f'), sep='') # The get_regular_price function prompts the user to enter an item's regular price and it returns that value. def get_regular_price(): price = float(input("Enter the item's regular price: ")) return price # The discount function accepts an item's price as an argument and returns the amount of the discount specified by DISCOUNT_PERCENTAGE. def discount(price): return price * DISCOUNT_PERCENTAGE # Call the main function. # main() """ """ ##commission_rate. # This program calculates a salesperson's pay # at Make Your Own Music. def main(): # Get the amount of sales. sales = get_sales() # Get the amount of advanced pay. advanced_pay = get_advanced_pay() # Determine the commission rate. comm_rate = determine_comm_rate(sales) # Calculate the pay. pay = sales * comm_rate − advanced_pay # Display the amount of pay. print('The pay is $', format(pay, ',.2f'), sep='') # Determine whether the pay is negative. if pay < 0: print('The Salesperson must reimburse') print('the company.') """ """ ## (Commission_rate) get_sales function #The get_sales function gets a saleperson's monthly sales from the user and returns that value def get_sales(): #Get the amount of monthly sales. monthly_sales = float(input('Enter the monthly sales: ')) # Return the amount entered. return monthly_sales """ """ ##Square_root #This program demonstrates the sqrt function. import math def main(): #Get a number. number = float(input('Enter a number: ')) #Get the square root of the number. square_root = math.sqrt(number) #Display the square root. print('The square root', number, '0 is', square_root) # Call the main function main() """ """ ##Hypotenuse #This program calculates the length of a right triangle's hypotenuse. import math def main(): #Get the length of the triangle's two sides. a = float(input('Enter the length of side A: ')) b = float(input('Enter the length of side B: ')) #Calculate the length of the hypotenuse. c = math.hypot(a, b) #Display the length of the hypotenuse. print('The lenght of the hypotenuse is', c) #Call the main function main() """ """ ##Circle #The circle module has functions that perform calculatons relate to circles. import math #The are function accepts a circle's radius as an argument and returns the area of the circle. def area(raduis): return math.pi * raduis ** 2 #The circumference function accepts a circle's radius and return the circle's circumfeenc. def circumference(raduis) return 2 * math.pi * raduis """ """ ##Rectangle #The rectangle module has functions that parform calculations related to rectangles. #The area function accepts a rectangle's width and length as arguments and returns the rectangle's area. def area(width, length): return width * length #The perimater function accepts a rectangle's width and length as argu,ments and returns the rectangle's perimeter def perimeter(width, length): return 2 * (width + length) """ """ ##Geometry #This program allows the user to choose various geometry calculations from a menu. This program imports the circl and the rectangles modules. import circle import rectangle #Constants for the menu choice AREA_CIRCLE_CHOICE = 1 CIRCUMFERENCE_CHOICE = 2 AREA_RECTANGLE_CHOICE = 3 PERIMETER_RECTANGLE_CHOICE = 4 QUIT_CHOICE = 5 #The main function. def main(): #The choice variable controlas the loop and holds the user's menu chioce. choice = 0 while choice != QUIT_CHIOCE: #display the menu() #Get the user's choice. choice = int(input('Enter your choice: ')) #Perform the selcted action. if choice == AREA_CIRCLE_CHOICE: raduis = float(input("Enter the circle's raduis: ")) print('The area is'. circle.area(raduis)) elif choice == CIRCUMFERENCE_CHOICE: raduis = float(input("Enter the circle's radius: ")) print('The circumference is'. circle.circumference(raduis)) elif choice == AREA_RECTANGLE_CHOICE: width = float(input("Enter the rectangle's width: ")) length = float(input("Enter the rectangle's length: ")) print('The ara is', rectangle.area(width,length)) elif choice == PERIMETER_RECTANGLE_CHOICE: width = float(input("Enter the rectangle's width: ")) length = float(input("Enter the rectangle's length: ")) print('The perimeter is', rectangle.perimeter(width, length)) elif choice ==QUIT_CHOICE: print('Exiting the program....') else: print('Error: invalid selcetion.') #The display_menu function displays a menu. def display_menu(): print('MENU') print('1) Area of a circle') print('2) circumference of a circle') print('3) Area of a rectangle') print('4) Perimeter of a rectangle') print('5) Quit') # Call the main function main() """
"""A função soma_lista(lista) recebe como parâmetro uma lista de números inteiros e devolve, usando recursão, um número inteiro correspondente à soma dos elementos desta lista.""" def soma_lista(lista): if len(lista) == 1: return lista[0] else: return lista[0] + soma_lista(lista[1:])
# The data we need to retrieve. # 1. The total number of votes cast # 2. A complete list of candidates who received votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on the popular vote # Import the datetime dependency. # import datetime # Use the now() attribute on the datetime class to get the present time. # now = datetime.datetime.now() # Print the present time # print("The time right now is,",now) #add our dependencies. import csv import os # Assign a variable for the file to load and the path. file_to_load = os.path.join("Resources", "election_results.csv") # file_to_load = os.path.join("Resources", "election_results.csv") # Assign a variable to save the file to a path. (!!! not sure this step is working !!!) file_to_save = os.path.join("Resources", "Election_Analysis", "analysis", "election_analysis.txt") print(file_to_save) # Using the with statement open the file as a text file # with open(file_to_save, "w") as txt_file: # 1. Initialize a total vote counter total_votes = 0 # Candidate Options candidate_options = [] # Declare the empty vote dictionary candidate_votes = {} # Winning Candidate and Winning Count Tracker winning_candidate = "" winning_count = 0 winning_percentage = 0 # County tally, can I do this efficiently so that the county vote tally is run at the same time as the candidate count? Check grading rubric. # establish county vote counter total_county_counter = 0 # County options (this is where the county names will be stored) county_options = [] # Declare the empty county tally dictionary (this is where key: county, value = votes cast) county_votes = {} # Leading county and leading count tracker leading_county = "" leading_county_count = 0 leading_county_percentage = 0 # Open the election results and read the file. with open(file_to_load) as election_data: # to do: read and analyze the data here. # Read the file object with the reader function file_reader = csv.reader(election_data) # Read the header row. headers = next(file_reader) # Print each row in the csv file. for row in file_reader: # Add to the total vote count. (and total vote tally though this may be unneccessary since total votes will be the same whether they are for candidate or from county) total_votes +=1 total_county_counter +=1 # Print the candidate name from each row (and county tally) candidate_name = row[2] county_name = row[1] # If the candidate does not match any existing candidate... if candidate_name not in candidate_options: # Add it to the list of candidates candidate_options.append(candidate_name) # Begin tracking that candidate's vote count candidate_votes[candidate_name] = 0 # Add a vote to that candidate's count. candidate_votes[candidate_name] +=1 # ************************************************************************************************************************** # If the county name does not match any existing county ... if county_name not in county_options: # Add it to the list of counties county_options.append(county_name) # Begin tracking that county's tally county_votes[county_name] = 0 # Add a "vote" to that county's tally county_votes[county_name] +=1 # ************************************************************************************************************************** # Save the results to our text file with open(file_to_save, "w") as txt_file: # Print the final vote count to the terminal election_results = ( f"\nElection Results\n" f"-----------------------------\n" f"Total Votes: {total_votes:,}\n" f"-----------------------------\n") print(election_results, end="") # Save the final vote count to the text file. txt_file.write(election_results) # ************************************************************************************************************************** # COUNTY PARTICIPATION CODE # Determine the percentage of votes cast in each county by looping through the counts. # Interate through the county list. print("\nCounty Votes:") txt_file.write("\nCounty Votes:\n") for county_name in county_votes: # Retrieve vote count of a candidate tally = county_votes[county_name] # Calculate the percentage of votes. tally_percentage = float(tally) / float(total_county_counter) * 100 # Name the county results variable county_results = (f"{county_name}: {tally_percentage:0.1f}% ({tally:,})\n") # Print the county name and percentage of votes. # Print each county, their vote tally, and percentage to the terminal. print(county_results) # Save the winning county's name to the text file. txt_file.write(county_results) # Determine leading vote count and candidate # Determine if the votes are greater than the winning tally if (tally > leading_county_count) and (tally_percentage > leading_county_percentage): # If true then set leading_county_count = tally and leading percentage = # tally percentage leading_county_count = tally leading_percentage = tally_percentage # Set the leading county equal to the county's name leading_county = county_name leading_county_summary = ( f"\n--------------------\n" f"Largest County Turnout: {leading_county}\n" f"---------------------\n") print(leading_county_summary) # Save the leading county's results to the text file. txt_file.write(leading_county_summary) # ************************************************************************************************************************** # Determine the percentage of votes for each candidate by looping through the counts. # Interate through the candidate list. for candidate in candidate_votes: # Retrieve vote count of a candidate votes = candidate_votes[candidate] # Calculate the percentage of votes. vote_percentage = float(votes) / float(total_votes) * 100 # Name the candidate results variable candidate_results = (f"{candidate}: {vote_percentage:0.1f}% ({votes:,})\n") # Print the candidate name and percentage of votes. # Print each candidate, their voter count, and percentage to the terminal. print(candidate_results) # Save the winning candidate's name to the text file. txt_file.write(candidate_results) # Determine winning vote count and candidate # Determine if the votes are greater than the winning count if (votes > winning_count) and (vote_percentage > winning_percentage): # If true then set winning_count = votes and winning percentage = # vote percentage winning_count = votes winning_percentage = vote_percentage # Set the winning candidate equal to the candidate's name winning_candidate = candidate winning_candidate_summary = ( f"--------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"---------------------\n") print(winning_candidate_summary) # Save the winning candidate's results to the text file. txt_file.write(winning_candidate_summary) # *********************************************************************************** #print(f"{candidate}: {vote_percentage:0.1f}% ({votes:,})\n") # Print the candidate vote dictionary. #print(candidate_votes) # Print the candidate list #print(candidate_options) # Print the total votes. #print(total_votes) # print(election_data) # Close the file #election_data.close() # Using the with statement open the file as a text file #with open(file_to_save, "w") as txt_file: # Write some data to the file. #txt_file.write("Arapahoe\nDenver\nJefferson") # Close the file #outfile.close() # Using the open() function with the "w" mode we will write data to the file. #open(file_to_save, "w")
### one code one day ### 两个排序数组 找第 K大的数字 ### 二分 def K_of_two_sorted_arr(arr1, arr2, K): start, end = 0, len(arr1)-1 while(start <= end): mid = (start + end) // 2 if(mid >= K): end = mid - 1 elif(mid == K - 1): if(arr1[mid] <= arr2[0]): return arr1[mid] else: end = mid - 1 else: arr2_idx = K - 2 - mid if(arr2_idx >= len(arr2)): start = mid + 1 continue if(arr2[arr2_idx] > arr1[mid]): if(mid == len(arr1) - 1 or (mid != len(arr1)-1 and arr2[arr2_idx] <= arr1[mid + 1])): return arr2[arr2_idx] else: start = mid + 1 else: if(arr2_idx == len(arr2) - 1 or (arr2_idx != len(arr2)-1 and arr1[mid] <= arr2[arr2_idx+1])): return arr1[mid] else: end = mid - 1 return arr2[K-1] arr1 = [1,4,6,10,20,25,26,30] arr2 = [2,3,5,8,11,31] for k in range(1,len(arr1)+len(arr2)+1): print(K_of_two_sorted_arr(arr1, arr2, k))
### one code one day ### 2020/04/10 ### leetcode 109 有序链表转换二叉搜索树 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: def helper(start, end): if(start == None): return None if(start == end): return None ### 查找链表长度为一般的节点,快慢指针法 slow = fast = start while(fast != end and fast.next != end): slow = slow.next fast = fast.next.next node = TreeNode(slow.val) node.left = helper(start, slow) node.right = helper(slow.next, end) return node return helper(head, None)
### one code one day ### 2020/05/08 ### leetcode 6 Z字形变换 def convert(self, s: str, numRows: int) -> str: def helper(word, row, flag): if(word != ''): arr[row].append(word[0]) if(flag): row += 1 if(row == numRows-1): flag = False else: row -= 1 if(row == 0): flag = True helper(word[1:], row, flag) if(numRows == 1): return s arr = [[] for _ in range(numRows)] helper(s, 0, True) res = '' for i in range(numRows): res += ''.join(arr[i]) return res
### one code one day ### 2020/05/02 ### leetcode 695 岛屿的最大面积 ### 栈实现深度优先搜索 def maxAreaOfIsland(self, grid: List[List[int]]) -> int: stack = [] res = 0 rows = len(grid) if(rows == 0): return 0 columns = len(grid[0]) walked = [[False] * columns for _ in range(rows)] for i in range(rows): for j in range(columns): if(not walked[i][j] and grid[i][j]): temp_res = 0 stack.append((i,j)) while(stack): row, column = stack.pop() if(0 <= row < rows and 0 <= column < columns and grid[row][column]==1 and not walked[row][column]): walked[row][column] = True temp_res += 1 stack.extend([(row+1,column),(row-1,column),(row,column+1),(row,column-1)]) res = max(res, temp_res) return res ### 递归实现 def maxAreaOfIsland(self, grid: List[List[int]]) -> int: def DFS(i, j): if(i < 0 or i >= rows or j < 0 or j >= columns): return 0 elif(walked[i][j] or grid[i][j] == 0): return 0 else: count = 1 walked[i][j] = True return count + DFS(i-1, j) + DFS(i+1, j) + DFS(i, j-1) + DFS(i, j+1) res = 0 rows = len(grid) if(rows == 0): return 0 columns = len(grid[0]) walked = [[False] * columns for _ in range(rows)] for i in range(rows): for j in range(columns): if(not walked[i][j]): res = max(res, DFS(i, j)) return res
### one code one day ### 2020/03/03 ### leetcode 61 旋转列表 def rotateRight(self, head: ListNode, k: int) -> ListNode: ### 判断head是否为空和是否不用旋转 if(not head or k == 0): return head ### 变为循环链表,并求出链表长度 length = 1 p = head while(p.next != None): length += 1 p = p.next p.next = head ### 确定要找第几个节点 m = (length - k % length) % length ### 开始找第m个节点 pre = p i = 0 while(i < m): pre = head head = head.next i += 1 pre.next = None return head def test(): pass
arr = [3,1,1,2,5,4,2,10,41,12,51,5,4,1] def merge(left, mid, right): temp = [] l = left r = mid + 1 while(l <= mid and r <= right): if(arr[l] <= arr[r]): temp.append(arr[l]) l += 1 else: temp.append(arr[r]) r += 1 if(l == mid+1): temp.extend(arr[r:right+1]) else: temp.extend(arr[l:mid+1]) for i in range(len(temp)): arr[left+i] = temp[i] def mergesort(start, end): if(start < end): mid = start + (end - start) // 2 mergesort(start, mid) mergesort(mid+1, end) merge(start, mid, end)
#!/usr/bin/env python # coding: utf-8 # In[1]: def add(n1,n2): print(n1+n2) # In[2]: add(10,20) # In[3]: number1 = 10 # In[4]: number2 = input("Please provide a number: ") # In[17]: add(number1,number2) print("Something happened!") # In[24]: try: # WANT TO ATTEMPT THIS CODE # MAY HAVE AN ERROR result = 10 + 10 except: print("Hey it looks like you aren't adding correctly!") else: print("Add went well!") print(result) # In[21]: result # In[ ]: # In[ ]: try: f = open('testfile','r') f.write("Write a test line") except TypeError: print("There was a type error!") except OSError: print('All other exceptions') finally: print("I always run") # In[ ]: def ask_for_int(): while True: try: result = int(input("Please provide number: ")) except: print("Whoops! that is not a number") continue else: print("Yes thank you!") break finally: print("Yes thank you!") # In[ ]: ask_for_int() # In[ ]: # In[ ]: # In[ ]: # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[28]: class Animal(): def __init__(self): print("ANIMAL CREATED") def who_am_i(self): print("I am an animal") def eat(self): print("I am eating") # In[35]: class Dog(Animal): def __init__(self): Animal.__init__(self) print("Dog Created") def eat(self): print("I am a dog and eating") def bark(self): print("WOOF!") # In[36]: mydog = Dog() # In[37]: mydog.who_am_i() # In[38]: myanimal = Animal() # In[39]: myanimal.who_am_i() # In[41]: mydog.eat() # In[42]: mydog.bark() # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
import numpy as np from .imputation import imputer class emulator: """Class to make predictions from the trained DGP model. Args: all_layer (list): a list that contains the trained DGP model produced by the method 'estimate' of the 'dgp' class. """ def __init__(self, all_layer): self.all_layer=all_layer self.n_layer=len(all_layer) self.imp=imputer(self.all_layer) def predict(self,x,N=50,method='mean_var',full_layer=False): """Implement predictions from the trained DGP model. Args: x (ndarray): a numpy 2d-array where each row is an input testing data point and each column is an input dimension. N (int): the number of imputation to produce the predictions. method (str, optional): the prediction approach: mean-variance ('mean_var') or sampling ('sampling') approach. Defaults to 'mean_var'. full_layer (bool, optional): whether to output the predictions of all layers. Defaults to False. Returns: Union[tuple, list]: if the argument method='mean_var', a tuple is returned: 1. If full_layer=False, the tuple contains two numpy 2d-arrays, one for the predictive means and another for the predictive variances. Each array has its rows corresponding to testing positions and columns corresponding to DGP output dimensions (i.e., GP nodes in the final layer); 2. If full_layer=True, the tuple contains two lists, one for the predictive means and another for the predictive variances. Each list contains L (i.e., the number of layers) numpy 2d-arrays. Each array has its rows corresponding to testing positions and columns corresponding to output dimensions (i.e., GP nodes from the associated layer). if the argument method='sampling', a list is returned: 1. If full_layer=False, the list contains D (i.e., the number of GP nodes in the final layer) numpy 2d-arrays. Each array has its rows corresponding to testing positions and columns corresponding to N imputations; 2. If full_layer=True, the list contains L (i.e., the number of layers) sub-lists. Each sub-list represents the samples draw from the GPs in the corresponding layers, and contains D (i.e., the number of GP nodes in the corresponding layer) numpy 2d-arrays. Each array gives samples of the output from one of D GPs at the testing positions, and has its rows corresponding to testing positions and columns corresponding to N imputations. """ #warm up M=len(x) (self.imp).sample(burnin=50) #start predictions mean_pred=[] variance_pred=[] for _ in range(N): overall_global_test_input=x (self.imp).sample() if full_layer==True: mean_pred_oneN=[] variance_pred_oneN=[] for l in range(self.n_layer): layer=self.all_layer[l] n_kerenl=len(layer) overall_test_output_mean=np.empty((M,n_kerenl)) overall_test_output_var=np.empty((M,n_kerenl)) if l==0: for k in range(n_kerenl): kernel=layer[k] m_k,v_k=kernel.gp_prediction(x=overall_global_test_input[:,kernel.input_dim],z=None) overall_test_output_mean[:,k],overall_test_output_var[:,k]=m_k,v_k else: for k in range(n_kerenl): kernel=layer[k] m_k_in,v_k_in=overall_test_input_mean[:,kernel.input_dim],overall_test_input_var[:,kernel.input_dim] if np.any(kernel.connect!=None): z_k_in=overall_global_test_input[:,kernel.connect] else: z_k_in=None m_k,v_k=kernel.linkgp_prediction(m=m_k_in,v=v_k_in,z=z_k_in) overall_test_output_mean[:,k],overall_test_output_var[:,k]=m_k,v_k overall_test_input_mean,overall_test_input_var=overall_test_output_mean,overall_test_output_var if full_layer==True: mean_pred_oneN.append(overall_test_input_mean) variance_pred_oneN.append(overall_test_input_var) if full_layer==True: mean_pred.append(mean_pred_oneN) variance_pred.append(variance_pred_oneN) else: mean_pred.append(overall_test_input_mean) variance_pred.append(overall_test_input_var) if method=='sampling': if full_layer==True: mu_layerwise=[list(mean_n) for mean_n in zip(*mean_pred)] var_layerwise=[list(var_n) for var_n in zip(*variance_pred)] samples=[] for l in range(self.n_layer): samples_layerwise=[] for mu, sigma2 in zip(mu_layerwise[l], var_layerwise[l]): realisation=np.random.normal(mu,np.sqrt(sigma2)) samples_layerwise.append(realisation) samples_layerwise=np.asarray(samples_layerwise).transpose(2,1,0) samples.append(list(samples_layerwise)) else: samples=[] for mu, sigma2 in zip(mean_pred, variance_pred): realisation=np.random.normal(mu,np.sqrt(sigma2)) samples.append(realisation) samples=list(np.asarray(samples).transpose(2,1,0)) return samples elif method=='mean_var': if full_layer==True: mu_layerwise=[list(mean_n) for mean_n in zip(*mean_pred)] var_layerwise=[list(var_n) for var_n in zip(*variance_pred)] mu=[np.mean(mu_l,axis=0) for mu_l in mu_layerwise] mu2_mean=[np.mean(np.square(mu_l),axis=0) for mu_l in mu_layerwise] var_mean=[np.mean(var_l,axis=0) for var_l in var_layerwise] sigma2=[i+j-k**2 for i,j,k in zip(mu2_mean,var_mean,mu)] else: mu=np.mean(mean_pred,axis=0) sigma2=np.mean((np.square(mean_pred)+variance_pred),axis=0)-mu**2 return mu, sigma2
import unittest from credential import Credential class TestCredential(unittest.TestCase): ''' Test class that defines test cases credential class behaiour Args: unittest,Testcase:Testcase that enable in creating testcases''' def setUp(self): self.new_application = Credential("github","Maureen1998","3344") ''' method that runs before every test''' def test_init (self): ''' test case that test if the object is initializing properly ''' self.assertEqual(self.new_application.application,"github") self.assertEqual(self.new_application.username,"Maureen1998") self.assertEqual(self.new_application.password,"3344") def test_save_credential(self): ''' testcase that test if the credential are saved in the credential list ''' self.new_application.save_credential() self.assertEqual(len(Credential.credential_lists),1) def test_save_mutliple_credential (self): ''' check if we can save multiple application username and passwords ''' self.new_application.save_credential() test_application = Credential("Test","user","5465") test_application.save_credential() self.assertEqual(len(Credential.credential_lists),2) def tearDown(self): ''' cleans up after each test has run''' Credential.credential_lists = [] def test_display_credential(self): ''' method that displays the list of all credential ''' self.assertEqual(Credential.display_credential(),Credential.credential_lists) def test_find_by_application(self): ''' method that finds an Application details by Application name ''' self.new_application.save_credential() test_application=Credential("Test","user","5465") test_application.save_credential() found_application = Credential.find_by_application("Test") self.assertEqual(found_application.username,test_application.username) def test_generate_password(self): ''' testcase to check if the password is generated ''' self.assertEqual(len(Credential.password()),5) if __name__ == '__main__': unittest.main()
import pyperclip import shelve import os import dev_deckmaker ''' TODO: Change the format so that python exports the pokemon cards as a list or a data structure then zip that data for saving, and unpack it for use. This way you can continue where you left off, and also to allow for sorting to happen. Also look into classes to see if these might help: Card properties etc Also look into xml and how OCTGN does it. ie: card.name = Pidgey, card.num = 68, card.rarity = 0, card.totalQty = 5, card.numSold = 0, card.numHolo = 2, etc TODO: Create a shelf file that stores the names of all currently made decks This should happen both on load or when a new deck is created. Store the name as a dictionary Alternatively it can search through the pokemon databases and merge them into 1 dictionary list and search their 'deckNAME" attribute. Slow but accurate TODO: Make deck to work on selectable TODO: Make the program ask the pokemon number FIRST. Check to see if the pokemon number exists already. If it exists then instead ask if the person wants to change some data Options: - Num Sold - Prices - Quantity - Edit names - Delete records TODO: Find a way to illustrate money as $1.00 with two points after decimal (lol) TODO: Change the program format so that it's used to create Databases for each deck. After creating the Databases. The user can say what deck they are adding cards to, the card's number, and the program does the rest. Essentially separate the developer tool (Deck making) vs the user tool (What cards the user has) ''' deckName = input("Insert The Name of this Deck:\n") deckFileName = input("Insert folder filename for this deck:\n") deckSize = input ("Total Num of Cards In this Deck: \n") htmlAnchor = '</html>' headAnchor = '</head>' titleAnchor = '</title>' bodyAnchor = '</body>' docTypeAnchor = '<!DOCTYPE html>' cssInsert = '<link rel="stylesheet" type="text/css" href="%s.css">' imgInsert = '<img src="img/%s">' h2Start = '<h2>\n\t' h2End = '\n\t</h2>' cardEndPoint = '<!-- Add cards here-->' exportPath = 'K:\\Users\\Reggie\\Desktop\\Pokemon HTML\\automated\\' os.chdir(exportPath) # currentShelfFile = open('') def saveData(pokemoncard): d = shelve.open('pokemonDB_%s'%(deckFileName)) flag = '%s' %(pokemoncard['num']) in d if (flag == True): # shelfFile = shelve.open('pokemonDB_%s'%(deckFileName)) print('Data exists already. Ignoring.') # data = d['cards'] # data else: print('Data doesnt exist, adding a new item to database') d['%s'%(pokemoncard['num'])] = pokemoncard print(list(d.keys())) print(list(d.values())) d.close() def insertNewData(sectionAnchor, newText, numTabs=0): # This works best if you send it the anchor version of what you want to find # Example: '</body>', '</title>', '</head>' try: sectionPos = v.index(sectionAnchor) v.insert(sectionPos, '\n') v.insert(sectionPos, ('\t'*numTabs) + newText) except: print('%s Not Found' %(sectionAnchor)) def createPokemonCard(): # pokemon = {'name': '', 'num': 0, 'rarity': 0, 'totalQty': 0, 'holoQty': 0, 'shinyQty': 0, 'deckName': '', # 'minPrice': 1.00, 'maxPrice': 1.00, 'numSold': 0} cardList = [] rarityList = ['Common', 'Uncommon', 'Rare'] card = [] b = card.append minPrice = 1.00 maxPrice = 1.00 avgPrice = (maxPrice + minPrice)/2 cardName = input("Name of the Pokemon: ") cardNum = input("Num of the Pokemon: ") cardQty = input("How many copies do you have? ") cardRarity = input("Card's Rarity? Input 0,1, or 2 for Common, Uncommon, or Rare: ") cardRarity = min(int(cardRarity),2) if cardRarity == 2: # Commons or Uncommons cannot be Holos. They can be shiny however cardHoloQty = input("How many holos of this card do you have? ") else: cardHoloQty = 0 cardShinyQty = input("How many shinies of this card do you have? ") print() numSold = 0 pokemonCard = {'name': cardName, 'num': int(cardNum), 'rarity': cardRarity, 'totalQty': cardQty, 'holoQty': cardHoloQty, 'shinyQty': cardShinyQty, 'deckName': deckName, 'minPrice': minPrice, 'maxPrice': maxPrice, 'numSold': numSold} saveData(pokemonCard) insertNewData(cardEndPoint, '<li class ="pkmncard" >', numTabs=3) insertNewData(cardEndPoint, '<img src="img/%s/%s.png">'%(deckFileName,cardNum), numTabs=4) insertNewData(cardEndPoint, '<table class ="pokedata">', numTabs=4) insertNewData(cardEndPoint, '<tbody>', numTabs=5) insertNewData(cardEndPoint, '<tr>',numTabs=6) insertNewData(cardEndPoint, '<th scope ="row"> Name:</th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--Name -->' %(cardName),numTabs=7 ) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope ="row"> Total Num: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--TotalNum -->' % (cardQty), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Holo Num: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--HoloNum -->' % (cardHoloQty), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Shiny Num: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--ShinyNum -->' % (cardShinyQty), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Card#: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s/%s</td> <!--CardNum -->' % (cardNum,deckSize), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Card Rarity: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--CardRarity -->' % (rarityList[int(cardRarity)]), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Min Price: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>$%s</td> <!--MinPrice -->' % (minPrice), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Max Price: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>$%s</td> <!--MaxPrice -->' % (maxPrice), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Avg. Price: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>$%s</td> <!--AvgPrice -->' % (avgPrice), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '<tr>', numTabs=6) insertNewData(cardEndPoint, '<th scope="row">Num Sold: </th>', numTabs=7) insertNewData(cardEndPoint, '<td>%s</td> <!--NumSold -->' % (numSold), numTabs=7) insertNewData(cardEndPoint, '</tr>', numTabs=6) insertNewData(cardEndPoint, '</tbody>', numTabs=5) insertNewData(cardEndPoint, '</table>', numTabs=4) insertNewData(cardEndPoint, '</li>', numTabs=3) ''' b('<li>Total Num: %s</li>' % (cardQty)) b('<li>Holos: %s</li>' % (cardHoloQty)) b('<li>Card #: %s/147</li>' % (cardNum)) b('<li>Min Price: %s</li>' % ('$1.00')) b('<li>Max Price: %s</li>' % ('$1.00')) b('\t') b('<li class="pkmncard">') b('\n') b('\t'*3) b('<img src="img/%s/%s.png">'%(deckFileName,cardNum)) b('\n') b('\t'*2) b('<ul>') b('\n') b('\t\t') b('<li><h3>%s</h3></li>'%(cardName)) b('<li>Total Num: %s</li>' %(cardQty)) b('<li>Holos: %s</li>' %(cardHoloQty)) b('<li>Card #: %s/147</li>' %(cardNum)) b('<li>Min Price: %s</li>' %('$1.00')) b('<li>Max Price: %s</li>' %('$1.00')) b('</ul>') b('</li>') return ''.join(card) ''' def addCards(): doneAdding = False i = 0 addMoreCards = input("Add a card to the database?\n") if (addMoreCards.lower() == "n"): doneAdding = True while(doneAdding == False): createPokemonCard() addMoreCards = input("Add more cards?\n") if addMoreCards.lower() == "n": doneAdding = True i += 1 print('Added %s cards to the database' %(i)) v = [] a = v.append newLine = ('\n') a('<!DOCTYPE html>') a('\n') a('<html>') a('\n') a('<head>') a('\n') a('<title>') a('\n') a('</title>') a('\n') a('</head>') a('\n') a('<body>') a('\n') a('</body>') a('\n') a('</html>') print(a) insertNewData(bodyAnchor, '<a href="index.html">\n\t\t<h1>Pokemon Catalog</h1>\n\t</a>') insertNewData(titleAnchor, deckName) insertNewData(headAnchor, cssInsert %('normalize')) insertNewData(headAnchor, cssInsert %('style')) insertNewData(bodyAnchor, h2Start + imgInsert %('icon_%s' %(deckFileName) + '.png') + deckName + h2End) insertNewData(bodyAnchor, '<div id ="wrapper">') insertNewData(bodyAnchor, '<ul class="pkmncardlist">') insertNewData(bodyAnchor, cardEndPoint) insertNewData(bodyAnchor, '</ul>') insertNewData(bodyAnchor, '</div') addCards() # v.insert(bodyPos + 1, ) finalHTML = ''.join(v) # print (''.join(v)) pyperclip.copy(finalHTML) currentHTMLFile = open('%s' %(deckFileName) + '.html','w') currentHTMLFile.write(finalHTML) currentHTMLFile.close() print("HTML Copied to the clipboard!") print("HTML file written to %s\%s.html" %(os.getcwd(),deckFileName))
from pointsandrotations import * from sidesandprinting import * from scramblecube import * from solvingstatecheck import * """Temporary user interface. To be replaced with a graphical version.""" print('Give the colors of the stickers in your cube as follows:') print('') print('Each side is represented as a 9 character string where single') print('character represents a color of the given square.') print('') print('For the front, left, back and right sides the indexing starts from') print('the top most square on the left corner of the given side.') print('') print('For the top side, it starts from the corner which touches the left side') print('and the back side.') print('') print('And for the bottom side from the corner which touches the left side') print('and the front side.') print('') print('Colors are reperesented as follows: r, g, o, b, w, y (which stand') print('for: red, green, orange, blue, white and yellow).') print('') print('Example: the string "gggooorrr" represents a side where first row') print('is green, second row is orange and third row is red.') print('') print('This program can also scramble a cube for you.') print('') print('Do you want to give your own cube settings or let us give you a cube?') print('') answer = input("Write 'y' if you use your own cube and 'n' otherwise : ") print('') while answer not in {'y', 'n'}: answer = input("Please try again. Write 'y' or 'n' (without citation): ") def proper_char(char): return char in {'r', 'g', 'o', 'b', 'w', 'y'} def proper_side_string(side_str): if len(side_str) != 9: return False if {proper_char(side_str[i]) for i in range(9)} != {True}: return False return True def s_input(request1, request2): side_str = input(request1) while not proper_side_string(side_str): side_str = input(request2) return side_str def ask_input(): users_cube = {} request = 'Please try again. String of 9 characters (g, r, o, b, w, y): ' front_string = s_input('Give the string for the front side: ', request) left_string = s_input('Same for the left side: ', request) back_string = s_input('Same for the back side: ', request) right_string = s_input('Same for the right side: ', request) top_string = s_input('Same for the top side: ', request) bottom_string = s_input('Same for the bottom side: ', request) side_strings = [front_string, left_string, back_string, right_string, top_string, bottom_string] for n in range(6): for m in range(9): users_cube[sides[n][m]] = side_strings[n][m] return users_cube if answer == 'y': print('Position first your cube as follows:') print('') print('The top face should have white center piece.') print('The front face should have red center piece.') print('The left face should have green center piece.') print('The right face should have blue center piece.') print('') cube = ask_input() elif answer == 'n': cube = scramble(start_cube) print('') print('So your cube looks like this:') print('') print_cube(cube) state_num = 7 # Default: cube scrambled. count = 0 # How many times a state lower than 5 is countered. solver_functions = [make_correct_edges, make_correct_corners, make_yellow_corners, make_a_yellow_cross, make_a_2nd_layer, make_a_top_layer, make_a_cross] while state_num != 0: s_state = check_state(cube) cube = s_state[0] state_num = s_state[1] if state_num == 0: break if state_num < 5: count += 1 if answer == 'y' and count == 1: print('You should now turn the cube upside down. That is, white side') print('should be on the bottom, yellow center on the top, and red rows') print('should be to two lowest rows on the front side.') print('') if answer == 'n' and count == 1: print('The cube will be now turned upside down.') print('') print('You currently have ' + string_rep[state_num] + ' solved.') print('') print('Do you want the instructions for next stage?') print('') print("Write 'y' if you want instructions for the next stage.") reply = input('(Any other key will let you to exit this program): ') print('') if reply == 'y': solver = solver_functions[state_num - 1] if state_num < 5: cube = start_orientation(cube) next_step = solver(cube) cube = next_step[0] if state_num > 5: instructions = next_step[1] else: instructions = next_step[2] print('') print('Rotations for the next stage are:') print('') print(', '.join(instructions)) print('') print('After doing these rotations your cube should look like this:') print_cube(cube) print('') else: exit(0) print('Gongratulations! You have solved the cube.')
import sub.mailing as mailing def send(email): ID = input("ID>>") r = mailing.mail(email, 1, 0, ID) while (r == -1): print("輸入錯誤") ID = input("ID>>") r = mailing.mail(email, 1, 0, ID) return 0 email = input() send(email)
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' # Create an array max_upto and a stack to store indices. Push 0 in the stack. # Run a loop from index 1 to index n-1. # Pop all the indices from the stack, which elements (array[s.top()]) is less than the current element and update max_upto[s.top()] = i – 1 and then insert i in the stack. # Pop all the indices from the stack and assign max_upto[s.top()] = n – 1. # Create a variable j = 0 # Run a loop from 0 to n – k, loop counter is i # Run a nested loop until j < i or max_upto[j] < i + k – 1, increment j in every iteration. # Print the jth array element. def sliding_window_max(nums, k): # Your code here n = len(nums) max_nums = [] max_upto=[0 for i in range(n)] # Update max_up to array similar to # finding next greater element s=[] s.append(0) for i in range(1,n): while (len(s) > 0 and nums[s[-1]] < nums[i]): max_upto[s[-1]] = i - 1 del s[-1] s.append(i) while (len(s) > 0): max_upto[s[-1]] = n - 1 del s[-1] j = 0 for i in range(n - k + 1): # j < i is to check whether the # jth element is outside the window while (j < i or max_upto[j] < i + k - 1): j += 1 max_nums.append(nums[j]) return max_nums if __name__ == '__main__': # Use the main function here to test out your implementation arr = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
# Description: The file names.txt contains a list of names, one per line. Write a program that reads in this list and prints the longest name. # Source: http://zarkonnen.com/python_exercises with open('names.txt', 'r') as f: longest_name = "" while True: name = f.readline() if name == "": break if len(name) > len(longest_name): longest_name = name print longest_name
import collections test = input("") d = True freq = collections.Counter(test) l = len(test) if "@" in test and '.' in test: diff = test.index('.') - test.index("@") for x,y in freq.items(): if(x== '@' and y!=1): print("NO") break elif(x == '.' and y!=1): print("No") break else: if(diff <4 and diff >5): print("NO") elif(test.index("@") <3): print("NO") elif(test[l-4:l] != ".com"): print("NO") else: print("YES") elif("@" not in test or "." not in test): print("NO")
import sys from typing import List from shared import get_exact_rows if __name__ == '__main__': grid = list(get_exact_rows(sys.argv[1], strip=False)) current_position = [0, grid[0].index('|')] direction = 1, 0 letters_encountered = [] # type: List[str] current_character = None steps = 0 while current_character != ' ': steps += 1 current_position[0] += direction[0] current_position[1] += direction[1] current_character = grid[current_position[0]][current_position[1]] if current_character.isalpha(): letters_encountered += current_character elif current_character == '+': left_turn = direction[1], direction[0] # this is not correct how did this work right_turn = direction[1] * -1, direction[0] * -1 peek_left_character = None peek_right_character = None if 0 <= current_position[0] + left_turn[0] < len(grid) and 0 <= current_position[1] + left_turn[1] < len(grid[1]): peek_left_character = grid[current_position[0] + left_turn[0]][current_position[1] + left_turn[1]] if 0 <= current_position[0] + right_turn[0] < len(grid) and 0 <= current_position[1] + right_turn[1] < len(grid[1]): peek_right_character = grid[current_position[0] + right_turn[0]][current_position[1] + right_turn[1]] if peek_left_character in {'-', '|'}: direction = left_turn elif peek_right_character in {'-', '|'}: direction = right_turn else: raise Exception("bad") print(''.join(letters_encountered)) print(steps)
#!/usr/bin/env python3 # !-*-coding:utf-8 -*- # !@File : $[name].py #该文件中是二分法的例子 #涉及到的题目,均来自于leetcode #在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素, #而不是第 k 个不同的元素。 #题目链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ import random from typing import List def findKthLargest(nums: List[int], k: int) -> int: #patition的作用是找到,当前元素在数组中,应该所站的位置 # def patition(nums, left, right): # # 使用类似快排的方式 # # x = nums[left] # pivot = left # # 此时的index永远指向,比x大的最小一个数所在的位置 # index = pivot + 1 # for i in range(index, right + 1): # # 如果有小于标杆的,就交换 # # 如果此前一直都是小于的,就不用交换 # # index每增加一次,就是标杆的位置向前挪动1 # if nums[i] < nums[pivot]: # nums[i], nums[index] = nums[index], nums[i] # index += 1 # nums[left], nums[index - 1] = nums[index - 1], nums[left] # print(nums) # return left+index - 1 #另一种patition def patition(nums,left, right): x = nums[left] while right > left: while left < right and nums[right] > x: right -=1 nums[left] = nums[right] while left < right and nums[left] < x: left +=1 nums[right] =nums[left] return left def quitsort(nums,left,right,k): while True: #随机抽取一个数 index = random.randint(left,right) nums[left], nums[index] = nums[index], nums[left] pat = patition(nums,left,right) if pat == k: return nums[left] elif pat < k: left = pat+1 else: right = pat-1 n = len(nums) return quitsort(nums,0,n-1,n-k-1) #快速排序的思想是分治,首先得到一个标杆,然后经过一次排序,比标杆大的,排在右边 #比标杆小的,排在左边 #一次便利,可以确定一个数的位置 #然后将确定位置的数的左边和右边,再递归排序 #除了使用快速排序之外,还可以使用堆排序 #维护一个小根对,最小的,就是第k个大 import heapq def findKthLargest2( nums: List[int], k: int) -> int: s = [] n = len(nums) for i in range(n): # 此时的数组个数小于n-k,不存在第k大的数 if i < k: heapq.heappush(s, nums[i]) else: if nums[i] > s[0]: s[0] = nums[i] heapq.heapify(s) return s[0] # 编写一个高效的算法来搜索mxn矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性: # # 每行的元素从左到右升序排列。 # 每列的元素从上到下升序排列。 #题目链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/ def searchMatrix(matrix: List[List[int]], target: int) -> bool: n = len(matrix) m = len(matrix[0]) for i in range(n): start = 0 end = m-1 if matrix[i][end] < target or matrix[i][start] > target: continue else: while start <= end: mid = (start+end)//2 if matrix[i][mid] == target: return True elif matrix[i][mid] < target: start = mid + 1 else: end = mid -1 return False #从题目的描述可以看出来,输入的矩阵是从左到右增大,从上到下增大 #因此我们可以先判断target 有可能再哪一个行, #如果这一行的最小数大于target 或者最大数小于target,则该数不可能在这一行 #当找到目标可能在的行之后,使用二分法来查找,如果不在这一样,则继续往下一行找,如果在,则直接返回True #当把整个矩阵都找完,还没有找到时,直接返回False
from abc import ABC, abstractmethod class AbstractData(ABC): def __init__(self): super().__init__() @abstractmethod def get_type(self): pass @abstractmethod def generate_data(self): pass class String(AbstractData): def __init__(self, string=""): super().__init__() self.__string = string def get_type(self): return "string" def generate_data(self): return "\"" + self.__string + "\"" class Enum(AbstractData): def __init__(self, stringID=""): super().__init__() self.__stringID = stringID def get_type(self): return "enum" def generate_data(self): return "\"" + self.__stringID + "\"" class Integer(AbstractData): def __init__(self, integer=0): super().__init__() self.__integer = integer def get_type(self): return "integer" def generate_data(self): return str(self.__integer) class Real(AbstractData): def __init__(self, real=0): super().__init__() self.__real = real def get_type(self): return "real" def generate_data(self): return str(self.__real) class Vector2(AbstractData): def __init__(self, vector=(0, 0)): super().__init__() self.__vector = vector def get_type(self): return "vector2" def generate_data(self): return "\"%f %f\"" % (self.__vector[0], self.__vector[1]) class Vector3(AbstractData): def __init__(self, vector=(0, 0, 0)): super().__init__() self.__vector = vector def get_type(self): return "vector3" def generate_data(self): return "\"%f %f %f\"" % (self.__vector[0], self.__vector[1], self.__vector[2]) class Quaternion(AbstractData): def __init__(self, quaternion=(0, 0, 0, 0)): super().__init__() self.__quaternion = quaternion def get_type(self): return "quaternion" def generate_data(self): return "\"%f %f %f %f\"" % (self.__quaternion[0], self.__quaternion[1], self.__quaternion[2], self.__quaternion[3]) class RealArray(AbstractData): def __init__(self, array=None): super().__init__() if array is None: self.__array = [] else: self.__array = array def get_type(self): return "real-array" def generate_data(self): fragments = ["{"] for real in self.__array: fragments.append("%f " % real) fragments.append("}") return "".join(fragments) def set_array(self, array): self.__array = array return self def add(self, real): self.__array.append(real) return self class Vector3Array(AbstractData): def __init__(self, array=None): super().__init__() if array is None: self.__array = [] else: self.__array = array def get_type(self): return "vector3-array" def generate_data(self): fragments = ["{"] for vector3 in self.__array: fragments.append("\"%f %f %f\" " % (vector3[0], vector3[1], vector3[2])) fragments.append("}") return "".join(fragments) def set_array(self, array): self.__array = array return self def add(self, vector3): self.__array.append(vector3) return self class Spectrum(AbstractData): def __init__(self, values=(0, 0, 0)): super().__init__() self.__values = values def get_type(self): return "spectrum" def generate_data(self): fragments = ["\""] for value in self.__values: fragments.append(str(value) + " ") fragments.append("\"") return "".join(fragments) class Path(AbstractData): def __init__(self, string=""): super().__init__() self.__string = string def get_type(self): return "path" def generate_data(self): return "\"" + self.__string + "\"" class ResourceIdentifier(AbstractData): def __init__(self, string=""): super().__init__() self.__string = string def get_type(self): return "PRI" def generate_data(self): return "\"" + self.__string + "\"" def set_bundled_path(self, path): self.__string = ":" + str(path) def set_external_path(self, path): self.__string = "ext:" + str(path) class Reference(AbstractData): def __init__(self, ref_type="", ref_name=""): super().__init__() self.__ref_type = ref_type self.__ref_name = ref_name def get_type(self): return self.__ref_type def generate_data(self): return "@\"%s\"" % self.__ref_name class RawData(AbstractData): def __init__(self, type_string="", data_string=""): super().__init__() self.__type_string = type_string self.__data_string = data_string def get_type(self): return self.__type_string def generate_data(self): return self.__data_string class AbstractCommand(ABC): def __init__(self): super().__init__() @abstractmethod def generate(self): pass class AbstractInputCommand(AbstractCommand): def __init__(self): super().__init__() self.__inputs = [] @abstractmethod def get_full_type(self): pass @abstractmethod def generate(self): pass def set_input(self, name, data: AbstractData): self.__inputs.append((name, data)) def _generate_input_fragments(self, out_fragments): for name, data in self.__inputs: out_fragments.append("[") out_fragments.append(data.get_type() + " ") out_fragments.append(name + " ") out_fragments.append(data.generate_data()) out_fragments.append("]") class RawCommand(AbstractCommand): """ Take any string and use it as a command. """ def __init__(self): super().__init__() self.__command_string = "" def append_string(self, string): self.__command_string += string def generate(self): return self.__command_string class DirectiveCommand(AbstractCommand): def __init__(self): super().__init__() self.__directive_string = "" def append_directive(self, string): self.__directive_string += string def generate(self): fragments = ["#", self.__directive_string, ";\n"] return "".join(fragments) class CreatorCommand(AbstractInputCommand): def __init__(self): super().__init__() self.__data_name = "" @abstractmethod def get_full_type(self): pass def generate(self): # TODO: some part can be pre-generated fragments = [ self.get_full_type(), " ", "@\"" + self.__data_name + "\"", " = "] self._generate_input_fragments(fragments) fragments.append(";\n") return "".join(fragments) def set_data_name(self, data_name): self.__data_name = data_name class ExplicitExecutorCommand(AbstractInputCommand): def __init__(self): super().__init__() self.__target_name = "" @abstractmethod def get_full_type(self): pass @abstractmethod def get_name(self): pass def generate(self): # TODO: some part can be pre-generated fragments = [ self.get_full_type(), ".", self.get_name(), "(", "@\"" + self.__target_name + "\")", " = "] self._generate_input_fragments(fragments) fragments.append(";\n") return "".join(fragments) def set_target_name(self, data_name): self.__target_name = data_name class ImplicitExecutorCommand(AbstractInputCommand): def __init__(self): super().__init__() self.__target_name = "" def get_full_type(self): return None @abstractmethod def get_name(self): pass def generate(self): # TODO: some part can be pre-generated fragments = [ self.get_name(), "(", "@\"" + self.__target_name + "\")", " = "] self._generate_input_fragments(fragments) fragments.append(";\n") return "".join(fragments) def set_target_name(self, data_name): self.__target_name = data_name
plate = int(input()) detergent = int(input()) * 2 limit = plate if plate < detergent else detergent i = 0 while i < limit: plate -= 1 detergent -= 1 i += 1 if(plate > detergent): print('Моющее средство закончилось. Осталось', plate, 'тарелок') elif(detergent > plate): print('Все тарелки вымыты. Осталось', detergent / 2, 'ед. моющего средства') else: print('Все тарелки вымыты, моющее средство закончилось')
# Problème : Réaliser une table de multiplication de taile 10x10 en utilisant la liste fournie. # Résultat attendu : un affichage comme ceci : 1 2 3 4 5 6 7 8 9 10 # 1 1 2 3 4 5 6 7 8 9 10 # 2 2 4 6 8 10 12 14 16 18 20 # . . . . . . . . . . . # Indication : L'alignement rectiligne n'est pas une contrainte, tant que la table est visible ligne par ligne c'est ok. # Si vous êtes perfectionnistes faites vous plaisir. liste = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i = 0 n = len(liste) j = 1 somme = 0 while i < n: i= i+ 1 somme=0; while j < n: somme = liste[i]*liste[j] print(somme) j=j+1
row=int(input("enter the num of row")) col=int(input("enter the num of column")) sum_mat=[[0,0,0],[0,0,0],[0,0,0]] matrix1=[] print('enter the value in matrix1') for i in range(row): a=[] for j in range(col): a.append(int(input())) matrix1.append(a) matrix2 = [] print('enter the value in matrix2') for i in range(row): b = [] for j in range(col): b.append(int(input())) matrix2.append(b) print('matrix one') for val in matrix1: for item in val: print(item,end=' ') print() print('matrix2') for value in matrix2: for items in value: print(items,end=' ') print() for i in range(len(matrix2)): for j in range(len(matrix2)): sum_mat[i][j]=matrix1[i][j]+matrix2[i][j] for values in sum_mat: for i in values: print(i,end='') print()
def myfun(str_1,str_2): str_1=str_1.replace(' ','') str_2=str_2.replace(" ",'') if len(str_1)!=len(str_2): return False for char in str_1: if char in str_2: str_2=str_2.replace(char,'') return len(str_2)==0 str_1=input('enter the string first') str_2=input('enter the string second') print(myfun(str_1,str_2))
# Author : Jayavardhan Bairabathina # 2. PROBLEM DEFINITION # ---------------------------------------------- # Sentence:You really cannot repeat three times the word 'because' because 'because' is a conjunction that should not be used in such a way. # Question: Write a program logic to reverse the word "because" and print a sentence without using built-in functions/methods. def reverse_the_word_and_print_sentence(test_str, given_word): ''' A method to reverse the given word and return the string! ''' reversed_word = given_word[::-1] return ((reversed_word).join(test_str.split(given_word))) if __name__ == '__main__': test_str = "You really cannot repeat three times the word 'because' because 'because' is a conjunction that should not be used in such a way." given_word = 'because' print(reverse_the_word_and_print_sentence(test_str, given_word))
from lib.enums import enum import properties class Task: """Represents a single task""" def __init__(self, title, notes = None, parent = None): if title is None: raise ValueError("Task cannot be created without a Title") self.title = title self.children = [] self.notes = notes self.complete = False self.virtual = False self.attributes = {} self.parent = None if parent is not None: parent.add_child(self) def __str__(self): result = self.title if self.notes is not None: result += ' [' + self.notes + ']' if self.complete is not None: result += ' (Completed)' return result @classmethod def create_virtual_task(cls, title = None): """Creates a virtual task, i.e. a task that serves only as the root of a tree or list of tasks""" t = Task('') t.title = title t.virtual = True return t def add_attribute(self, key, value): """Adds an atribute to the attribute list""" if self.virtual: raise Exception("Virtual tasks cannot have attributes") if key in self.attributes: raise KeyError("Attribute {0} already exists".format(key)) self.attributes[key] = value def add_attribute_list(self, attrList): """Adds a whole list of attributes to the task's attribute list. Expects a list of two-element lists, in the form [key, value] e.g. [[key1, value1], [key2, value2], [key3, value3]] """ for kvPair in attrList: self.add_attribute(kvPair[0], kvPair[1]) def add_child(self, task): """ Adds a child task, if it doesn't already have a parent """ if not task.virtual: if task.parent is None: task.parent = self self.children.append(task) else: raise Exception("Task already has a parent") else: raise Exception("Virtual tasks cannot have parents") def add_children(self, children): """Adds a list of children at once""" for child in children: self.add_child(child)
def loading(file_name): print("Loaded weather data from",file_name[0].upper()+file_name[1:-4],"\n") def daily(file_name): date = input("Give a date (dd.mm): ") #06.10 search="2019-"+date[3:]+"-"+date[0:2] with open(file_name, "r") as weather_file: weather_file.readline() for line in weather_file: if search in line: data=line.split(";") print("The weather on",date,"was on average",data[2],"centigrade") print("The lowest temperature was",data[3],"and the highest temperature was",data[4]) print("There was",data[1],"mm rain \n") def statistics(file_name): sum1=0 sum2=0 sum3=0 i=0 with open(file_name,"r") as wf: wf.readline() for row in wf: details=row.split(";") sum1=sum1+float(details[2]) sum2=sum2+float(details[3]) sum3=sum3+float(details[4]) i=i+1 average1=sum1/i average2=sum2/i average3=sum3/i print("The average temperature for the 25 day period was",round(average1,1)) print("The average lowest temperature was",round(average2,1)) print("The average highest temperature was",round(average3,1),"\n") def print_temperature_line(day, month, temp): print(day + "." + month + " ", end="") print(" "*(temp+5) + "-", end="") print() def print_temperature_axis(): print(" ", end="") for i in range(-5,16): print("{:02d} ".format(i), end="") print() while True: print("ACME WEATHER DATA APP") print("""1) Choose weather data file \n2) See data for selected day \n3) Calculate average statistics for the data \n4) Print a scatterplot of the average temperatures \n0) Quit program""") choice=int(input("Choose what to do: ")) if choice==0: break elif choice==1: file_name=input("Give name of the file: ") loading(file_name) elif choice==2: daily(file_name) elif choice==3: statistics(file_name) elif choice==4: with open(file_name,"r") as f: f.readline() for row in f: info=row.split(";") time=info[0] day=time[9:11] month=time[6:8] temp=float(info[2]) temp=round(temp) print_temperature_line(day, month, temp) print_temperature_axis()
from tkinter import * window = Tk() # Get buy/sell data here buy = True if buy: txt = "Buy" color = "green" else: txt = "Sell" color = "red" label = Label(window, text=txt, bg=color, font=("Arial", 50), padx=20, pady=20) label.pack() window.mainloop()
""" Create a fibinacci sequnce, which takes nth starting number,nth ending number and nth number of times repeated. """ def Fibonacci(start,end,step): print(start, end,end=" ") for i in range(step-2): sums = start + end print(sums,end=" ") end = start start = sums def get_number(): try: start = int(input("Please enter the start value: ")) end = int(input("Please enter the end value: ")) step = int(input("Please enter the number of numbers: ")) except ValueError: print("Please enter a whole number !!") return get_number() else: return Fibonacci(start, end, step) get_number()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- height=1.75 weitht=80.5 bmi=weitht/(height*height) print('小明的BMI指数为:%.2f' % bmi) if bmi <18.5: print('过轻') elif bmi>=18.5 and bmi <25: print('正常') elif bmi>=25 and bmi <32: print('过重') else: print('严重肥胖')
#!/usr/bin/env python #Write a Python program to test whether all numbers of a list is greater than a certain number. num = [1, 4, 5] #list of numbers print str("This many items:"),(len(num)) print "Roll Call!" if 4 in num: print str("yes 4 is here") print "Height Check!!" print str("Anyone taller than 10? "),(all(x > 10 for x in num)) print str("Okay anyone shorter than 10?"),(all(x < 10 for x in num)) #I don't really get why x calls the numbers from num but...
#!/usr/bin/env python # user's first and last name and #print them in reverse order with a space between them first = input() second = input() print (second,str(","), first)
#!/usr/bin/env python # 66. Calculate body mass index #BMI = kg/m2 #Added print options to practice classifications again w = (float(input("Input Weight in kg: "))) #weight h = (float(input("Input Height in meters: "))) #height n = round(w / (h * h), 2) print "underweight: ", n <= 18.5 print "normal weight", 18.6 <= n <= 24.9 print "overweight", 25.0 <= n <= 29.9 print "obesity class I", 30.0 <= n <= 34.9 print "obesity class II", 35.0 <= n <= 39.9 print "obesity class III", 40.0 <= n print "don't worry bmi doesn't handle exceptional people very well"
#Python problem 4 #This is a solution to the python poblem 4 where the prgram displays the factorial for the number 10 and adds all the numbers in the answer. #Created by Robert Kiliszewski #01/10/2017 #Import the maths library into the program import math print() #10 Factorial print ("10! = ",math.factorial(10)) print() #giving 'n' the value of 10 factorial myFactorial = math.factorial(10) # Create a list of integers # List is populated from a string that contains the long number from 10! allNumbers = [int(d) for d in str(myFactorial)] #Prints the list of numbers that are in the answer as an array print(allNumbers) print() # Print the sum of the digits in the number 10! print("The sum of all the digits in 10! = ", sum(allNumbers))
import numpy as np def djisktra_slow(): #Initialize largest value of shortest distance to large number maxDist = 1000000 #Load graph from file and populate Path weight matrix #Note that if weight for a path is equal to maxDist it means given path is not connected f = open("djikstra.txt","r") lines = [line.rstrip('\n').split() for line in f] Lij = maxDist*np.ones((len(lines),len(lines)),dtype=int) for g in lines: for j in g: list = j.split(',') if len(list) > 1: Lij[lines.index(g)][int(list[0])-1] = int(list[1]) f.close() #Initialize full graph (use set so that comparison with X can be done irrespective of order #in which nodes are captured by algorithm) V = {i for i in range(1,len(lines)+1)} # Initialize portion of graph which Djikstra algorithm has already seen X = {1} A = {} A[1] = 0 # Initialize counters iteration = 0 cnt = 0 while X != V: LowDist = maxDist LowIdx = 0 for i in X: for j in V: if j not in X: dist = A[i] + Lij[i-1][j-1] cnt += 1 #print(i,j,dist) if dist < LowDist: LowDist = dist LowIdx = j X.add(LowIdx) A[LowIdx] = LowDist iteration += 1 print(iteration,cnt) print(A[7],A[37],A[59],A[82],A[99],A[115],A[133],A[165],A[188],A[197]) djisktra_slow() #1 - There is a shortest path s-t with no repeated vertices; Shortest path may have as many as n-1 vertices #2 - When all edges are distinct powers of 2 #3 - Always #4 - Always terminates but in some cases paths computed will not be shortest; always terminates and in some cases paths computed will be correct shortest path #5 - Djkistra algorithm always terminates
b = 8 B = "Earth" #B will not overwrite b because variables in python are case sensitive print(B) print(b)
# 대입 연산자란 변수에 값을 연산자대로 처리한 다음 반영하는 # 연산자를 의미 # = 은 특정 변수에 값을 대입할 때 사용하며 # += 은 더한 결과 저장, -= 은 뺀 결과 저장, *= 은 곱한결과 저장 # /= 은 나눈 결과 저장, %= 은 출력된 나머지값을 저장 a = 5 a +=1 # a = a + 1 print(a) a -= 3 print(a) a *= 4 print(a) a /= 3 print(a) a %= 5 print(a)
import pickle def save(): f = open('savefile.dat', 'wb') pickle.dump(myPlayer, f, protocol = 2) f.close def load(): global myPlayer f = open('savefile.dat', 'rb') myPlayer = pickle.load(f) f.close def saveprompt(): print("do you wish to save?\n") s = input("> ") while s.lower() not in ("yes", 'no'): print("please select a valid option for saving") print("(yes or no)") if s.lower() == "yes": print("Now saving...") save() elif s.lower() == "no": print("you have chosen not to save") def loadprompt(): print("Do you wish to load? ") s = input("> ") while s.lower() not in ("yes", 'no'): print("please select a valid option for loading") print("(yes or no)") if s.lower() == "yes": print("Now loading...") load() elif s.lower() == "no": print("you have chosen not to load")
# User enters as many races as he/she wants # Program returns the media of the times and the number of races races = 0 timings = [] media = 0 print("Please enter your race timings (minutes) separated by spaces and then press enter.") timings = input() for time in timings: if time == ' ': pass else: try: val = int(time) # Parsing media+=val races+=1 except ValueError: print("A value entered in not an integer. Therefore it won't be used.") # Handle the exception calculated_media = media / races print(f"Your media is: {calculated_media}, in a total of {races} races.")
MENU = { 'sandwich': 0.99, 'coffee': 0.87, 'salad': 3.05 } def user_imput(): print("-- Welcome to the restaurant --") total = 0 option = None found = False while option != '': found = False option = input("Please enter your desired meal: ") if option != '': for name, number in MENU.items(): if name == f'{option}': found = True total += number print(f'{option} costs: {number:.2f}$. Total atm is {total:.2f}$.') if not found: print (f'Damn! We ran out of fresh {option} today!') print(f'Your total to pay is: {total}.') if __name__ == "__main__": user_imput()
# Script gets a string as input and prints the word with more repeated letters def letters(sentence): print(f'Your sentence is: {sentence}') letter_list = [] for letter in sentence: print(word) letter_list_aux = [] letters(input())
def add(a, b): return a+b def min(a,b): return a-b sum = add(5, 6) min = min(5, 6) print(sum, min)
""" Week 2, Day 3: Flood Fill An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. At the end, return the modified image. E x a m p l e Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. N o t e s - The length of image and image[0] will be in the range [1, 50]. - The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. - The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. H i n t - Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels. """ from typing import List class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: oldColor = image[sr][sc] self.image = image self._floodFill(sr, sc, newColor, oldColor) return image def _floodFill(self, sr: int, sc: int, newColor: int, oldColor: int) -> None: self.image[sr][sc] = -1 up, right, down, left = sr - 1, sc + 1, sr + 1, sc - 1 if up >= 0 and self.image[up][sc] == oldColor: self._floodFill(up, sc, newColor, oldColor) if right < len(self.image[0]) and self.image[sr][right] == oldColor: self._floodFill(sr, right, newColor, oldColor) if down < len(self.image) and self.image[down][sc] == oldColor: self._floodFill(down, sc, newColor, oldColor) if left >= 0 and self.image[sr][left] == oldColor: self._floodFill(sr, left, newColor, oldColor) self.image[sr][sc] = newColor class SolutionV2: """ This solution is the proposed one, from LeetCode. It looks much nicer and less convoluteed, compared to my own, but is not necessarily faster. It has same complexity: Time: O(n) - Space: O(n) """ def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: R, C = len(image), len(image[0]) color = image[sr][sc] if color == newColor: return image def dfs(r: int, c: int) -> None: if image[r][c] == color: image[r][c] = newColor if r >= 1: dfs(r - 1, c) if r+1 < R: dfs(r + 1, c) if c >= 1: dfs(r, c - 1) if c+1 < C: dfs(r, c + 1) dfs(sr, sc) return image if __name__ == '__main__': print( SolutionV2().floodFill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2), [[2, 2, 2], [2, 2, 0], [2, 0, 1]], sep='\n' ) print('---') print( SolutionV2().floodFill([[0, 0, 0], [0, 1, 1]], 1, 1, 1), [[0, 0, 0], [0, 1, 1]], sep='\n' ) print('---') # last line of code
""" Week 2, Day 4: Single Element in a Sorted Array You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: [3,3,7,7,10,11,11] Output: 10 Note: Your solution should run in O(log n) time and O(1) space. """ from typing import List class Solution: """ Solution complexities: time is O(n), space is O(1). The solution is fast, but worst case slower than O(log n). """ def singleNonDuplicate(self, nums: List[int]) -> int: last_seen = None for num in nums: if last_seen is None: last_seen = num elif last_seen == num: last_seen = None else: break return last_seen class SolutionV2: """ Solution complexities: time is O(log n), space is O(1). This implementation follows a solution from the LeetCode discussion page: https://leetcode.com/explore/featured/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3327/discuss/628036/Python-Binary-Search-O(logn)-explained """ def singleNonDuplicate(self, nums: List[int]) -> int: lo, hi = 0, len(nums) - 1 while lo < hi: mid = ((hi + lo) >> 2) << 1 if nums[mid] == nums[mid + 1]: lo = mid + 2 else: hi = mid return nums[hi] if __name__ == '__main__': print(SolutionV2().singleNonDuplicate([1, 1, 2, 3, 3, 4, 4, 8, 8]) == 2) print(SolutionV2().singleNonDuplicate([3, 3, 7, 7, 10, 11, 11]) == 10) print(SolutionV2().singleNonDuplicate([1]) == 1) print(SolutionV2().singleNonDuplicate([1, 1, 2]) == 2) print(SolutionV2().singleNonDuplicate([1, 2, 2]) == 1) print(SolutionV2().singleNonDuplicate([1, 2, 2, 3, 3]) == 1) print(SolutionV2().singleNonDuplicate([1, 1, 2, 3, 3]) == 2) print(SolutionV2().singleNonDuplicate([1, 1, 2, 2, 3]) == 3) print(SolutionV2().singleNonDuplicate([1, 2, 2, 3, 3, 4, 4]) == 1) print(SolutionV2().singleNonDuplicate([1, 1, 2, 2, 3, 3, 4]) == 4) print(SolutionV2().singleNonDuplicate([1, 1, 2, 3, 3, 4, 4]) == 2) print(SolutionV2().singleNonDuplicate([1, 1, 2, 2, 3, 4, 4]) == 3) print(SolutionV2().singleNonDuplicate([3, 3, 7, 7, 10, 11, 11]) == 10) # last line of code
""" LeetCode 30-Day Challenge, May 2020, Week 1, Day 4 Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary. For a given number N in base-10, return the complement of it's binary representation as a base-10 integer. Example 3: Input: 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. Example 4: Input: 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. N o t e s 1. The given integer is guaranteed to fit within the range of a 32-bit signed integer. 2. You could assume no leading zero bit in the integer’s binary representation. """ def findComplement(num: int) -> int: return int(''.join([str((int(b) + 1) % 2) for b in bin(num)[2:]]), 2) def findComplement_v2(num: int) -> int: if not num: return 1 return ~num & sum([2 ** b for b in reversed(range((num).bit_length()))]) def findComplement_v3(num: int) -> int: return ~num & max(1, 2 ** (num).bit_length() - 1) def findComplement_v4(num: int) -> int: """The lLeetCode solutions runner judges this to be the fastest of all four.""" return num ^ max(1, 2 ** (num).bit_length() - 1) if __name__ == '__main__': print(findComplement_v4(5), 2) print(findComplement_v4(1), 0) print(findComplement_v4(7), 0) print(findComplement_v4(10), 5) print(findComplement_v4(0), 1) print(findComplement_v3(0), 1) print(findComplement_v2(0), 1) print(findComplement(0), 1) # last line of code
""" A node type for singly linked lists. """ class ListNode: def __init__(self, val=0, next_=None): self.val = val self.next = next_ def __str__(self): s = [f'{self.val} -> '] walker = self.next while walker is not None: s.append(f'{walker.val} -> ') walker = walker.next s.append('None') return ''.join(s) # last line of code
#Will continue tomorrow at '8.4 Skriv transaktioner till filen' # Planning : # Imports from functions import * # Functions check_file_exists() read_file() # Variabler # Main loop # Input of text # Write it in a file # Read the file # Complete the program while True: meny = ("\n#######################" "\n# Lilla banken" "\n# Meny" "\n# Saldo: {} kr" "\n#######################" "\n1. Visa saldo" "\n2. Gör en insättning" "\n3. Gör ett uttag" "\n4. Nollställ kontot" "\n0. Avsluta programmet" "\nGör ditt val: ".format(balance())) val = validate_int(meny, "Felaktig inmatning !") # Val 0 if val == 0: break #Val 1 elif val == 1: print(print_transactions()) # Val 2 elif val == 2: deposit = validate_int("Ange hur mycket du vill sätta in: ", "Felaktig inmatning !") if deposit > 0: add_transaction(deposit, True) print("Tack för din insättning på {}kr".format(deposit)) else: print("En insättning måste vara större än 0.") # Val 3 elif val == 3: withdraw = validate_int("Ange hur mycket du vill ta ut: ", "Felaktig inmatning !") if withdraw <= balance() and withdraw >= 0: add_transaction(-withdraw, True) print("Uttag goodkänt! Nytt saldo {}".format(balance())) elif withdraw < 0: print("Uttaget måste vara större än 0.") else: print("Uttaget får inte vara större än saldot. Uttag medgs ej") # Val 4 elif val == 4: os.remove(filename) # Tar bort filen transactions.clear() # Töm listan read_file() # Skapa filen och läs in den else: print("Felaktigt val !") print("Tack för ditt besök, välkommen åter!")
"""Argument parser""" """Command : status, start [prog_name], stop [prog_name], restart [prog_name], reload, shutdown""" class CmdParser(): """ A class which parse arguments of our program. """ def __init__(self): """ Initialize attibute for the Parser """ self.command = [] self.multi_param_cmd = ["status", "start", "stop", "restart", "exit"] def run(self, args): """ main parsing of argument parser [tm restart all]""" if not args: return self.command if args[0] == "shutdown" or args[0] == "reload": self.command.append(args[0]) if len(args) > 1: print(f"Error: {args[0]} accepts no arguments") elif self._check_multi_param(args): for arg in args: self.command.append(arg) return self.command def _check_multi_param(self, args): """ for start, stop restart status """ for i in range(len(self.multi_param_cmd)): if self.multi_param_cmd[i] == args[0]: return True print (f"Error: {args[0]}, unknow command" ) return False
#warning print "*** POUR LE BON FONCTIONNEMENT DU JEU, VERIFIEZ QUE " print " VOTRE TOUCHE VER.MAJ EST DESACTIVE ***" print "-----------------------------------" import sys def clear(): sys.stdout.write('\033[2J') sys.stdout.write('\033[H') sys.stdout.flush() raw_input("Appuyez sur [ENTRER] pour demmarer") clear() #INTRODUCTION import time print time.strftime('%d/%m/%y %H:%M',time.localtime()) print nom=raw_input("Quel est votre nom : ") print print "BIENVENUE " + nom.upper() introqst=raw_input("POUR SAUTER L'INTRODUCTION APPUYEZ SUR [a] SINON SUR [ENTER] ") if introqst=="a": True else: clear() print "------------------" print "Je suis le Dr. Robet Wonderstone;" print "Specialiste des phenomenes psychiques du suconscient." print print "Ma specialite ? Les reves." print "Les reves sonts intimement lies a la vie du reveur" print print "Pourtant, dans la majorite du temps, vous ne vous rappellez pas de vos reves." print "Ils ne sont qu'un produit de notre imagination ..." rev=raw_input("N'est-ce pas ? (oui/non): ") clear() print "------------------- " print "Peu importe..." print "J'ai decouvert que les reves, meme s'ils parraissent anodins," print "sont bien plus que des films qui jouent dans nos tetes." print "..." print "ILS SONT REELS !" print print "Desole, je m'emporte.." print print "En fait, j'ai developpe un systeme qui permet de revivre ses reves." print "L'etude du cerveau a montre que beaucoup de personnes se souviennent" print "de leurs reves si on les reveillent pendant le sommeil paradoxal. " print "C'est a ce moment qu'il devient possible de les extraires" print print "Cependant il y a une faille." print print "Le dernier sujet a eu une crise d'epillepsie au moment critique de l'extraction..." print "J'ai voulu annuler le processus, mais il etait trop tard.." print "Mort Cerebrale" raw_input("Appuyez sur [ENTRER]") clear() print "Toutefois j'ai remarque un phenomene etrange." print "Malgre le coma de type 5 de mon patient, le reve ne s'est pas arrete." print "C'est comme si son esprit s'etait detache. " print "Comme s'il etait toujours vivant, mais dans son reve " print print "Apres etude, j'en suis venu a une theorie. Si on arrive a " print "retourner dans le reve et a retrouver son esprit" print "... ou quelque chose du genre," print "il sera probablement possible de le faire revenir.." print #start print "J'ai alors modifie la machine pour pouvoir introduire" print "un second sujet dans le reve en cours." jouer=raw_input("et pour cela j'ai besoin de votre aide. [o/n]: ") if jouer=="o": print print "Tres biens " + nom + " !" print "Nous n'avons pas de temps a perdre." print "Debutont..." True elif jouer=="n": print "Etes-vous certain ? :" quit=raw_input("[o/n] : ") if quit=="o": print "Au revoirs, alors" import sys sys.exit("[FIN DE LA PARTIE]") elif quit=="n": print print "Nous n'avons pas de temps a perdre." print "Debutont..." print "===============" #Debut raw_input("Appuyez sur [ENTRER]") clear() print ".............................." print "[Une heure plus tard]" print ".............................." print "Allonge toi ici " + nom print "Je t'injecte un somnifere.." print "Il fera effet dans quelques minutes" print "Tout a l'heure il sera possbile de comuniquer enssemble," print "je te guiderai tous le long du periple." print print "Ton subconcient sera en lien avec le systeme et avec le reve de mon ex-patient" print "Je te donnerai plus de detail lorsque tu aura atteint le sommeil paradoxal" print print "Ah et j'oubliais !" print "Dans un reve normal, si tu meurt tu te reveille, mais dans " print "celui d'un autre ce n'est p...." print print "(VOUS VOUS ETES ENDORMI)" print raw_input("Appuyez sur [ENTRER]") clear() print print '\033[0;32m [CONSOLE R.E.V.E - BETA 2.1.4 :]\033[1;m' print '\033[0;32m [EN ATTENTE DU SOMMEIL PARADOXAL...]\033[1;m' print '\033[0;32m [...]\033[1;m' print '\033[0;32m [TEMPS ECOULE : 270 MIN]\033[1;m' print '\033[0;32m [DEMARAGE DE LA SEQUENCE R.E.V.E]\033[1;m' print '\033[0;32m ....\033[1;m' print '\033[0;32m ......\033[1;m' print '\033[0;32m ..........\033[1;m' print '\033[0;32m ..............\033[1;m' print '\033[0;32m ................\033[1;m' print '\033[0;32m ...................\033[1;m' print '\033[0;32m [Connexion etablie]\033[1;m' print raw_input("Appuyez sur [ENTRER]") clear() print print "(VOUS ETES DANS UNE PIECES BLANCHE, VOUS NE POUVEZ RIEN DISTINGUER" print "MEME PAS LES MUR OU LE PLANCHE. RIENQUE CETTE LUMIERE ENVOUTANTE)" print print "RE-Bonjour " + nom print "Tu est desormais dans le R.E.V.E" print "Tu n'a malheureusement pas la capacite physique de te deplacer." print "Dans le reve, tu pourra toutefois choisir quoi faire." print raw_input("appuyez sur [ENTRER]") clear() print print "J'entrerai les donnes dans la console pour que tu puisse interagir." print "Je dois par contre t'avertir qu'il faudra etre tres vigillant lors" print "de la saisie d'information..." print print "Mon systeme n'etant pas tres stable, une erreur pourrais etre fatale" print "Ainsi quand tu a le choix entre deux option, tu dois absolument choisir" print "l'une ou l'autre et ce de facon exacte" print print "Testons tout de suite !" a=raw_input("Fais un [a] puis apuis sur [entrer]: ") print if a=="a": print "ca fonctionne" else: print "Tu a fais une erreur, il faudra faire attention" print "une fois dans le reve sa pourrait te tuer !" print "Je crois que tu est pres on entre dans le reve ?" play=raw_input("Oui: apuyez sur [a] - Non: apuyez sur [b] : ") if play=="a": clear() print "C'est parti !" else: clear() print "On a plus le temps de parler, de toutes facon tu ne peux plus reculer" print "C'est parti !"
import queue class merged_sort: def __init__(self, x1, x2): self.x1 = x1 self.x2 = x2 def __lt__(self, other): return self.x1 < other.x1 n = int(input()) left = [] l = int(input()) for _ in range(l): x,y = map(float, input().split()[:2]) left.append((x,y)) r = int(input()) right = [] for _ in range(r): x,y = map(float, input().split()[:2]) right.append((x,y)) count_array = [0] * (l + r) merged_array = left + right pq = queue.PriorityQueue() for result in merged_array: pq.put(merged_sort(result[0], result[1])) results = [] while not pq.empty(): imp = pq.get() results.append(imp.x2) # print(results) count = 0 for i in range(len(results)): for j in range(i+1): if results[i] > results[j]: if results[i] > results[j]: count += 1 count_array[i] = count count = 0 for _ in range(len(count_array)): print(count_array[_])
import random class Chromosome: """ Class, representing a chromosome. Each chromosome is 10 bits long: 1 bit for sign, 2 bits for integer part and 7 bits for fractional part. Since numbers not larger than 127 can be encoded with 7 bits and in my chromosome representation the fractional part is encoded "as it is" than the binary representation of fractional part can not be larger than 0b01100011. """ def __init__(self, x=None): """ The chromosome can be created randomly (if no parameter was given) or from a 10 bit integer number (x) by rules, described above. """ if x is None: self.sign = random.randint(0, 1) self.integer_part = random.randint(0, 3) self.fractional_part = random.randint(0, 99) else: self.sign = (x & 512) >> 9 self.integer_part = (x & 384) >> 7 self.fractional_part = x & 127 if self.integer_part > 99: self.integer_part = 99 def __str__(self): return str(round(self.get_float_representation(), 2)) def get_binary_representation(self): """ Return binary representation of a chromosome for genetic algorithm. """ binary_representation = (self.sign << 9) + \ (self.integer_part << 7) + \ self.fractional_part return binary_representation def get_float_representation(self): """ Return float representation of a chromosome to pass it to function. """ if self.sign == 1: return -1 * (self.integer_part + self.fractional_part * (10 ** (-2))) else: return self.integer_part + self.fractional_part * (10 ** (-2)) # DEBUG def main(): c = Chromosome() print(c.get_float_representation()) print(bin(c.get_binary_representation())) d = Chromosome(c.get_binary_representation()) print(d.get_float_representation()) print(bin(d.get_binary_representation())) if __name__ == '__main__': main()
import random class Point: """ Sert à définir un point pour et sans le training coord,label """ #Constructeur def __init__(self,canvas_width,canvas_height): #Assigne des coordonnées random selon la width et l'height données self.coord = (random.uniform(0,canvas_width),random.uniform(0,canvas_height)) if self.coord[0] > self.coord[1]: #Selon la règle de l'équation self.label = 1 else: self.label = -1
def romanToInt(s: str) -> int: r_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} i = 0 res = 0 while i < len(s): #getting the number equivalent to the roman number num1 = r_dict.get(s[i]) if (i+1 < len(s)): num2 = r_dict.get(s[i+1]) #if the number preceding the next number is greater, just adding the numbers to the result if ( num1 >= num2): res = res + num1 i = i+1 #if the number preceding the next number is lesser, then subtracting the first number from the second # for example IX = 10-1 = 9; IV = 5-1 = 4; whereas else: res = res + (num2 - num1) i = i+2 else: res = res + num1 i = i+1 print(res) return res if __name__ == "__main__": string = str(input("Enter the roman number")) romanToInt(string)
''' Neighbourhood Data Object Purpose: - Creates a 3 x 3 cell instance from the terrain Filename: - neighbourhood.py Input: - Terrain surface Raster data (excluding headers) - Terrain resolution / cell size - Terrain processing cell row number - Terrain processing cell column number Output: - Instance of Neighbourhood class Classes: - Neighbourhood - a 3 x 3 block of cells with the processing cell located in the centre (1,1) Methods: - slope_aspect - sink_fill - get<var name> (multiple) - Set<var name> (multiple). ''' import math #---------------------------------------------------------- # Neighbourhood Class #---------------------------------------------------------- class Neighbourhood(): ''' Processing an instance of a 3 x 3 Neighbourhood. ''' def __init__(self, terrain, resolution, y, x): ''' Initialisation of the Neighbourhood instance with variables relating to: - 3 x 3 neighbourhood grid - Slope (percentage & degrees) - Aspect Triggered by: - tothemaxmain.py Input: - Terrain Raster data (excluding headers) - Terrain resolution / cell size - Terrain processing cell row number - Terrain processing cell column number Output: - 3 x 3 cell instance from the terrain data ''' #--------------------------------------------------------- # Initialise variables. #--------------------------------------------------------- self.resolution = resolution self.y_boundary = len(terrain) - 1 self.x_boundary = len(terrain[0]) - 1 self.edge = None self.slope = -math.inf self.slope_perc = -math.inf self.slope_deg = -math.inf self.aspect = math.nan self.d8 = [] #--------------------------------------------------------- # Construct 3 x 3 Neighbourhood grid. # Identify, if applicable, direction of adjacent edge. #--------------------------------------------------------- if y == 0 and x == 0: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'NW' elif y == 0 and x < self.x_boundary: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'N' elif y == 0: self.neighbourhood = [ [terrain[y][x]] * 3, [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y][x]]] self.edge = 'NE' elif y < self.y_boundary and x == 0: self.neighbourhood = [ [terrain[y][x], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'W' elif y < self.y_boundary and x < self.x_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y+1][x+1]]] self.edge = 'No Edge' elif y < self.y_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y][x]], [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y+1][x-1], terrain[y+1][x], terrain[y][x]]] self.edge = 'E' elif x == 0: self.neighbourhood = [ [terrain[y][x], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x], terrain[y][x], terrain[y][x+1]], [terrain[y][x]] * 3] self.edge = 'SW' elif x < self.x_boundary: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y-1][x+1]], [terrain[y][x-1], terrain[y][x], terrain[y][x+1]], [terrain[y][x]] * 3] self.edge = 'S' else: self.neighbourhood = [ [terrain[y-1][x-1], terrain[y-1][x], terrain[y][x]], [terrain[y][x-1], terrain[y][x], terrain[y][x]], [terrain[y][x]] * 3] self.edge = 'SE' #--------------------------------------------------------- # Seperate the centre Neighbourhood cell from the # neighbours and order the neighbours for D8 slope # calculation purposes, starting with the East # neighbour and working clockwise. #--------------------------------------------------------- self.centre = self.neighbourhood[1][1] # Processing cell self.neighbours = [ self.neighbourhood[1][2], # East neighbour self.neighbourhood[2][2], # South-East neighbour self.neighbourhood[2][1], # South neighbour self.neighbourhood[2][0], # South_West neighbour self.neighbourhood[1][0], # West neighbour self.neighbourhood[0][0], # Noth_West neighbour self.neighbourhood[0][1], # North neighbour self.neighbourhood[0][2]] # North-East neighbour def slope_aspect(self, d8_dict, nodata_value): ''' Use this method to identify the maximum downhill gradient of a Neigbourhood, and the applicable aspect using D8 notation. Start with the East neighbour and work clockwise. Triggered by: - tothemaxmain.py Input: - D8 dictionary - Geo-referenced NoData value Output: - Slope calculation as a percentage - Slope calculation in degrees - Aspect of max. gradient (first cell if more than 1 with the same) - List of D8 directions containing the same maximum slope ''' # --Straight edge-- ---------Corner edge-------- DICT_EDGE = {0:('NE', 'E', 'SE'), 1:('NE', 'E', 'SE', 'S', 'SW'), 2:('SW', 'S', 'SE'), 3:('NW', 'W', 'SW', 'S', 'SE'), 4:('NW', 'W', 'SW'), 5:('SW', 'W', 'NW', 'N', 'NE'), 6:('NW', 'N', 'NE'), 7:('NW', 'N', 'NE', 'E', 'SE')} dist_adjacent = self.resolution dist_diagonal = math.sqrt((self.resolution**2) * 2) #--------------------------------------------------------- # Starting from the East neighbour and working clockwise. #--------------------------------------------------------- for n, neighbour in enumerate(self.neighbours): # Do not use if upward gradient if self.centre == nodata_value: break # Do not use if neighbour contains NoData if self.neighbours[n] == nodata_value: continue # Do not use if neighbour is outside of the boundaries if self.edge in DICT_EDGE[n]: continue # Do not use if upward gradient if self.centre - self.neighbours[n] < 0: continue # Is cells comparison orthogonl or diagonal to each other? # Note: diagonal is when n = 1, 3, 5 or 7) if n % 2 == 0: if (self.centre - self.neighbours[n]) / dist_adjacent \ > self.slope: self.slope = (self.centre - self.neighbours[n]) \ / dist_adjacent self.d8 = [n] self.aspect = d8_dict[2**n] elif (self.centre - self.neighbours[n]) / dist_adjacent \ == self.slope: self.d8.append(n) else: if (self.centre - self.neighbours[n]) / dist_diagonal \ > self.slope: self.slope = (self.centre - self.neighbours[n]) \ / dist_diagonal self.d8 = [n] self.aspect = d8_dict[2**n] elif (self.centre - self.neighbours[n]) / dist_diagonal \ == self.slope: self.d8.append(n) #--------------------------------------------------------- # No downhill slope found #--------------------------------------------------------- if math.isinf(self.slope): self.slope_perc = math.nan self.slope_deg = math.nan else: self.slope_perc = self.slope * 100 self.slope_deg = math.atan(self.slope) * 180 / math.pi def sink_fill(self, d8_dict): ''' Use this method to fill the processing cell when it does not have any neighbours that lead downhill from it. Triggered by: - tothemaxmain.py Input: - D8 dictionary Output: - Slope calculation as a percentage - Slope calculation in degrees - Aspect calculation - D8 direction calculation ''' #--------------------------------------------------------- # If the processing cell is not an an edge cell, modify # height value equal to the lowest height of the 8 # neighbours. Then assign slope and aspect. #--------------------------------------------------------- if self.edge == 'No Edge' and self.neighbours.count(-math.inf) != 8: self.slope = 0.0 self.d8 = [self.neighbours.index( min(n for n in self.neighbours if n != -math.inf))] self.aspect = d8_dict[2**self.d8[0]] #--------------------------------------------------------- # If the cell is now filled, do more slope calculations. #--------------------------------------------------------- if math.isinf(self.slope) is False: self.slope_perc = self.slope * 100 self.slope_deg = math.atan(self.slope) * 180 / math.pi #------------------------------------- # Get & Set methods #------------------------------------- @property def edge(self): '''Get the cell edge indicator''' return self._edge @edge.setter def edge(self,val): '''Set the cell edge indicator''' self._edge = val @property def y_boundary(self): '''Get the y axis boundary''' return self._y_boundary @y_boundary.setter def y_boundary(self,val): '''Set the y axis boundary''' self._y_boundary = val @property def x_boundary(self): '''Get the x axis boundary''' return self._x_boundary @x_boundary.setter def x_boundary(self,val): '''Set the x axis boundary''' self._x_boundary = val @property def slope(self): '''Get the cell to cell rise over run value''' return self._slope @slope.setter def slope(self,val): '''Set the cell to cell rise over run value''' self._slope = val @property def slope_perc(self): '''Get the cell to cell slope as a percentage value''' return self._slope_perc @slope_perc.setter def slope_perc(self,val): '''Set the cell to cell slope as a percentage value''' self._slope_perc = val @property def slope_deg(self): '''Get the cell to cell slope in degrees value''' return self._slope_deg @slope_deg.setter def slope_deg(self,val): '''Set the cell to cell slope in degrees value''' self._slope_deg = val @property def aspect(self): '''Get the cell aspect value''' return self._aspect @aspect.setter def aspect(self,val): '''Set the cell aspect value''' self._aspect = val
from tkinter import * root = Tk() #create an object that is a blank window topFrame = Frame(root) #make invisible container and put it in the main window (root) topFrame.pack() #place somewhere in main window bottomFrame = Frame(root) bottomFrame.pack(side = BOTTOM) button1 = Button(topFrame, text="Button 1", fg="red") button2 = Button(topFrame, text="Button 2", fg="white") button3 = Button(topFrame, text="Button 3", fg = "green") button4 = Button(bottomFrame, text = "Button 4", fg = "purple") #display button on screen button1.pack(side=LEFT) button2.pack(side=LEFT) button3.pack(side=LEFT) button4.pack(side=BOTTOM) one = Label(root, text="One", bg = "red", fg="white") one.pack() two = Label(root, text="Two", bg="green", fg="black") two.pack(fill=X) three = Label(root, text="Three", bg="blue", fg="white") three.pack(side=LEFT, fill=Y) label_1= Label(root, text="Name") label_2= Label(root, text="Password") label_3= Label(root, text="Name") root.mainloop() #put in inifinite loop so it never ends. Window will continue to display until you close it.
from functools import reduce #1.map def function1(list): list = list[0].upper() + list[1:].lower() return list L1 = ['adam', 'LISA', 'barT'] L2 = list(map(function1, L1)) print(L2) #2.prod def prod(list): return reduce(lambda x, y: x*y,list) L3 = [1,2,3,4] print(prod(L3))
from src.state import State, Turn import chess def init_board(): """ Initialize checkers board (8x8) """ board = ['w', '-', 'w', '-', 'w', '-', 'w', '-', '-', 'w', '-', 'w', '-', 'w', '-', 'w', 'w', '-', 'w', '-', 'w', '-', 'w', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 'b', '-', 'b', '-', 'b', '-', 'b', 'b', '-', 'b', '-', 'b', '-', 'b', '-', '-', 'b', '-', 'b', '-', 'b', '-', 'b'] return board def print_board(board): for i in range(56, -1, -8): for j in range(8): print(board[i+j], end=' ') print() def game_over(board): """ 1: num_pieces >=4 2: num_pieces = 1 -> 1 wins """ b_counter = 0 w_counter = 0 for i in range(64): if board[i] == "b" or board[i] == "B": b_counter += 1 elif board[i] == "w" or [i] == "W": w_counter += 1 state = State(board, Turn.WHITE, []) if w_counter == 0 or (b_counter > 3 and w_counter < 2) or len(state.get_states()) == 0: print("GAME OVER! You lost!") return True if b_counter == 0 or (w_counter > 3 and b_counter < 2): print("CONGRATS! You won!") return True return False def init_gui_board(board): board.set_piece_at(chess.B8, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.D8, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.F8, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.H8, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.A7, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.C7, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.E7, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.G7, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.B6, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.D6, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.F6, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.H6, chess.Piece.from_symbol('k'), chess.KING) board.set_piece_at(chess.A3, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.C3, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.E3, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.G3, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.B2, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.D2, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.F2, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.H2, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.A1, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.C1, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.E1, chess.Piece.from_symbol('K'), chess.KING) board.set_piece_at(chess.G1, chess.Piece.from_symbol('K'), chess.KING) return board
import sys class GarageHeap: ''' Garage Heap that orders jobs by a given comparison function. ''' __slots__ = 'data', 'size', 'above_fn' def __init__(self, above_fn): ''' Constructor takes a comparison function. :param above_fn: Function that takes in two heap objects and returns true if comparison returns true in the above function. ''' self.data = [] self.size = 0 self.above_fn = above_fn def insertHeap(self, job): ''' Inserts a job into the heap and increases its size. :param job: job to be inserted ''' self.data.append(job) self.size += 1 self.bubbleUpHeap(self.size-1) def parent(self,position): ''' Function to compute the parent location of a position. :param position: position in the heap :return: position of parent ''' return (position-1)//2 def bubbleUpHeap(self, position): ''' Starts from the given position and moves the job up into heap as far as necessary. :param position: Place to start bubbling up from. ''' while position > 0 and self.above_fn(self.data[position], self.data[self.parent(position)]): self.data[position],self.data[self.parent(position)] = \ self.data[self.parent(position)],self.data[position] position = self.parent(position) def popHeap(self): ''' Checks if job on top is already done or not, if its done then keep popping jobs till you get unfinished job and then remove that job and return. :return: Unfinished Job on top of the heap ''' temp = self.data[0] while temp.done is True and self.size > 0: self.__popHeap() temp = self.data[0] if self.size > 0: self.__popHeap() temp.done = True else: print("No more jobs to do!!") sys.exit(0) return temp def __popHeap(self): ''' Helper function for popping job from the heap. :return: None ''' self.size -= 1 if self.size > 0: self.data[0] = self.data.pop(self.size) self.bubbleDownHeap(0) def bubbleDownHeap(self, position): ''' Starts from the given position and moves the job as far down the heap as necessary. :param position: Place to start bubbling down from. :return: None ''' swap = self.topHeap(position) while swap != position: self.data[position], self.data[swap] = self.data[swap], self.data[position] position = swap swap = self.topHeap(position) def topHeap(self, position): ''' Finds the value among position and it's two children that should be at the top and correctly handles end-of-heap issues. :param position: Index of job :return: position of top value ''' leftChild = position*2+1 rightChild = position*2+2 if leftChild >= self.size: return position if rightChild >= self.size: if self.above_fn(self.data[position], self.data[leftChild]): return leftChild else: return position if self.above_fn(self.data[leftChild], self.data[rightChild]): if self.above_fn(self.data[position], self.data[leftChild]): return position else: return leftChild else: if self.above_fn(self.data[position], self.data[rightChild]): return position else: return rightChild
import openning as open import guess import guess2 import time open.show_robot()#显示机器人 print('接下来我会对你稍微有个了解') time.sleep(2)#程序暂停5秒 name=open.ask()#询问年龄 print('-------------------------') print('''您可以输入: 几点了?------用来查询当前时间 你好----------可以向你问好 天气----------查询当前天气 猜数字--------进入小游戏猜数字 高级猜数字-----进入小游戏高级猜数字 关于作者-------可了解Banxia 88------------退出小夏 帮助----------查看帮助''') while (True): print(f'你好{name},请问有什么可以帮您?') order=input('') print('知道了') if order == "几点了?": open.show_time() elif order=='帮助': open.help() elif order == "你好": open.hello(name) #问好 elif order=="88": print('好的再见') break#跳出循环 elif order=='天气': open.tianqi() elif order=='彩蛋': print('其实我真的是一个价值百万的人工智能机器人') user_input=input() print(open.ai_talk(user_input)) elif order=='猜数字': guess.guess1() elif order=='高级猜数字': guess2.guess2() elif order=='关于作者': print('''我是Banxia 这是我初上手Python的一个小程序 应该在大佬眼里很简陋了 您可以访问:https://banxia.ink了解我更多 期待和您成为朋友''') else: print('小夏会努力学习这些个问题,请再给我一点时间!') #print(open.ai_talk(order)) print('-----------------------')
# Released to students: validator for README import sys def main(argv): if len(argv) == 1: print(processReadMe(argv[1])) elif len(argv) == 0: print(processReadMe()) else: print("Usage Error: python readme_validator.py [*optional* path_to_readme]") def processReadMe(path="README"): try: fin = open("README", "r") except FileNotFoundError: return "README not found." line = fin.readline().strip() if len(line) <= 1: return "You must have a team name." i = 0 while True: line = fin.readline().split() if len(line) == 0 or len(line[0]) == 0: break; sid = line[0] if i >= 4: return "You have too many students on your team." if len(sid) != 8 or not sid.isdigit(): return "The {0}-th ID is invalid".format(i) i += 1; return "instance ok" if __name__ == '__main__': main(sys.argv[1:])
s=raw_input('enter a string') s1="" x=len(s) for i in s: s1+=s[x-1] x-=1 print s1
n=input('enter no of even numbers') count=0 for i in range(0,n,2): print i count=count+1 print count
x = 123456 epsilon = 0.01 step = epsilon**2 numGuesses = 0 ans = 0.0 while abs(ans**2 - x) >= epsilon and ans*ans <= x: ans += step numGuesses += 1 print 'numGuesses =', numGuesses if abs(ans**2 - x) >= epsilon: print 'Failed on square root of', x else: print ans, 'is close to square root of', x
#write a program which uses previousely defined funciton in # problem 2 & 3 to print the reverse of a string and number after a swapping import swapping from stringReversal import reversestring swapping.swappingNumbers(124,36) print reversestring("best government")
i=raw_input('enter a number ') print type(i) print 5*int(i) print str(5)+ '*' + str(i) + '=' + str(5*i)
n=input('enter a number to print backwards ') for i in range(1,n): if n%i!=0: print i else:
n=input('enter a number') x=input('enter a number') y=input('enter a number') def fun(n): if (n%2==0): print n,'is even' elif(n%2!=0): print n,'is odd' fun(n) def swap(x,y): print x,y temp=0 temp=x x=y y=temp return x,y #swap(x,y) print swap(x,y)
y=float(raw_input('enter a number')) epsilon =0.01 guess=y/2.0 while abs(guess*guess-y)>=epsilon: guess=guess-(((guess**2)-y)/(2*guess)) print (guess) print 'Square root of',y,'is about ',guess
n=input('enter a number') def fun(n): if (n%2==0): print n,'is even' elif(n%2!=0): print n,'is odd' fun(n)
# @Author: Antero Maripuu Github:<machinelearningxl> # @Date : 2019-07-15 17:55 # @Email: antero.maripuu@gmail.com # @Project: Coursera # @Filename : Homework_1.py import numpy as np import pandas as pd df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) print(df) print() print(df.rename(index=str, columns={"A": "a", "B": "c"}))
#Write your code below this row 👇 sum = 0 for n in range (2,101,2): sum += n print (sum) sum2 = 0 for n in range (1,101): if n % 2 == 0: sum2 += n print (sum2)
import math def is_prime(n): """ from an answer # https://stackoverflow.com/questions/18833759/python-prime-number-checker # bruteforce check """ if n <= 2: return True if n % 2 == 0: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) # from an answer # https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python class ECMPoint(object): O = POINT_INFINITY = "inf" def __init__(self, x: int, y: int, ec: 'EllipticCurveModulo'): self.x = x self.y = y self.ec = ec def __mul__(self, mult: int): # dumb mult result = self.ec.point(self.x, self.y) for i in range(mult): result = self.ec.ec_add(result, self) return result def __add__(self, p: 'ECMPoint'): return self.ec.ec_add(self, p) def __sub__(self, p: 'ECMPoint'): return self.ec.ec_add(self, self.ec.ec_inv(p)) def __invert__(self): return self.ec.ec_inv(self) def __repr__(self): return "ECMPoint({}, {})".format(self.x, self.y) def __eq__(self, p: 'ECMPoint'): return p is not None and p != ECMPoint.O and self.x == p.x and self.y == p.y and self.ec == p.ec def __hash__(self): return hash((self.x, self.y)) # elliptic curve like y^2 = x^3 + a*x + b class EllipticCurveModulo(object): class FullPointIter(object): def __init__(self, ec: 'EllipticCurveModulo'): self.x = 0 # type: int self.ec = ec self.make_inverse = False self.point_cache = None # type: ECMPoint self.squares_y = dict([(y**2 % ec._mod, y) for y in range(int(ec._mod/2 + 1))]) def next(self) -> ECMPoint: while self.x < self.ec._mod: not_ok = True if self.make_inverse: self.x += 1 if self.point_cache.y != 0: not_ok = False self.point_cache.y = -self.point_cache.y % self.ec._mod else: while not_ok: y = self.squares_y.get(self.ec.eval_x(self.x)) if y is None: self.x += 1 else: not_ok = False self.point_cache = self.ec.point(self.x, y) self.make_inverse = not self.make_inverse if not not_ok: return self.ec.point(self.point_cache.x, self.point_cache.y) raise StopIteration() def __iter__(self): return self def __next__(self): return self.next() class PointIter(object): def __init__(self, gen_point: ECMPoint, ec: 'EllipticCurveModulo'): self.gen_point = gen_point self.inter_point = None # type: ECMPoint self.ec = ec self.max_gen = 1 def next(self) -> ECMPoint: if self.inter_point != ECMPoint.O: if self.inter_point is not None: self.inter_point = self.gen_point + self.inter_point else: self.inter_point = self.ec.point(self.gen_point.x, self.gen_point.y) return self.inter_point if self.inter_point == ECMPoint.O else self.ec.point(self.inter_point.x, self.inter_point.y) else: raise StopIteration() def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def __init__(self, a: int, b: int, mod: int): self._mod = mod self._a = a self._b = b self.__size__ = None # type: int def old_point_begin(self) -> 'PointIter': for x in range(0, self._mod): try: p = self.eval(x) return EllipticCurveModulo.PointIter(p, self) except ValueError: pass def point_begin(self) -> 'FullPointIter': return EllipticCurveModulo.FullPointIter(self) def eval_x(self, x: int) -> int: x = x % self._mod return (x ** 3 + self._a * x + self._b) % self._mod def eval(self, x) -> ECMPoint: y_square = self.eval_x(x) # find a square root by brute force for y in range(self._mod): if y**2 % self._mod == y_square: return self.point(x, y) raise ValueError("given x cannot evaluate a point (no square root from {} modulo {})".format(y_square, self._mod)) def check(self, crypto_check: bool = True, raise_error=True) -> bool: if self._mod <= 2: if raise_error: raise ValueError("_mod value '{}' is incorrect (<=2)!".format(self._mod)) return False if not is_prime(self._mod): if raise_error: raise ValueError("_mod value '{}' is incorrect (not prime)!".format(self._mod)) return False if crypto_check and ((4*self._a**3 % self._mod) + (27*self._b**2 % self._mod) % self._mod) % self._mod == 0: if raise_error: raise ValueError("EC is singular: 4*a^3 + 27*b^2 is zero mod p (crypto check) " "with a={},b={},p={}".format(self._a, self._b, self._mod)) return False return True def valid(self, p: ECMPoint): """ Determine whether we have a valid representation of a point on our curve. We assume that the x and y coordinates are always reduced modulo p, so that we can compare two points for equality with a simple ==. """ if p == ECMPoint.O: return True elif p.ec != self: return False else: return ((p.y ** 2 - (p.x ** 3 + self._a * p.x + self._b)) % self._mod == 0 and 0 <= p.x < self._mod and 0 <= p.y < self._mod) def point(self, x, y) -> ECMPoint: return ECMPoint(x, y, self) @property def size(self) -> int: if self.__size__ is None: self.__size__ = sum(1 for _ in self.point_begin()) # type: int return self.__size__ def size_hasse_check(self) -> bool: s = self.size return abs(s - self._mod - 1) < 2*math.sqrt(self._mod) def inv_mod(self, x): """ Compute an inverse for x modulo p, assuming that x is not divisible by p. """ if x % self._mod == 0: raise ZeroDivisionError("Impossible inverse") # three-args pow - ( x^p-2 mod p ) # if mod is prime - result is always an inverse (because x^(p-1) = 1 mod p) return pow(x, self._mod-2, self._mod) def ec_inv(self, p: ECMPoint, check=True) -> ECMPoint: """ Inverse of the point P on the elliptic curve y^2 = x^3 + ax + b. """ if check and not self.valid(p): raise ValueError("Point '{}' is invalid".format(p)) if p == ECMPoint.O: return p return ECMPoint(p.x, (-p.y) % self._mod, self) def ec_add(self, p: ECMPoint, q: ECMPoint, check=True): """ Sum of the points P and Q on the elliptic curve y^2 = x^3 + ax + b. """ if check and not self.valid(p): raise ValueError("Point '{}' is invalid".format(p)) # Deal with the special cases where either P, Q, or P + Q is # the origin. if p == ECMPoint.O: result = q elif q == ECMPoint.O: result = p elif q == self.ec_inv(p, check=False): result = ECMPoint.O else: # Cases not involving the origin. if p == q: dydx = (3 * p.x ** 2 + self._a) * self.inv_mod(2 * p.y) else: dydx = (q.y - p.y) * self.inv_mod(q.x - p.x) x = int((dydx ** 2 - p.x - q.x) % self._mod) y = int((dydx * (p.x - x) - p.y) % self._mod) result = ECMPoint(x, y, self) # The above computations *should* have given us another point # on the curve. assert self.valid(result) return result def __repr__(self): return "EllipticCurveModulo({}, {}, {}) =" \ " 'y^2 = x^3 + {}x + {} mod {}'".format(*((self._a, self._b, self._mod)*2))