text
stringlengths
37
1.41M
def demo01(): print("hello python") print("我是汉字") f = open('./demo01.txt', 'rb') for line in f: print(line.decode('utf-8')) def fibonacci(): a, b = 0, 1 while b < 1000: print(b, end=',') a, b = b, a+b if __name__ == "__main__": demo01() fibonacci()
# 9-3 Users: Make a class called User") class User: def __init__(self, first_name, last_name, occupation, address, phone): self.first_name = first_name self.last_name = last_name self.occupation = occupation self.address = address self.phone = phone def describe_user(self): """print summary of user info""" print(self.first_name.title()) print(self.last_name.title()) print(self.occupation) print(self.address) print(self.phone) def greet_user(self): """Print personalized greeting to a user""" print(f"Hello {self.first_name.title()}, nice to see you!") # create several instances, and use both methods for each: person1 = User("tom", "jefferson", "programmer", "NYC", "212-0000") person2 = User("george", "jefferson", "programmer", "NYC", "212-0000") person3 = User("jessica", "thomson", "programmer", "NYC", "212-0000") person1.describe_user() person2.describe_user() person3.describe_user() person1.greet_user() person2.greet_user() person3.greet_user() # exe 9.8 print("+++++++++++++++++++9.8 ++++++++++") #Write a separate Privileges class. The class should have one #attribute, privileges, that stores a list of strings as described in #Exercise 9-7.Move the show_privileges() method to this class. Make a #Privileges instance as an attribute in the Admin class. Create a new #instance of Admin and use your method to show its privileges.""" class Userlog: def __init__(self, first_name, last_name, country, age): self.first_name = first_name self.last_name = last_name self.country = country self.age = age def describe_user(self): print(f"Meet our guest {self.first_name.title()} {self.last_name.title()}!" f"\n{self.first_name.title()} is {self.age} and lives in {self.country}") def greet_user(self): print(f"Welcome {self.first_name + ' ' + self.last_name}") class Privileges: def __init__(self, privileges: str): self.privileges = privileges def show_privileges(self): print(f"The user has following privileges: {self.privileges}") admin_pri = Privileges("can add info, ask questions") class Admin(Userlog): def __init__(self, first_name, last_name, country, age): super().__init__(first_name, last_name, country, age) self.privileges = admin_pri user100 = Admin("Jack", "Thompson", "USA", 23) print(user100.describe_user()) user100.greet_user()
# 03/11/2021 cars = ['bugatti', 'ferrari', 'tesla', 'lexus'] # making numerical list # SYNTEX: range ([start], stop, [step]) for num in range(4): print(num) nums = range(4) nums2 = list(range(4)) print(nums) print(nums2) for num in nums2: print(f"number: {num}") print() print('range with start and stop') for num in range(1, 4): print(f"number: {num}") print() print("range with start stop and step") # start stop step=interval for num in range(2, 15, 2): print(num) print() print('print even numbers from 1 to 16') evens = [] for num in range(0, 17, 2): print(num) evens.append(num) # to add values in list print(evens) # printing list as many times as we have range, only with + another # print() print(evens) print() print("Exercise2: print the squares of numbers from 10 to 20.") squares = [] for num in range(10, 21): squares.append(num ** 2) print(squares) print(f"min(squres): {min(squares)}") print(f"max(squres): {max(squares)}") print(f"sum(squres): {sum(squares)}") print() print("Exercise3 using index") len_cars = len(cars) for car in cars: print(car) print(f"index of the {car} is {cars.index(car)}") print() print("looping using ind") for ind in range(len_cars): # or using len function range(len(cars)) print(ind) print(f"index of the {cars[ind]} is {ind}") print("_______________________________________________") # list comprehension (only for appending) squares = [] for num in range(10, 21): squares.append(num ** 2) # append(expresion) + for loop squares = [num ** 2 for num in range(10, 21)] print() print("Execirs") nums = [] for num in range(1, 1000001): nums.append(num) print(f"smallest number: {min(nums)}") print(f"biggest number: {max(nums)}") print(f"sum number: {sum(nums)}")
# ind1 ind2 favorite_places = {'Alex': 'Spain', 'Jen': ['Arizona', 'Florida'], 'Bob': 'Thailand', 'Anna': 'India'} for name, details in favorite_places.items(): if name == 'Jen': print(f"{name}'s favorite places are" f"\n {favorite_places['Jen'][0]} and {favorite_places['Jen'][1]}") else: print(f"{name}'s favorite place is {details} ")
print("++++++++++++++++++++++++++++7.1++++++++++++++++") ''' Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.''' number = input("What kind of rental car they would like?: ") print(f"Let me see if i can find you a {number.title()}") print("++++++++++++++++++++++++++++7.2++++++++++++++++") '''Write a program that asks the user how many people are in their dinner group. If the answer is more than eight, print a message saying they’ll have to wait for a table. Otherwise, report that their table is ready''' table = int(input("How many people are in your dinner group?: ")) if table > 8: print(f"You will have to wait for a table") else: print(f"Your table is ready") print("++++++++++++++++++++++++++++7.3 ++++++++++++++++") '''Ask the user for a number, and then report whether the number is a multiple of 10 or not.''' number = int(input("Please enter number: ")) if number % 10 == 0: print(f"number is a multiple of 10") else: print(f"number is not a multiple of 10") print("++++++++++++++++++++++++++++7.4++++++++++++++++") ''' Write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you’ll add that topping to their pizza.''' topping = None while topping != 'quit' or topping != 'q': topping = input("Enter your topping: ") if topping == 'quit' or topping == 'q': break else: print(f"You’ll add {topping} topping to the pizza") print("++++++++++++++++++++++++++++7.5++++++++++++++++") ''' A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket''' while True: # incorrect whe i type 'q' it gives error age = int(input('Enter your age: ')) if age == 'quit': break elif age < 3: print(f"The ticket is free for you") elif 3 <= age < 12: print(f"The ticket is $10 for you") else: print(f"The ticket is $15 for you") print("++++++++++++++++++++++++++++7.6++++++++++++++++") '''Write different versions of either Exercise 7-4 or Exercise 7-5 that do each of the following at least once: • Use a conditional test in the while statement to stop the loop. • Use an active variable to control how long the loop runs. • Use a break statement to exit the loop when the user enters a 'quit' value''' topping = None while topping != 'quit' or topping != 'q': topping = input("Enter your topping: ") if topping == 'quit' or topping == 'q': break else: print(f"You’ll add {topping} topping to the pizza") print("++++++++++++++++++++++++++++7.1++++++++++++++++")
from turtle import Turtle, Screen import random # Screen setup screen = Screen() screen.setup(width=500, height=400) # Make bet user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race?") # Create turtles colors = ["red", "blue", "pink", "orange"] coordinates_y = [0, 30, 60, 90] turtles_list = [] is_race_on = False for turtle_index in range(0, 4): turtle = Turtle(shape="turtle") turtle.color(colors[turtle_index]) turtle.penup() turtle.goto(-230, coordinates_y[turtle_index]) turtles_list.append(turtle) if user_bet: is_race_on = True while is_race_on: for turtle_ in turtles_list: if turtle_.xcor() > 230: winning_color = turtle.pencolor() is_race_on = False if winning_color == user_bet: print(f"You've won, {winning_color} arrived first!") else: print(f"You've lost, {winning_color} arrived first!") random_distance = random.randint(0, 10) turtle_.forward(random_distance) screen.exitonclick()
""" -------------------------------------------------------------------------- PROJECT EULER - PROBLEM 96 Copyright (c) Eduardo Ocampo, All Rights Reserved https://www.github.com/thatguyeddieo -------------------------------------------------------------------------- """ import copy from itertools import product def solve_cells(grid,grid_num): """ Parameters ---------- grid: dict Dictionary data structure containing Suduko grids See read_file() in Su_Doku.py for more information grid_num: str Grid number from dictionary grid. Used as key value when analyzing specific unsolved cells, or grids. Example: grid_num = 'Grid 06' Returns ------- None The passed Suduko grid will contain the updated cell values after processed through this function Notes ----- """ nums = {str(i) for i in range(1,10)} for row,col in product(range(9),repeat=2): # Check if solution exists at (row,col) if len(grid[grid_num][row][col]) == 1 and int(grid[grid_num][row][col]) != 0: continue # get row, col, and box set row_set = set(r for r in grid[grid_num][row] if len(r)==1) col_set = set(grid[grid_num][i][col] for i in range(len(grid[grid_num])) if len(grid[grid_num][i][col])==1) x = lambda a: a // 3 * 3 box_set = set( b for i in range(x(row),x(row)+3) for b in grid[grid_num][i][x(col):x(col)+3] if len(b)==1) used_vals = row_set | col_set | box_set if '0' in used_vals: used_vals.remove('0') avail_vals = nums - used_vals # Assign possible solutions to cell (row,col) grid[grid_num][row][col] = ''.join(avail_vals) return None def reduce_cells(grid,grid_num): """ Parameters ---------- grid: dict Dictionary data structure containing Suduko grids See read_file() in Su_Doku.py for more information grid_num: str Grid number from dictionary grid. Used as key value when analyzing cells, or grids. Example: grid_num = 'Grid 06' Returns ------- None The passed Suduko grid will contain the updated cell values as processed through this function Notes ----- """ progress = [0,1] # nums = {str(i) for i in range(1,10)} # Copy grid to remove any errors when editing cells from original grid copied_grid = copy.deepcopy(grid) while((progress[-2]-progress[-1])/2 != 0): solve_cells(copied_grid,grid_num) # for row,col in product(range(9),repeat=2): # # Check if solution exists at (row,col) # if len(copied_grid[grid_num][row][col]) == 1 and int(copied_grid[grid_num][row][col]) != 0: # continue # # get row, col, and box set # row_set = set(r for r in copied_grid[grid_num][row] if len(r)==1) # col_set = set(copied_grid[grid_num][i][col] for i in range(len(copied_grid[grid_num])) # if len(copied_grid[grid_num][i][col])==1) # x = lambda a: a // 3 * 3 # box_set = set( b for i in range(x(row),x(row)+3) # for b in copied_grid[grid_num][i][x(col):x(col)+3] if len(b)==1) # used_vals = row_set | col_set | box_set # if '0' in used_vals: # used_vals.remove('0') # avail_vals = nums - used_vals # # print("avail_vals: ",avail_vals) # # if len(avail_vals) == 0: # # print("Wowowoowowowow") # # continue # copied_grid[grid_num][row][col] = ''.join(avail_vals) progress.append(check_if_solved(copied_grid,grid_num)) return None def hidden_singles(grid,grid_num): """ Parameters ---------- grid: dict Dictionary data structure containing Suduko grids See read_file() in Su_Doku.py for more information grid_num: str Grid number from dictionary grid. Used as key value when analyzing cells, or grids. Example: grid_num = 'Grid 06' Returns ------- None The passed Suduko grid will contain the updated cell values as processed through this function Notes ----- """ for row,col in product(range(9),repeat=2): # only consider cells with more than one possible solution if len(grid[grid_num][row][col]) > 1: original_list = grid[grid_num][row][col] grid[grid_num][row][col] = '0' # get row, col, and box set row_set = set(c for r in grid[grid_num][row] for c in r) col_set = set(c for i in range(len(grid[grid_num])) for c in grid[grid_num][i][col] ) x = lambda a: a // 3 * 3 box_set = set( c for i in range(x(row),x(row)+3) for b in grid[grid_num][i][x(col):x(col)+3] for c in b) if len(set(original_list)-row_set) == 1: grid[grid_num][row][col] = ''.join(set(original_list)-row_set) continue if len(set(original_list)-col_set) == 1: grid[grid_num][row][col] = ''.join(set(original_list)-col_set) continue if len(set(original_list)-box_set) == 1: grid[grid_num][row][col] = ''.join(set(original_list)-box_set) continue grid[grid_num][row][col] = original_list return None def naked_pairs(grid,grid_num): """ Parameters ---------- grid: dict Dictionary data structure containing Suduko grids See read_file() in Su_Doku.py for more information grid_num: str Grid number from dictionary grid. Used as key value when analyzing cells, or grids. Example: grid_num = 'Grid 06' Returns ------- None The passed Suduko grid will contain the updated cell values as processed through this function Notes ----- """ for row,col in product(range(9),repeat=2): # only consider cells with more than one possible solution if len(grid[grid_num][row][col]) > 1: # get row, col, and box list row_list = list(r for r in grid[grid_num][row] if len(r)>1) col_list = list(grid[grid_num][i][col] for i in range(len(grid[grid_num])) if len(grid[grid_num][i][col] )>1) # x = lambda a: a // 3 * 3 # box_set = list( b for i in range(x(row),x(row)+3) # for b in grid[grid_num][i][x(col):x(col)+3] if len(b)>1) naked_col_val = [x for x in col_list if col_list.count(x) > 1 and len(x) == 2] if naked_col_val and len(naked_col_val) == len(naked_col_val[0]): for r in range(0,9): if len(grid[grid_num][r][col]) > 1 and grid[grid_num][r][col] != naked_col_val[0]: for pair in naked_col_val[0]: grid[grid_num][r][col] = grid[grid_num][r][col].replace(pair,"") naked_row_val = [x for x in row_list if row_list .count(x) > 1 and len(x) == 2] if naked_row_val and len(naked_row_val) == len(naked_row_val[0]): for c in range(0,9): if len(grid[grid_num][row][c]) > 1 and grid[grid_num][row][c] != naked_row_val[0]: # print(grid[grid_num][row][w]) for pair in naked_row_val[0]: grid[grid_num][row][c] = grid[grid_num][row][c].replace(pair,"") return None def check_if_solved(grid,grid_sel): """ Parameters ---------- grid: dict Dictionary data structure containing Suduko grids See read_file() in Su_Doku.py for more information grid_sel: str Grid number from dictionary grid. Used as key value when analyzing cells, or grids. Example: grid_num = 'Grid 06' Returns ------- Number of cells which contain a single solution """ copied_grid = copy.deepcopy(grid) cell_check = [True for row,col in product(range(9),repeat=2) if len(copied_grid[grid_sel][row][col]) == 1 and int(copied_grid[grid_sel][row][col]) != 0] return sum(cell_check)
inp = input("Введите фамилию, имя и отчество").split() print("ФИО:"+inp[2], inp[0][0]+"."+inp[1][0]+".")
# ===================================== # --*-- coding: utf-8 --*-- # @Author : TRHX # @Blog : www.itrhx.com # @CSDN : itrhx.blog.csdn.net # @FileName: 【11】Pawn Brotherhood.py # ===================================== def safe_pawns(pawns: set) -> int: num = 0 for i in pawns: left_pawns = chr(ord(list(i)[0])-1) + chr(ord(list(i)[1])-1) right_pawns = chr(ord(list(i)[0])+1) + chr(ord(list(i)[1])-1) if left_pawns in pawns or right_pawns in pawns: num += 1 return num if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6 assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1 print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
# ============================================ # --*-- coding: utf-8 --*-- # @Author : TRHX # @Blog : www.itrhx.com # @CSDN : itrhx.blog.csdn.net # @FileName: 【15】Date and Time Converter.py # ============================================ def date_time(time: str) -> str: month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] time = time.replace('.', ' ').replace(':', ' ').split() time[0] = str(int(time[0])) time[1] = month[int(time[1])-1] time[2] = time[2] + ' year' if time[3] == '01': time[3] = '1 hour' else: time[3] = str(int(time[3])) + ' hours' if time[4] == '01': time[4] = '1 minute' else: time[4] = str(int(time[4])) + ' minutes' time = ' '.join(time) return time if __name__ == '__main__': print("Example:") print(date_time('01.01.2000 00:00')) # These "asserts" using only for self-checking and not necessary for auto-testing assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium" assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory" assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born" print("Coding complete? Click 'Check' to earn cool rewards!")
def alphabet_position2(text): text = text.lower() alph = [] text_pos = "" for x in range(97, 123): alph.append(chr(x)) for char in text: if char.isalpha(): text_pos += str(alph.index(char)+1) + " " return text_pos def alphabet_position(text): x = ' '.join(str(ord(ch.lower()) - 96) for ch in text if ch.isalpha()) return x def decrypt(encrypted_text, n): pass def encrypt(text, n): if n <= 0: return text if n == 1: return text[1::2] + text[::2] if n > 1: c = text[1::2] + text[::2] for i in range(n-1): c = c[1::2] + c[::2] print(c) encrypt("This is a test!", 4)
def get_middle(s): i = len(s) // 2 if len(s) % 2 == 0: return s[i-1]+s[i] return s[i] def get_middle(s): return s[len(s)//2 - 1:len(s)//2 + 1] if len(s) % 2 == 0 else s[len(s) // 2] # assert get_middle("test") == "es" # assert get_middle("testing") == "t" # assert get_middle("A") == "A" def high_and_low(numbers): nums_str = numbers.split() nums = [int(n) for n in nums_str] mx = max(nums) mn = min(nums) return '{} {}'.format(mx, mn) def high_and_low(numbers): nums = [int(n) for n in numbers.split()] return '{} {}'.format(max(nums), min(nums)) def high_and_low(numbers): nums = [int(n) for n in numbers.split()] return '{} {}'.format(sorted(nums)[-1], sorted(nums)[0]) # assert high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6") == "542 -214" # # high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6") #"542 -214" def square_digits(num): res = '' for ch in str(num): n = int(ch) res += str(n ** 2) return int(res) def square_digits(num): res = '' for ch in str(num): res += str(int(ch) ** 2) return int(res) assert square_digits(9119) == 811181 # my own thing for testing purpose def reverse_num(number): digits = [] i = 0 while number > 0: digits.append(number % 10) number //= 10 print(digits)
# Hash Generator def generate_hashtag(s): s = s.strip() result = '' if s != '' and len(s) < 140: words = s.strip().split(' ') for word in words: if word != '': word = word.lower() word = word[0].upper() + word[1:] result += word return '#' + result return False def generate_hashtag(s): print( generate_hashtag(''), # -> False generate_hashtag('Codewars '), #-> '#Codewars' generate_hashtag('Codewars Is Nice'), #-> '#Codewars' generate_hashtag('c i n'), #-> '#Codewars' generate_hashtag('CodeWars is nice'), #-> '#Codewars' )
from tkinter import * from tkinter import * from PIL import Image, ImageTk import random window = Tk() window.title("ball") text = Label(window, text = "shake the ball!", font= ("Helvetica", 25)) text.grid(column = 0, row = 0) window.geometry('220x300') # the switching function goes here ball = PhotoImage(file = "blankball.png") ball = ball.zoom(20) ball = ball.subsample(90) #load some images in this # = ball.resize(width = 210, height = 400) # tkimage = ImageTk.PhotoImage(ball) # Tk.Label(window, image=tkimage).pack() label = Label(window, image = ball ) def clicked(): x = random.randrange(1,21) print(x) choices = { 1 : 'nah.gif', 2 : 'certain.gif', 3: 'notnow.gif',4: 'concentrate.gif',5: 'decided.gif', 6: 'doubt.gif', 7: 'forsure.gif', 8: 'good.gif', 9: 'hazy.gif', 10 : 'later.gif', 11: "likely.gif", 12: "nah.gif", 13: 'nat.gif', 14: 'nay.gif', 15: 'ncount.gif', 16: 'nodoubt.gif', 17: 'not now.gif', 18: 'notgood.gif', 19: 'rely.gif', 20: 'toyes.gif'} result = choices.get(x,'default') ball.configure(file= result) btn = Button(window, text="Shake!", command = clicked) btn.grid(column=0, row=1) label.grid(column=0,row=2) window.mainloop()
from random import randint #引入随机整数函数 arr=[] #初始化数组 for i in range(20): arr.append(randint(1,100)) #读入数组 print('排序前的列表为:{}'.format(arr)) arr.sort() #排序 print('排序后的列表为:{}'.format(arr))
# Pokemon class class Pokemon: def __init__(self, name, type, level = 5): self.name = name self.level = level self.health = level * 5 self.max_health = level * 5 self.type = type self.is_knocked_out = False def lose_health(self, health_lost): self.health -= health_lost if self.health <= 0: self.knock_out() else: print("{pokemon} has {health} HP!".format(pokemon=self.name,health=self.health)) def gain_health(self, health_gained): self.health += health_gained if (self.health > self.max_health): self.health = self.max_health print("{pokemon} gained {healthgain} HP".format(pokemon=self.name, healthgain= health_gained )) def attack(self, enemy): if (self.is_knocked_out): print("{name} is knocked out and can't attack!".format(name=self.name)) elif (enemy.is_knocked_out): print("You can't attack a knocked out pokemon!") else: if ((self.type == "Grass") and (enemy.type == "Fire")) or ((self.type == "Fire") and (enemy.type == "Water")) or ((self.type == "Water") and (enemy.type == "Grass")): damage_dealt = enemy.level * 0.5 message = "It was not very effective!" elif ((self.type == "Grass") and (enemy.type == "Water")) or ((self.type == "Fire") and (enemy.type == "Grass")) or ((self.type == "Water") and (enemy.type == "Fire")): damage_dealt = enemy.level * 1.5 message = "It was super effective!" else: damage_dealt = enemy.level message = "Good hit!" print("{your_pokemon} attacked {enemy_pokemon} for {damage} damage!".format(your_pokemon=self.name, enemy_pokemon=enemy.name, damage=damage_dealt)) print(message) enemy.lose_health(damage_dealt) def knock_out(self): self.health = 0 self.is_knocked_out = True print("{pokemon} has been knocked out!".format(pokemon=self.name)) #Trainer Class class Trainer: def __init__(self, name, pokemon, potions): self.name = name self.pokemon = pokemon self.potions = potions self.active_pokemon = 0 def __repr__(self): print("\n{self}'s Pokemon: ".format(self=self.name)) for pokemon in self.pokemon: print("{name}, {type}-Type, Level:{level}, HP: {HP}".format(name=pokemon.name, type=pokemon.type, level = pokemon.level, HP=pokemon.health)) return "Current Pokemon: {pokemon}".format(pokemon=self.pokemon[self.active_pokemon].name) def use_potion(self): print("\n") if (self.potions == 0): print ("{name} have no potions!".format(name = self.name)) else: self.potions -= 1 print("{name} used a potion on {pokemon}".format(name= self.name, pokemon=self.pokemon[self.active_pokemon].name)) self.pokemon[self.active_pokemon].gain_health(30) print("{pokemon} has {HP} HP left".format(pokemon=self.pokemon[self.active_pokemon].name, HP=self.pokemon[self.active_pokemon].health)) def attack_trainer(self, enemy): print("\n") if (self.pokemon[self.active_pokemon].is_knocked_out): print("{name}'s {pokemon} is knocked out! Swap to another pokemon".format(name = self.name, pokemon=self.pokemon[self.active_pokemon].name)) else: print("{your_name}'s {your_pokemon} attacked {enemy_name}'s {enemy_pokemon}!".format(your_name = self.name, your_pokemon=self.pokemon[self.active_pokemon].name, enemy_name=enemy.name, enemy_pokemon=enemy.pokemon[enemy.active_pokemon].name)) self.pokemon[self.active_pokemon].attack(enemy.pokemon[enemy.active_pokemon]) def swap_pokemon(self, desired_pokemon): print("\n") if (self.pokemon[desired_pokemon].is_knocked_out): print("You can't swap to a knocked out pokemon!") else: print("{name}'s swapping Pokemon!\nCome back {pokemon}!".format(name=self.name, pokemon=self.pokemon[self.active_pokemon].name)) self.active_pokemon = desired_pokemon print ("{pokemon} I choose you!".format(pokemon = self.pokemon[self.active_pokemon].name)) Charmander = Pokemon("Charmander","Fire",10) Bulbasaur = Pokemon("Bulbasaur","Grass",11) Squirtle = Pokemon("Squirtle","Water",7) Butterfree = Pokemon("Butterfree","Grass",9) Caterpie = Pokemon("Butterfree","Grass",5) Polywhirl = Pokemon("Polywhirl","Water",7) Magmar = Pokemon("Magmar","Fire",3) Venasaur = Pokemon("Venasaur","Grass",19) Red = Trainer("Red",[Venasaur,Magmar,Caterpie,Squirtle,Charmander,Polywhirl],4) Blue = Trainer("Blue",[Charmander,Bulbasaur,Butterfree,Squirtle,Magmar,Polywhirl],4) print(Red) print(Blue) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.swap_pokemon(1) Blue.use_potion() Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.use_potion Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.swap_pokemon(5) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.use_potion() Blue.swap_pokemon(2) Red.attack_trainer(Blue) Blue.attack_trainer(Red) Red.attack_trainer(Blue) Blue.attack_trainer(Red)
#!/usr/bin/python2.7 #-*- coding: utf-8 -*- message = "hello python" print(message) print("hello everyone.") #将首字母大写 print(message.title()) #将字符串全部大写 favorite_language=' python ' favorite_language.rstrip() print(favorite_language) print(favorite_language.strip()) print(favorite_language.lstrip()+favorite_language.strip()+ '\n'+favorite_language) #对数列的增删改查 alist=['apple','pear','egg','bear'] print alist print(alist[0],alist[1],alist[2],alist[3]) print("so sorry for "+alist[2]+" that can't come here!") del alist[2] alist.insert(2,'star') print alist alist[2]='car' print alist alist.append('moon') print alist alist.pop() print alist alist.pop() alist.pop() alist.pop() print alist del alist[0] print alist #对数列的排序 blist=['pear','egg','bear','orange','moon'] sorted(blist) print blist print(sorted(blist)) print(sorted(blist,reverse=True)) print blist print(len(blist))
def matrix_transpose(A): result = [[0 for i in range(len(A))] for j in range(len(A[0]))] for i in range(len(A)): for j in range(len(A[0])): result[j][i] = A[i][j] return result print(matrix_transpose(A))
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None #Insert a node into BST def insert(self, key): if self.root == None: self.root = Node(key) else: self.__insert(key, self.root) def __insert(self, key, curr): if key < curr.value: if curr.left: self.__insert(key, curr.left) else: curr.left = Node(key) elif key > curr.value: if curr.right: self.__insert(key, curr.right) else: curr.right = Node(key) elif key == curr.value: pass #Check if key exists in BST def exist(self, key): if self.root.value == key: return True else: return self.__exist(key, self.root) def __exist(self, key, curr): if key == curr.value: return True elif key < curr.value: if curr.left: return self.__exist(key, curr.left) else: return False elif key > curr.value: if curr.right: return self.__exist(key, curr.right) else: return False #Node with min value def minimum(self, key): return self.__minimum(key, self.root) def __minimum(self, key, curr): if key == curr.value: while curr.left != None: curr = curr.left return curr.value elif key < curr.value: if curr.left: return self.__minimum(key, curr.left) elif key > curr.value: if curr.right: return self.__minimum(key, curr.right) #Node with max value def maximum(self, key): return self.__maximum(key, self.root) def __maximum(self, key, curr): if key == curr.value: while curr.right != None: curr = curr.right return curr.value elif key < curr.value: if curr.left: return self.__maximum(key, curr.left) elif key > curr.value: if curr.right: return self.__maximum(key, curr.right) # Inorder Traversal # Left Root Right def inorder_traversal(self): self.order = [] if self.root: self.__inorder_traversal(self.root) return self.order def __inorder_traversal(self, curr): if curr: self.__inorder_traversal(curr.left) self.order.append((curr.value)) self.__inorder_traversal(curr.right) # Pre-order Traversal # Root Left Right def preorder_traversal(self): self.order = [] if self.root: self.__preorder_traversal(self.root) return self.order def __preorder_traversal(self, curr): if curr: self.order.append((curr.value)) self.__preorder_traversal(curr.left) self.__preorder_traversal(curr.right) # Post-order Traversal # Left Right Root def postorder_traversal(self): self.order = [] if self.root: self.__postorder_traversal(self.root) return self.order def __postorder_traversal(self, curr): if curr: self.__postorder_traversal(curr.left) self.__postorder_traversal(curr.right) self.order.append((curr.value)) #Get tree height def height(self): if self.root == None: return 0 else: return self.__height(self.root) def __height(self, curr_node, curr_height=0): if curr_node == None: return curr_height left_height = self.__height(curr_node.left, curr_height + 1) right_height = self.__height(curr_node.right, curr_height + 1) print(left_height, right_height) return max(left_height, right_height) #Question 1 bst = BST() # #----------------------Question 1a-----------------------# # bst.insert(68) bst.insert(88) bst.insert(61) bst.insert(89) bst.insert(94) bst.insert(50) bst.insert(4) bst.insert(76) bst.insert(66) bst.insert(82) # # print('----------------------Question 1b-----------------------') # key = 50 print(bst.exist(50)) print('----------------------Question 1c-----------------------') #key = 49 print(bst.exist(49)) print('----------------------Question 1d-----------------------') # starting node = 68 print(bst.minimum(68)) print('----------------------Question 1e-----------------------') # starting node = 88 print(bst.minimum(88)) print('----------------------Question 1f-----------------------') # starting node = 68 print(bst.maximum(68)) print('----------------------Question 1g-----------------------') # starting node = 61 print(bst.maximum(61)) print('----------------------Question 1h-----------------------') # In order Traversal print(bst.inorder_traversal()) print('----------------------Question 1i-----------------------') # Pre order traversal print(bst.preorder_traversal()) print('----------------------Question 1j-----------------------') # Post order traversal print(bst.postorder_traversal()) #----------------------Question 2-----------------------# # keys = ['begin', 'do', 'else', 'end', 'if', 'then', 'while'] mid = len(keys)//2 #Initialising the keywords tree keywords = BST() #Adding the middle value to the tree keywords.insert(keys[mid]) #Adding the rest of the keywords into the tree for k in keys: keywords.insert(k)
def matrix_multiplication(A, B): Arow, Acol = len(A), len(A[0]) Brow, Bcol = len(B), len(B[0]) #print(Arow, Acol, Brow, Bcol) def multiply(x, y): result = [[0 for i in range(y)] for j in range(x)] #print(result) for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): pass result[i][j] += A[i][k] * B[k][j] return result if Arow == Bcol: return multiply(Arow, Bcol) elif Acol == Brow: return multiply(Arow, Bcol) else: return 'The number of columns in Matrix A does not equal the number of rows in Matrix B required for Matrix Multiplication.' print(matrix_multiplication(A,B))
def mergeSort(arr): if len(arr) < 2: return arr else: a = arr[:len(arr)//2] b = arr[len(arr)//2:] a = mergeSort(a) b = mergeSort(b) c = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: c.append(a[i]) i = i + 1 else: c.append(b[j]) j = j + 1 c += a[i:] c += b[j:] return c testList = [1,3,5,7,2,6,25,18,13] print(mergeSort(testList)) # def merge(left, right): # result = [] # i,j = 0,0 # while i < len(left) and j < len(right): # if left[i] < right[j]: # result.append(left[i]) # i += 1 # else: # result.append(right[j]) # j += 1 # while i < len(left): # result.append(left[i]) # i += 1 # while j < len(right): # result.append(right[j]) # j += 1 # return result # def merge_sort(lst): # if len(lst) < 2: # return lst # else: # middle = len(lst)//2 # left = merge_sort(lst[:middle]) # right = merge_sort(lst[middle:]) # return merge(left, right) #print(merge_sort(testList)) # def mergeSort(lst, ascending=True): # if len(lst) < 2: # return lst # middle = len(lst)//2 # left = mergeSort(lst[:middle], ascending) # right = mergeSort(lst[middle:], ascending) # result = [] # i,j = 0,0 # while i < len(left) and j < len(right): # if (left[i] < right[j] and ascending) or (left[i] > right[j] and not(ascending)): # result.append(left[i]) # i += 1 # else: # result.append(right[j]) # j += 1 # while i < len(left): # result.append(left[i]) # i += 1 # while j < len(right): # result.append(right[j]) # j += 1 # return result # def mergeSort(lst): # if len(lst) < 2: # return lst # middle = len(lst)//2 # left = mergeSort(lst[:middle]) # right = mergeSort(lst[middle:]) # result = [] # i,j = 0,0 # while i < len(left) and j < len(right): # if left[i] < right[j]: # result.append(left[i]) # i += 1 # else: # result.append(right[j]) # j += 1 # while i < len(left): # result.append(left[i]) # i += 1 # while j < len(right): # result.append(right[j]) # j += 1 # return result arr2 = [2, 4, 1, 3, 5] arr = [1, 20, 6, 4, 5] #print(mergeSort(arr2))
import ast lst = input() lst = ast.literal_eval(lst) def selection_sort(lst): for i in range(len(lst)): minimum = i for j in range(i, len(lst)): if lst[j] < lst[minimum]: minimum = j lst[i], lst[minimum] = lst[minimum], lst[i] print(lst) selection_sort(lst)
import ast lst = input() lst = ast.literal_eval(lst) column = int(input()) def sort_matrix_by_columnNumber(lst, column): for i in range(len(lst)): minimum = i for j in range(i, len(lst)): if lst[j][column] < lst[minimum][column]: minimum = j lst[i], lst[minimum] = lst[minimum], lst[i] return lst print(sort_matrix_by_columnNumber(lst, column))
import argparse import sys class Node(object): def __init__(self,data=None,next=None): self.data = data self.next = next def ParseArgs(): #desc = 'usage:' parser = argparse.ArgumentParser() parser.add_argument('-i',action='store',dest='list',help='The input list') parser.add_argument('-k',action='store',dest='knode',help='the number of nodes to reverse') args = parser.parse_args() return args def ReverseList(head): if head == None: return None tail = head p = head.next while p != None: r = p.next #move the current node to the head of the list p.next = head head = p p = r #Finish move all nodes tail.next = None ####################for test #print("in revlist") #p = head #while p != None: # print(p.data) # p = p.next #print ('end') ################################## return head def ReverseListPerKNodes(head, K): if head == None: return None if K == 0 or K == 1: return head #get the sublist with lenth K start = head p = head lasttail = None numRuns = 0 while start is not None: count = 1 p = start while p.next != None: count += 1 p = p.next if count == K: #get a sublist with K node: [start, p] break #the remainder nodes less than K,leave the list as it is if count < K: if lasttail is not None: lasttail.next = start break #P is the tail of the current K list,record the start node for the next K nodes nextStart = p.next #start to reverse the current K nodes p.next = None rev_start = ReverseList(start) numRuns += 1 if numRuns == 1: #change the head pointer after reversing the first K nodes head = rev_start #linked the reversed K nodes after the last sub list if lasttail is not None: lasttail.next = rev_start lasttail = start #Adjust to the current tail node start = nextStart return head if __name__=='__main__': args = ParseArgs() if args != None: print('input list= %s, K= %s' % (args.list, args.knode)) else: exit(0) # pass liststr = args.list #liststr= '12345' k = int(args.knode) #k = 2 head = tail = None for nodeindex in range(len(liststr)): node = Node(liststr[nodeindex]) if head == None: #head node head = node tail = head else: #link the node to the tail tail.next = node tail = node #L = Node(1,Node(2,Node(3,Node(4,Node(5,Node(6, Node(7))))))) #h = ReverseList(L) tmp = '->' in_list = [] print ('----------------------') p = head while(p!= None): in_list.append(p.data) p = p.next print ('the input list is:' + tmp.join(in_list)) r = ReverseListPerKNodes(head,k) p = r print ('----------------------') out_list = [] while p != None: out_list.append(p.data) p = p.next print('the output list is:' + tmp.join(out_list))
''' A program that returns any two numbers from a list which adds up to a target. @params arr: a list @params target_value: an integer @returns: a boolean. True returns a tuple with result. ''' from itertools import permutations def find_sum(arr, target_value): '''Using permutations. Loops through the list only once''' result = [numbers for numbers in permutations(arr, 2) if sum(numbers) == target_value] return False if not result else (True, result) def find_sum2(arr, target_value): '''Using range. Loops through list twice. Returns unique value if True.''' result = [] for first_number in arr: for i in range(len(arr) - 1): if first_number + arr[i + 1] == target_value: result.append((first_number, arr[i + 1])) return False if not result else (True, result) def find_sum3(arr, target_value): '''Using enumerate. Loops through list twice.''' result = [] for first_number in arr: for _, last_number in enumerate(arr): if first_number + last_number == target_value: result.append((first_number, last_number)) if not result: return False return True, result print(find_sum([10, 15, 3, 7], 17))
#!/usr/bin/python import math class StatisticsAccumulator: """Accepts one value at a time and keeps track of the associated statistics""" def __init__(self): self.__welford_mean__ = 0.0 self.__welford_i_var__ = 0.0 self.i = 0 # Maintain the statistics for each estimate def update_statistics(self, estimate): self.i += 1 self.__update_i_var__(estimate) # The previous mean is used in this calculation, so calculate this first self.__update_mean__(estimate) # Account for the new value in the Welford mean def __update_mean__(self, estimate): self.__welford_mean__ += (1.0/self.i) * (estimate - self.__welford_mean__) # Account for the new value in the Welford iVar def __update_i_var__(self, estimate): self.__welford_i_var__ += ((self.i-1.0)/self.i) * (estimate - self.__welford_mean__)**2 # Functions to return the statistics def get_mean(self): return self.__welford_mean__ def get_variance(self): return self.__welford_i_var__ / float(self.i) def get_stdev(self): return math.sqrt(self.get_variance())
# -*- coding: utf-8 -*- """ Created on Thu Nov 10 14:05:16 2016 @author: LeviZ """ # implementation of card game - Memory import simplegui import random # helper function to initialize globals def new_game(): global state, turns, cards, exposed, click_1, right_guess state = 0 turns = 0 card_index = 0 right_guess = [] cards = [n for n in range(0,8)*2] exposed = [False for n in range(0, 8)*2] random.shuffle(cards) label.set_text("Turns = "+str(turns)) # define event handlers def mouseclick(pos): # add game state logic here global state, turns, exposed, card_index, click_1, click_2 card_index = pos[0]//50 if not exposed[pos[0]//50]: if state == 0: click_1 = card_index exposed[click_1] = True state = 1 turns += 1 elif state == 1: if not exposed[card_index]: click_2 = pos[0]//50 exposed[click_2] = True state = 2 else: if not exposed[card_index]: if cards[click_1] != cards [click_2]: exposed[click_1] = False exposed[click_2] = False turns += 1 state=1 click_1 = pos[0]//50 exposed[click_1] = True label.set_text("Turns = "+str(turns)) # cards are logically 50x100 pixels in size def draw(canvas): for n in range(len(cards)): card_pos = 50 * n if exposed[n]: canvas.draw_text(str(cards[n]), (card_pos+20, 100//2 ), 20, 'White') canvas.draw_polygon([(50*n, 0), (50*n, 100), (50*(n + 1), 100), (50*(n+1), 0)], 2, 'White') else: canvas.draw_polygon([(50*n, 0), (50*n, 100), (50*(n + 1), 100), (50*(n+1), 0)], 2, 'White', 'Green') if exposed.count(True) == 16: canvas.draw_text("Winner! Winner!", (300, 90), 40, "Red") # create frame and add a button and labels frame = simplegui.create_frame("Memory", 800, 100) frame.add_button("Reset", new_game) label = frame.add_label("Turns = 0") # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) # get things rolling new_game() frame.start() # Always remember to review the grading rubric
class Car: def __init__(self, speed=None, color='', name='', is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print(f'{self.color} машина марки {self.name} поехала') def stop(self): print(f'{self.color} машина марки {self.name} остановилась') def turn(self, direction): print(f'{self.color} машина марки {self.name} повернула {direction}') def show_speed(self): print(f'{self.color} машина марки {self.name}, скорость: {self.speed}') class TownCar(Car): def show_speed(self): print(f'{self.color} машина марки {self.name}, скорость: {self.speed}') if self.speed > 60: print(f'Превышение скорости') class SportCar(Car): pass class WorkCar(Car): def show_speed(self): print(f'{self.color} машина марки {self.name}, скорость: {self.speed}') if self.speed > 40: print(f'Превышение скорости') class PoliceCar(Car): pass car_1 = SportCar(speed=90, color='красная', name='Infinity') car_1.show_speed() car_1.turn('налево') car_2 = TownCar(speed=55, color='синяя', name='Nissan') car_2.go() car_2.show_speed() car_2.stop() car_3 = WorkCar(speed=45, color='желтая', name='Dodge') car_3.show_speed() car_3.turn('направо')
def f(x): return x * x * x + 3 * x - 5 def RegulaFalsi(a, b, ACCURACY): x1 = a - f(a) * (b - a) / (f(b) - f(a)) if abs(f(x1)) < ACCURACY: return x1 if f(x1) * f(a) < 0: x0 = a else: x0 = b while abs(x1 - x0) > ACCURACY: x1 = x1 - f(x1) * (x0 - x1) / (f(x0) - f(x1)) if abs(f(x1)) < ACCURACY: return x1 return (x1 + x0) / 2 print (RegulaFalsi(0, 5, 0.000001))
# -*- coding: utf-8 -*- # This script describes how truncated and fully compounded fiscal multiplier # scenarios can be consider to be equivalent. It is described in the accompanying # iPython Notebook and at # # http://misunderheard.org/monetary_economics/2017/04/10/modelling_the_fiscal_multiplier/ # # %% import matplotlib.pyplot as plt import numpy as np %matplotlib inline G = 100 # government spending theta = 0.2 # tax rate rounds = 5 # solve equation 1 for the 5th spending round sum_y = G*(1-(1-theta)**(rounds+1))/(1-(1-theta)) print(sum_y) # calculate the total tax paid after the 5th spending round T = theta*sum_y print(T) # solve equation 2 for the 6th spending round y = G*(1-theta)**(rounds) # gross income # subtract the tax paid y_d = (1-theta)*y # disposable income print(y_d) # derive the implied alpha value alpha = (1-(G/sum_y))/(1-theta) print(alpha) # calculate the total income with saving sum_y = G/(1-alpha*(1-theta)) print(sum_y) # calculate the implied savings and tax revenue s = (1-alpha)*(1-theta)*sum_y T = theta*sum_y print(s) print(T)
#РЕАЛИЗАЦИИ МАССИВОВ #В Python существует 2 реализации массивов: списки и кортежи #Списки --- list() my_list = [10, 20, 30, 40, 5, -1, 20] print(my_list[0], my_list[1]) print("Last element of my_list is: ", my_list[6]) print("Last element of my_list is: ", my_list[-1]) print(my_list[-3]) print(my_list[-0]) #Empty list() my_list_1 = [] print(type(my_list_1)) my_list_2 = list() #Dop elemts print("##############################") nums = [20,30,40,100,200,300,4,3,5,6, 20] nums.append(98) print(nums) nums.pop() print(nums) print(dir(nums)) print(nums.count(20)) print(nums.index(30)) print(nums.index(20)) nums.sort(reverse = True) print(nums) print("##################################") print(sum(nums)) print(len(nums)) average = sum(nums) / len(nums) print(average)
def my_function(a, b): result = a ** 2 + b ** 3 / (a * b) return result q = my_function(4,10) w = my_function(10,2000) e = my_function(1,1) print(q + w + e) # y(x,z) = 5*x + 3*z # y(2,1) = 5*2 + 3*1 = 13 # y(7,1) = 5*7 + 3*1 = 38
def add(a :int, b :int) -> int: return a + b def sub(a :int, b :int) -> int: return a - b def mult(a :int, b :int) -> int: return a * b def div(a:int, b:int) -> float: if ( b != 0): return a / b else: return 0 a = 10
def add(a :int, b :int) -> int: return a + b + 1 def sub(a :int, b :int) -> int: return a - b def mult(a :int, b :int) -> int: return a * b def div(a:int, b:int) -> float: if ( b != 0): return a / b else: return 0 a = 109 print("Hi from another module!") class User: def __init__(self): self.a = "a"
my_list = [1,2,3,4,5,6,7,8,9,10] my_tup = (1,2,3,4,5,6,7,8,9,10) print(type(my_list),my_list.__sizeof__(), my_list ) print(type(my_tup),my_tup.__sizeof__(), my_tup ) print(my_tup[0:-1:3])
#猜单词游戏,在实际应用中把输入的单词从文件读取或者在源码中修改直接写好。 #定义函数 def guessWord(word): print("play the game:") wrong=0 getWords=list(word) bind=["_"]*len(word) win= False gragh=["————————————————————", "| |", "| |", "| o", "| |", "| /|\ ", "| /|\ " ] while wrong<len(word)-1: charater=input() if charater in getWords: print("祝贺你答对了,加油哦") c_index=getWords.index(charater) bind[c_index]=charater getWords[c_index]='$' else: wrong+=1 if wrong<len(gragh)+1: for i in range(wrong): print(gragh[i]) #print(gragh[0:wrong+1]) if "_" not in bind: print("你赢了") win=True break if not win: print("你输了") #打印图像 import os wpath=os.path.join("D:\\","practiceForPython","word.txt") with open(wpath,'r') as f: myword=f.read().strip('\n') print("如果要修改单词,请到word.txt的修改单词") print(myword) guessWord(myword)
import pygame as pg pg.init() # Iniciar pygame pantalla = pg.display.set_mode((800, 600)) # Crear pantalla # Bucle principal game_over = False while not game_over: # = "Mientras game_over sea falso" ó "while True" , se mete en el bucle. Para salir, game_over a True: eventos = pg.event.get() # Procesar eventos. Lo que sale de la lista de event.get(), todo lo que pasa en la ventana de pygame, lo meto en "eventos" para evitar que se cuelgue el programa for evento in eventos: if evento.type == pg.QUIT: game_over = True # Si uno de los eventos de event.get() es de tipo cerrar "X", que se cierre pygame, poniendo game_over a True pantalla.fill((255, 0, 0)) # Color fondo pantalla pg.display.flip() # Hay que hacerlo siempre. Renderiza pantalla pg.quit() # Al salir del bucle "while not game_over", porque game_over es True, que pygame se pare
# INHERITANCE class Animal(): def __init__(self): print('ANIMAL CREATED') def whoAmI(self): print('ANIMAL') def eat(self): print('EATING') mya = Animal() mya.whoAmI() mya.eat() class Dog(Animal): def __init__(self): print('DOG CREATED') def bark(self): print('WOOF') def eat(self): print('dog is eating') mydog = Dog() mydog.whoAmI() mydog.eat() mydog.bark() # SPECIAL METHODS mylist = [1,2,3] print(mylist) class Book(): def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages b = Book('Python', 'jose', 200) print(b) # w/o the __str__ method defined, it just prints out the location in memory Book.__str__ = lambda x: 'hello' # one way, probably not pythonic. print(b) # probably prefer this: class Book(): def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): return f'Title: {self.title}, Author: {self.author}, Pages: {self.pages}' def __len__(self): return self.pages def __del__(self): print('a book is destroyed') b = Book('Python', 'jose', 200) print(b) print(len(b)) # returns an object because we don't have have __len__ method del b
# prompt: # A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well. # Given a series of digits as a string, determine if the number represented by the string is divisible by three. # You can expect all test case arguments to be strings representing values greater than 0. # Example: # "123" -> true # "8409" -> true # "100853" -> false # "33333333" -> true # "7" -> false # Try to avoid using the % (modulo) operator. from functools import reduce def divisible_by_three(st): # just to see if I could do it a different way # sum = reduce(lambda x, y: int(x) + int(y), list(st)) sum = 0 for num in st: sum += int(num) # deal with divisibility while sum > 2: sum -= 3 if sum == 0: return True return False print(divisible_by_three('123'))
from random import shuffle SUITE = 'H D S C'.split() RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() class Deck(): ''' This is the Deck class. This object will create a deck of cards to initiate play. You can then use this Deck List of cards to split in half and give to the players. It will use SUITE and RANKS to create the deck. It should also have a method for splitting/cutting the deck in half and Shuffling the deck. ''' def __init__(self): self.deck = [{'suite': suite, 'rank': rank} for suite in SUITE for rank in RANKS] def shuffle(self): shuffle(self.deck) def cut_and_deal(self): return self.deck[:26], self.deck[26:] class Hand(): ''' This is the Hand class. Each player has a Hand, and can add or remove cards from that hand. There should be an add and remove card method here. ''' def __init__(self, hand): self.hand = hand def add(self, cards): self.hand.extend(cards) def remove(self): return self.hand.pop(0) def __len__(self): return (len(self.hand)) def __str__(self): return self.hand.__str__() class Player(): ''' This is the PLayer class, which takes in a name and instanceo fo a Hand class object. The player can then play cards and check if they still have cards. ''' def __init__(self, name, hand): self.name = name self.hand = hand def play_card(self): return self.hand.remove() def card_count(self): return len(self.hand) def compare_cards(card1, card2): # compare values # how account for face cards index1 = RANKS.index(card1['rank']) index2 = RANKS.index(card2['rank']) if index1 == index2: return 'equal' elif index1 > index2: return 'one' else: return 'two' def check_for_winner(p1, p2): if p1.card_count() == 0: return 'p2' elif p2.card_count() == 0: return 'p1' else: return False def war(p1, p2): # check that each have enough cards(4), if not draw n-1 cards spoils_count = min(p1.card_count() - 1, p1.card_count() - 1, 3) spoils = [] for num in range(spoils_count): print(f'p1 has {p1.card_count()} cards') spoils.append(p1.play_card()) print(f'p2 has {p2.card_count()} cards') spoils.append(p2.play_card()) return spoils # The game def play_game(): print('Welcome to War. Because War doesn\'t actually require any decisions, \n the game will automatically play.') # create the deck deck = Deck() deck.shuffle() h1, h2 = deck.cut_and_deal() # create players p1 = Player('computer', Hand(h1)) p2 = Player('player', Hand(h2)) # play the game winner = False p1_card = p1.play_card() p2_card = p2.play_card() spoils = [p1_card, p2_card] rounds = 0 while not winner: rounds += 1 print(f'------------ ROUND {rounds} ------------------') comparison = compare_cards(p1_card, p2_card) if comparison == 'equal': spoils.extend(war(p1, p2)) # set the new comparison cards print(f'spoils has {len(spoils)} cards', f'\n\t{spoils}') print(f'p1 has {p1.card_count()} cards', f'\n\t{p1.hand}') print(f'p2 has {p2.card_count()} cards', f'\n\t{p2.hand}') # p1_card = p1.play_card() # p2_card = p2.play_card() # spoils.extend([p1_card, p2_card]) continue elif comparison == 'one': print(f'spoils has {len(spoils)} cards') print(f'p1 has {p1.card_count()} cards') print(f'p2 has {p2.card_count()} cards') p1.hand.add(spoils) else: print(f'spoils has {len(spoils)} cards') print(f'p1 has {p1.card_count()} cards') print(f'p2 has {p2.card_count()} cards') p2.hand.add(spoils) winner = check_for_winner(p1, p2) if not winner: p1_card = p1.play_card() p2_card = p2.play_card() spoils = [p1_card, p2_card] # print out the winner print(f'After {rounds}, ') print(f'{winner} has won!') print(f'{p1.name} had {p1.card_count()} cards') print(f'{p2.name} had {p2.card_count()} cards.') play_game() # play the game
""" Demo of the histogram (hist) function with a few features. In addition to the basic histogram, this demo shows a few optional features: * Setting the number of data bins * The ``normed`` flag, which normalizes bin heights so that the integral of the histogram is 1. The resulting histogram is a probability density. * Setting the face color of the bars * Setting the opacity (alpha value). """ import numpy as np import matplotlib.pyplot as plt def run_curve(fname): # load data f = open(fname,'r') s = f.readline(); s = s.split() for i in range(0,len(s)): s[i]=float(s[i]) # draw line x = np.linspace(0, len(s)-1, num=len(s)) plt.plot(x, s, '-', linewidth=1, color='black') # plot plt.xlabel('x axis') plt.ylabel('y axis') # Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) plt.show() if __name__ == '__main__': run_curve('vec.txt')
from typing import List n = 4 def small_square(tu, line_list): counter = 0 if [tu[0], tu[1]] in line_list: counter += 1 elif [tu[0], tu[0] + n] in line_list: counter += 1 elif [tu[1], tu[1] + n] in line_list: counter += 1 elif [tu[0] + n, tu[1] + n] in line_list: counter += 1 return counter def average_square(tu, line_list): counter = 0 if [tu[0], tu[1]] and [tu[0] + 1, tu[1] + 1] and [tu[0], tu[0] + n] and [tu[0] + n, tu[0] + n * 2] and [tu[0] + n * 2, tu[1] + n * 2] and [tu[0] + n * 2 + 1, tu[1] + n * 2 + 1] and [tu[1] + 1, tu[1] + n * 2 + 1] and [tu[1] + n +1, tu[1] + n * 2 + 1] in line_list: counter += 1 else: print([tu[0], tu[1]]) return counter def large_square(tu, line_list): pass def checkio(lines_list: List[List[int]]) -> int: sq = 0 for tu in lines_list: if small_square(tu, lines_list) == 4: sq += 1 print(small_square()) elif average_square(tu, lines_list) == 1: sq += 1 elif large_square(tu, lines_list) == 12: pass """Return the quantity of squares""" return sq if __name__ == '__main__': print("Example:") print(checkio([[1, 2], [2, 3], [5, 6], [6, 7], [5, 9], [9, 13], [13, 14], [14, 15], [7, 11], [11, 15]])) # print(checkio([[1, 2], [3, 4], [1, 5], [2, 6], [4, 8], [5, 6], [6, 7], # [7, 8], [6, 10], [7, 11], [8, 12], [10, 11], # [10, 14], [12, 16], [14, 15], [15, 16]])) # # assert (checkio([[1, 2], [3, 4], [1, 5], [2, 6], [4, 8], [5, 6], [6, 7], # [7, 8], [6, 10], [7, 11], [8, 12], [10, 11], # [10, 14], [12, 16], [14, 15], [15, 16]]) == 3), "First, from description" # assert (checkio([[1, 2], [2, 3], [3, 4], [1, 5], [4, 8], # [6, 7], [5, 9], [6, 10], [7, 11], [8, 12], # [9, 13], [10, 11], [12, 16], [13, 14], [14, 15], [15, 16]]) == 2), "Second, from description" # assert (checkio([[1, 2], [1, 5], [2, 6], [5, 6]]) == 1), "Third, one small square" # assert (checkio([[1, 2], [1, 5], [2, 6], [5, 9], [6, 10], [9, 10]]) == 0), "Fourth, it's not square" # assert (checkio([[16, 15], [16, 12], [15, 11], [11, 10], # [10, 14], [14, 13], [13, 9]]) == 0), "Fifth, snake" # print("Coding complete? Click 'Check' to earn cool rewards!")
from linkedlist import * node1 = Node(3) node2 = Node(4) print(node1.data) print(node2.data) node1.data = 5 print (node1.data) node1.nextNode = node2 print(node1.nextNode.data) print("\nLL TEST\n") myLL = LinkedList() myLL.add2Front(4) myLL.add2Front(3) myLL.add2Back(6) myLL.addinOrder(5) print(myLL.isIn(5)) print(myLL.isIn(12)) myLL.printAll()
# Erich Eden # SY301 # Dr. Mayberry # Lab 2 class Node: def __init__(self, data): self.data = data self.nextNode = None class LinkedList: def __init__(self): self.head = None self.tail = None def printAll(self): print ("list contains: \n") current = self.head if (current == None): #list is empty. Checked this bc otherwise my print tail would crash on an empty list print(" ") while (current.nextNode != None): print (current.data) current = current.nextNode print(current.data) #while loop exited before printing tail def add2Front(self, data): if (self.head == None): #if this is the first thing in the list newNode = Node(data) self.head = newNode self.tail = self.head else: newNode = Node(data) tmp = self.head #store prior head self.head = newNode newNode.nextNode = tmp #what was the head is now the next node for the new head def add2Back(self, data): if (self.tail == None): #list is empty newNode = Node(data) self.tail = newNode self.head = self.tail else: newNode = Node(data) self.tail.nextNode = newNode self.tail = newNode def isIn(self, data): current = self.head test = Node(data) while (current.nextNode != None): if (current.data == test.data): return True current = current.nextNode return False def addinOrder(self, data): current = self.head previous = self.head newNode = Node(data) if (newNode.data < current.data): #if new node should be first in LinkedList add2front(data) return if (newNode.data > self.tail.data): add2back(data) return while (current.data < newNode.data): previous = current current = current.nextNode newNode.nextNode = current previous.nextNode = newNode return
# Assigment: CoinFlips # Name: Akhmadjon Kurbanov import random # by flipping the coin get H (heads) or T (tails) def flipCoin(): return random.choice(['T','H']) # Return true of flips result has at least two heads, otherwise false def gotMatch(n): counter = 0 for i in range(n): if flipCoin() == 'H': counter += 1 if counter >= 2: return True return False # calculate probability empirically def empirProb(n, numTrials): numHits = 0 for i in range(numTrials): if gotMatch(n): numHits += 1 return numHits/numTrials # calculate probability theoretically def theorProb(n): return 1 - ((1+ n)/(2**n)) if __name__ == '__main__': numTrials = 10000 numFlips = [2, 3, 4, 5, 10, 20, 100] for n in numFlips: print('For N =', n) print('The Theoretical Probability:', round(theorProb(n), 4)) print('The Empirical Probability: ', round(empirProb(n, numTrials), 4)) print()
# Assigment: CoinFlips pt2 # Name: Akhmadjon Kurbanov import random import matplotlib.pyplot as plt # by flipping the coin get H (heads) or T (tails) def flipCoin(): return random.choice(['T','H']) # Return true of flips result has at least two heads, otherwise false def gotMatch(n, k): result = '' for i in range(n): result += flipCoin() if result.count('H') == k: return True return False # calculate probability empirically def empirProb(n, numTrials, k): numHits = 0 for i in range(numTrials): if gotMatch(n, k): numHits += 1 return numHits/numTrials # calculate probability theoretically def theorProb(n): return 1 - ((1+ n)/(2**n)) # draw a histogram def drawGraph(kList, probList): probList = [i * 100 for i in probList] plt.bar(kList, probList) plt.xticks(kList) plt.title('Probability for getting k heads per ' + str(numFlips) + ' flips after ' + str(numTrials) + ' trials') plt.ylabel('Probability (%)') plt.xlabel('Number of heads (k)') plt.show() if __name__ == '__main__': numTrials = 10000 numFlips = 10 kList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] probList = [] for k in kList: probList.append(round(empirProb(numFlips, numTrials, k), 4)) print(sum(probList)) drawGraph(kList, probList)
#!/usr/bin/env python #importing the library required, topics and mathematical functions import rospy #the main library for ROS functions in python from geometry_msgs.msg import Twist #the (node_turtle_revolve) node will publish velocities to this Twist from turtlesim.msg import Pose #the (node_turtle_revolve) node will subscribe to position of tutle at different instances from Pose from math import pow, sqrt #importing the math functions required to vary velocities class turtle_revolve(): def __init__(self): #defining the node, publisher and subcriber in this section rospy.init_node('node_turtle_revolve') self.vel_pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size = 10) self.pos_sub = rospy.Subscriber('/turtle1/pose', Pose, self.pos_callback) self.pose = Pose() self.rate = rospy.Rate(10) #defining the pos_callback function to update pose values def pos_callback(self, msg): self.pose = msg self.pose.x = round(self.pose.x, 4) self.pose.y = round(self.pose.y, 4) self.pose.theta = round(self.pose.theta, 4) #print(self.pose.x, self.pose.y, self.pose.theta) #calculating distance from updated_pose to goal_pose def distance(self, goal_x, goal_y): distance = sqrt(pow((goal_x - self.pose.x), 2) + pow((goal_y - self.pose.y), 2)) return distance #main loop function def main(self): goal_pose = Pose() goal_pose.x = 5.5344 #spawn_pose.x - distance_tolerance = goal_pose.x goal_pose.y = 5.5344 #spawn_pose.y - distance_tolerance = goal_pose.y distance_tolerance = 0.01 vel_msg = Twist() while sqrt(pow((goal_pose.x - self.pose.x), 2) + pow((goal_pose.y - self.pose.y), 2)) >= distance_tolerance: #linear velocity component vel_msg.linear.x = 0.9325 * sqrt(pow((goal_pose.x - self.pose.x), 2) + pow((goal_pose.y - self.pose.y), 2)) vel_msg.linear.y = 0 vel_msg.linear.z = 0 t1=float(rospy.Time.now().to_sec()) rospy.loginfo('moving in a circle... Time:') print t1 #angular velocity component vel_msg.angular.x = 0 vel_msg.angular.y = 0 vel_msg.angular.z = vel_msg.linear.x #equating to linear_velocity to get circle of radius 1 (unit) # [radius=(linear_velocity/angular_velocity)] #Publishing our vel_msg self.vel_pub.publish(vel_msg) self.rate.sleep() #terminating after the goal reached vel_msg.linear.x = 0 vel_msg.angular.z =0 self.vel_pub.publish(vel_msg) rospy.loginfo('goal reached. Final Time:') print t1 rospy.spin() #terminate executing script on ctrl+c if __name__ == '__main__': try: p = turtle_revolve() p.main() except rospy.ROSInterruptException: pass
#Arrays in python are called lists x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in x: print(i)
# # This is my work regarding a problem in Chapter 2 of Spraul's "Think Like a Programmer": # # Write a program that takes an identification number of arbitrary length and # determines whether the number is valid under the Luhn formula. The program must # process each character before reading the next one. # # Because we don't know the length in advance, we don't know which digits we should be doubling # and taking the digit sum of until the end. This program tackles the problem by doing the # computations for both possibilities as we go along, then choosing the right one to output. # def digit_list(myint): return [int(a) for a in list(str(myint))] def digit_sum_of_double(myint): return sum(digit_list(2 * myint)) def validity(check_digit): if check_digit == 0: return("Valid!") else: return("Invald :(") doubled_odd_positions_check_digit = 0 doubled_even_positions_check_digit = 0 current_position = 0 finished = False print("\nType the digits, pressing enter after each,") print("then press enter again when you're done.\n") while(not finished): s = input() if s != "": newdigit = int(s) current_position += 1 if current_position % 2 == 0: doubled_odd_positions_check_digit += newdigit doubled_even_positions_check_digit += digit_sum_of_double(newdigit) else: doubled_odd_positions_check_digit += digit_sum_of_double(newdigit) doubled_even_positions_check_digit += newdigit doubled_odd_positions_check_digit %= 10 doubled_even_positions_check_digit %= 10 else: if (current_position % 2 == 0): print(validity(doubled_odd_positions_check_digit)) else: print(validity(doubled_even_positions_check_digit)) finished = True
import math class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ max = math.pow(2,31) if x >= 0: flag = 1 else: flag = -1 _ = str(abs(x)) reverse = _[::-1] result = int(reverse) if flag == -1: result = result * (-1) if result > max or result < -max: result = 0 return result
n = int(input("plase enter n: ")) m = int(input("enter m: ")) for i in range(n): for j in range(m): if (i+j) %2==0: print('*', end=" ") else: print('#', end=" ") print()
"""CPU functionality.""" import time import sys class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.reg = [0] * 8 self.pc = 0 self.reg_pc = 0 self.sp = 6 self.flag = [0] * 8 def ram_read(self, pos): return self.ram[pos] def ram_write(self, value, pos): self.ram[pos] = value def load(self): """Load a program into memory.""" address = 0 if len(sys.argv) != 2: print("Program requires second system argument to run.") sys.exit(1) try: with open(sys.argv[1]) as f: for line in f: temp = line.split() if len(temp) == 0 or temp[0][0] == "#": continue try: self.ram[address] = int(temp[0], 2) except ValueError: print(f"Invalid value: {int(temp[0], 2)}") address += 1 except FileNotFoundError: print(f"Couldn't open {sys.argv[1]}") sys.exit(2) if address == 0: print("Program is empty!") sys.exit(3) def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == "ADD": self.reg[reg_a] += self.reg[reg_b] elif op == "SUB": self.reg[reg_a] -= self.reg[reg_b] elif op == "MUL": self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b] elif op == "DIV": self.reg[reg_a] = self.reg[reg_a] / self.reg[reg_b] elif op == "CMP": if self.reg[reg_a] == self.reg[reg_b]: self.flag[-1] = 1 elif self.reg[reg_a] < self.reg[reg_b]: self.flag[-3] = 1 elif self.reg[reg_a] > self.reg[reg_b]: self.flag[-2] = 1 else: raise Exception("Unsupported ALU operation") def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f"TRACE: %02X | %02X %02X %02X |" % ( self.pc, # self.fl, # self.ie, self.ram_read(self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2) ), end='') for i in range(8): print(" %02X" % self.reg[i], end='') def run(self): """Run the CPU.""" self.running = True while self.running: # Ensures we won't need to restart Anaconda Prompt # every time that something goes wrong. start = time.time() if time.time() - start > 0.5: return # LDI - sets value of register to integer if self.ram_read(self.pc) == 0b10000010: if 0 not in self.reg: break # self.reg[self.reg_pc] = self.ram_read(self.pc + 2) # self.reg_pc += 1 self.reg[self.ram_read(self.pc + 1) ] = self.ram_read(self.pc + 2) self.pc += 3 # PRN, R0 if self.ram_read(self.pc) == 0b01000111: print(self.reg[self.ram_read(self.pc + 1)]) self.pc += 2 # HALT if self.ram_read(self.pc) == 0b00000001: break if self.ram_read(self.pc) == 0b10100010: self.alu("MUL", 0, 1) self.pc += 3 # PUSH if self.ram_read(self.pc) == 0b01000101: # Decrement self.sp self.reg[self.sp] -= 1 # Get value from self.reg reg_num = self.ram[self.pc + 1] value = self.reg[reg_num] # Store value on Stack top_stack_addr = self.reg[self.sp] self.ram[top_stack_addr] = value self.pc += 2 # POP if self.ram_read(self.pc) == 0b01000110: # Get value from self.ram addr_to_pop = self.reg[self.sp] value = self.ram[addr_to_pop] # Store in self.reg reg_num = self.ram[self.pc + 1] self.reg[reg_num] = value # Increment self.sp self.reg[self.sp] += 2 self.pc += 2 # CMP if self.ram_read(self.pc) == 0b10100111: self.alu("CMP", 0, 1) self.pc += 3 # JMP if self.ram_read(self.pc) == 0b01010100: self.pc = self.reg[self.ram_read(self.pc + 1)] # JEQ if self.ram_read(self.pc) == 0b01010101: if self.flag[-1] == 1: self.pc = self.reg[self.ram_read(self.pc + 1)] else: self.pc += 2 # JNE if self.ram_read(self.pc) == 0b01010110: if self.flag[-1] == 0: self.pc = self.reg[self.ram_read(self.pc + 1)] else: self.pc += 2
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: node = ListNode(0) dummy = node while l1 or l2: total_node = dummy.val if l1: # print(l1.val) total_node +=l1.val l1 = l1.next if l2: total_node +=l2.val l2 = l2.next dummy.val = (total_node%10) if l1 or l2 or total_node>9: dummy.next = ListNode(total_node//10) dummy = dummy.next return (node)
""" Valid Starting City Imagine you have a set of cities that are laid out in a circle, connected by a circular road that runs clockwise. Each city has a gas station that provides gallons of fuel, and each city is some distance away from the next city. You have a car that can drive some number of miles per gallon of fuel, and your goal is to pick a starting city such that you can fill up your car with that city's fuel, drive to the next city, refill up your car with that city's fuel, drive to the next city, and so on and so forth until you return back to the starting city with 0 or more gallons of fuel left. This city is called a valid starting city, and it's guaranteed that there will always be exactly one valid starting city. For the actual problem, you'll be given an array of distances such that city i is distances[i] away from city i + 1. Since the cities are connected via a circular road, the last city is connected to the first city. In other words, the last distance in the distances array is equal to the distance from the last city to the first city. You'll also be given an array of fuel available at each city, where fuel[i] is equal to the fuel available at city i. The total amount of fuel available (from all cities combined) is exactly enough to travel to all cities. Your fuel tank always starts out empty, and you're given a positive integer value for the number of miles that your car can travel per gallon of fuel (miles per gallon, or MPG). You can assume that you will always be given at least two cities. Write a function that returns the index of the valid starting city. Sample Input distances = [5, 25, 15, 10, 15] fuel = [1, 2, 1, 0, 3] mpg = 10 Sample Output 4 """
""" This module colects the weather information that will be used in the main module """ import requests import json def get_weather(): """ This function colects and process al the data and returns a string with the content of the weather notifications of the main module """ #Read configuration file and sets the parameters with open('config.json', 'r') as configfile: weather = json.load(configfile) api_key = weather["weather"]["api_key"] base_url = weather["weather"]["base_url"] city_name = weather["weather"]["city_name"] complete_url = base_url + "appid=" + api_key + "&q=" + city_name response = requests.get(complete_url) info = response.json() #Relevant information is extracted air_temperature = round(info["main"]["temp"]-273.15, 2) feels_like = round(info["main"]["feels_like"]-273.15, 2) weather_description = info["weather"][0]["description"] location_name = info["name"] location_temp_text = "At "+ str(location_name)+" the air temperature is " + str(air_temperature) feels_like_temp = ", but it feels like " + str(feels_like) weather_description_text = ". The weather description is " + str(weather_description) + "." return location_temp_text + feels_like_temp + weather_description_text
import requests from bs4 import BeautifulSoup import csv from jumia_db import * ##To crawl in disguise headers = requests.utils.default_headers() headers.update( { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" } ) ## FOR NAIRALAND # The desired web application url = "https://nairaland.com" my_response = requests.get(url, headers) ##.get() helps assess the url passed to it as arguments # print(my_response.status_code) fresh_soup = BeautifulSoup(my_response.content, features ="lxml") # print(fresh_soup.prettify()) first_search = fresh_soup.find("td", attrs={"class": "featured w"}) # print(first_search.prettify()) second_search = first_search.find_all("a") # find_all() returns a list # print(second_search[:5]) # pretty_second = [print(entry.text) for entry in second_search] mined_data = [] for index, entry in enumerate(second_search): index += 1 news_headline = entry.text # print(entry.prettify()) needed_link = entry["href"] # To navigate to the new url new_response = requests.get(needed_link, headers) new_soup = BeautifulSoup(new_response.content, features = "lxml") # print(new_soup.prettify()) desired_tag = new_soup.find("p", attrs= {"class": "bold"}) # print(desired_tag.prettify()) number_of_views = str(desired_tag).split("</a>")[-1].split("</p>")[0].strip(" () ").split(" ")[0] # print(number_of_views) mined_data.append([index, news_headline, number_of_views]) # print(mined_data) new_file = open("/Users/drizzytom/Documents/PHYTHON/Data_Sci/nairaland_news_views.csv", mode="w", encoding="utf-8", newline="") pen = csv.writer(new_file) pen.writerow(["S/N", "News Headline", "Number of Views"]) # To write smartly pen.writerows(mined_data) new_file.close()
def getPath(start, hierarchy): if start in hierarchy: l = getPath(hierarchy[start], hierarchy) l.append(start) return l else: return [] def travelUpTree(obj, hierarchy): if obj in hierarchy: #print("found parent for",obj,":",hierarchy[obj]) return 1+ travelUpTree(hierarchy[obj], hierarchy) else: #print("no found parent for",obj) return 0 orbits = {} parents = {} objects = set() with open("../../day6.txt","r") as f: #test = """COM)B ,B)C ,C)D ,D)E ,E)F ,B)G ,G)H ,D)I ,E)J ,J)K ,K)L ,K)YOU ,I)SAN """ #for line in test.split(","): for line in f: orbit = line[:-1].split(")") orbits.setdefault(orbit[0],[]).append(orbit[1]) parents[orbit[1]] = orbit[0] objects.add(orbit[0]) objects.add(orbit[1]) #print(parents) YOUpath = getPath("YOU", parents) SANpath = getPath("SAN", parents) print(YOUpath) print(SANpath) print( [x for x in YOUpath+SANpath if (YOUpath+SANpath).count(x) == 1 and x != "YOU" and x != "SAN"])
RIGHT = (0,1) DOWN = (1,0) UP = (-1,0) LEFT = (0,-1) DIRECTIONS = [UP,RIGHT,DOWN,LEFT] TURNS = [-1, 0, 1] LEFTTURN = "\\" LEFTTURNS = {0:3,1:2,2:1,3:0} RIGHTTURN = "/" RIGHTTURNS = {0:1,1:0,2:3,3:2} INTERSECTION = "+" area = [] #cart : y,x,direction,nextTurn carts = [] def printArea(area, carts): areaCopy = list([list(row) for row in area]) for cart in carts: if cart[2] == 0: areaCopy[cart[0]][cart[1]] = "^" if cart[2] == 2: areaCopy[cart[0]][cart[1]] = "v" if cart[2] == 3: areaCopy[cart[0]][cart[1]] = "<" if cart[2] == 1: areaCopy[cart[0]][cart[1]] = ">" for line in areaCopy: print "".join(line) def intersection(cart): turn((len(DIRECTIONS) + cart[2] + TURNS[cart[3]]) % len(DIRECTIONS), cart) cart[3] = (cart[3]+1) % len(TURNS) def turn(direction, cart): cart[2] = direction def checkCollisions(carts): positions = [(cart[0],cart[1]) for cart in carts ] return len([pos for pos in positions if positions.count(pos) > 1]) with open("../../data/13.txt", "r") as f: y = 0 for line in f: row = [] area.append(row) x = 0 for c in line[:-1]: if c == "^": carts.append([y,x,0, 0]) row.append("s") elif c == "<": carts.append([y,x,3, 0]) row.append("s") elif c == ">": carts.append([y,x,1, 0]) row.append("s") elif c == "v": carts.append([y,x,2, 0]) row.append("s") else: row.append(c) x += 1 y += 1 collisions = 0 #printArea(area, carts) while collisions == 0: for cart in carts: cart[0] += DIRECTIONS[cart[2]][0] cart[1] += DIRECTIONS[cart[2]][1] if area[cart[0]][cart[1]] == LEFTTURN: turn(LEFTTURNS[cart[2]], cart) if area[cart[0]][cart[1]] == RIGHTTURN: turn(RIGHTTURNS[cart[2]], cart) if area[cart[0]][cart[1]] == INTERSECTION: intersection(cart) if(checkCollisions(carts)): collisions += 1 print "collision at",cart[1],cart[0] break #printArea(area, carts)
with open('data.txt') as file: positions = [int(x) for x in file.readline().split(',')] def findFuelCost(positions, target): cost = 0 for x in positions: cost += sum(range(abs(x-target)+1)) return cost def findMinimumFuelCost(positions, guess): neighborhood = {guess:findFuelCost(positions, guess), guess+1:findFuelCost(positions, guess+1), guess-1:findFuelCost(positions, guess-1)} newValues = sorted(neighborhood, key=lambda a:neighborhood[a]) #print(guess,":",neighborhood) if (guess == newValues[0]): return newValues[0] else: return findMinimumFuelCost(positions, newValues[0]) #test data #positions = [16,1,2,0,4,2,7,1,2,14] print(findMinimumFuelCost(positions, sum(positions)//len(positions)))
from collections import namedtuple targetX = [85,145] targetY = [-163,-108] #targetX = [20,30] #targetY = [-5,-1] targetArea = set((x,y) for x in range(targetX[0],targetX[1]+1) for y in range(targetY[0],targetY[1]+1)) Velocity = namedtuple('Velocity',['x','y']) def simulate(x,y, vel, path): #print(x,y,vel) path.add((x,y)) if (x,y) in targetArea: return (True,path) if x>targetX[1] or y<targetY[0]: return (False,path) drag = 0 if vel.x != 0: drag = vel.x-(vel.x//abs(vel.x)) return simulate(x+vel.x,y+vel.y,Velocity(drag,vel.y-1),path) def findHighestParabola(xguess, yguess,path): success, overshot = simulate(0,0,Velocity(xguess,yguess),path) print("simulating",xguess, yguess, success, overshot) path = set() """ 162 found by reasoning; The probe trajectory (=function) always intersects the x-axis with x_vel=0, if start y_vel>0. The highest point in the parabola must be reached when the probe falls the maximum amount the next step. The maximum the probe can sink is the deepest point in the target area, i.e. -163, thus with start y_vel=162 it sinks 163 units. """ findHighestParabola(4,162,path) print(max(path,key=lambda a:a[1]))
from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bets", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] def create_turtle(num): x = -230 y = -130 turtles = [] position = 0 for _ in range(num): y += 40 turtles.append(Turtle(shape="turtle")) turtles[_].penup() turtles[_].color(colors[position]) turtles[_].goto(x, y) position += 1 return turtles all_turtles = create_turtle(6) if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: if turtle.xcor() > 230: is_race_on = False winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} turtle is the winner!") else: print(f"You've lost! The {winning_color} turtle is the winner!") rand_distance = random.randint(0, 10) turtle.forward(rand_distance) screen.exitonclick()
from builders import * def numberToWords(number): try: number = int(number) if number < 0: return 'Expresión inválida' except: return 'Expresión inválida' if number == 0: return 'cero' if number >= 1 and number < 1000: return hundredBuilder(number) if number >= 1000 and number < 1000000: return sixDigitsBuilder(number) if number >= 1000000 and number < 1000000000: return sevenDigitsBuilder(number) if number == 1000000000: return 'un millardo' return 'Andate a cagar' try: numero = input('Ingrese un valor numerico positivo: ') print(numberToWords(numero)) except: print('error')
# # The Vector class represents a position, a force or a direction. # class Vector: def __init__(self, x, y): ### Test if arguments are of correct type if not isinstance(x, int) and not isinstance(x, float) and x != None: raise TypeError(f"unsupported type(s) for Vector.x: '{type(x)}'") if not isinstance(y, int) and not isinstance(y, float) and y != None: raise TypeError(f"unsupported type(s) for Vector.y: '{type(y)}'") ### self._x = x self._y = y # Get methods def _get_x(self): return self._x def _get_y(self): return self._y # Set methods def _set_x(self, x): ### Test if arguments are of correct type if not isinstance(x, int) and not isinstance(x, float) and x != None: raise TypeError(f"unsupported type(s) for Point.x: '{type(x)}'") self._x = x def _set_y(self, y): ### Test if arguments are of correct type if not isinstance(y, int) and not isinstance(y, float) and y != None: raise TypeError(f"unsupported type(s) for Point.y: '{type(y)}'") self._y = y # Add get methods and set methods x = property(_get_x, _set_x) y = property(_get_y, _set_y) def __add__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(self.x + value.x, self.y + value.y) elif isinstance(value, int) or isinstance(value, float): return Vector(self.x + value, self.y + value) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __radd__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(value.x + self.x, value.y + self.y) elif isinstance(value, int) or isinstance(value, float): return Vector(value + self.x, value + self.y) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __sub__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(self.x - value.x, self.y - value.y) elif isinstance(value, int) or isinstance(value, float): return Vector(self.x - value, self.y - value) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __rsub__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(value.x - self.x, value.y - self.y) elif isinstance(value, int) or isinstance(value, float): return Vector(value - self.x, value - self.y) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __mul__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(self.x * value.x, self.y * value.y) elif isinstance(value, int) or isinstance(value, float): return Vector(self.x * value, self.y * value) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __rmul__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(value.x * self.x, value.y * self.y) elif isinstance(value, int) or isinstance(value, float): return Vector(value * self.x, value * self.y) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __truediv__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(self.x / value.x, self.y / value.y) elif isinstance(value, int) or isinstance(value, float): return Vector(self.x / value, self.y / value) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'") def __rtruediv__(self, value): ### Test if arguments are of correct type if isinstance(value, Vector): return Vector(value.x / self.x, value.y / self.y) elif isinstance(value, int) or isinstance(value, float): return Vector(value / self.x, value / self.y) else: raise TypeError(f"unsupported type(s) for operator +: '{type(value)}'")
print('Введите число') a=input() summa=0 m=0 while a !="": a=int(a) summa=summa+a m+=1 print(summa, a) print('Введите число') a=input() if a =="": average=summa/m print('Среднее арифметическое=', average)
# Group Anagrams # Given an array of strings, group anagrams together. # Example: # Input: ["eat", "tea", "tan", "ate", "nat", "bat"], # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] # Note: # All inputs will be in lowercase. # The order of your output does not matter. class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: pattern = [] ans = [] num_pattern = 0 for i in range(len(strs)): if sorted(strs[i]) not in pattern: num_pattern += 1 pattern.append(sorted(strs[i])) ans.append([strs[i]]) else: index = pattern.index(sorted(strs[i])) ans[index].append(strs[i]) return ans
def is_number_correct(number): # Votre code ici result = number >= 10 and number <= 20 diff = 0 if result == False: if number < 10: diff = 10 - number elif number > 20: diff = 20 - number return (result, diff) def run(): assert is_number_correct(0) == (False, 10) assert is_number_correct(10) == (True, 0) assert is_number_correct(20) == (True, 0) assert is_number_correct(21) == (False, -1) assert is_number_correct(50) == (False, -30) assert is_number_correct(15) == (True, 0)
def NEWTON_METHOD(number): number=float(number) ε=10**-10 num_old=number num_new=number/2 while abs(1-num_old/num_new)>ε: num_old=num_new num_new=(num_old+number/num_old)/2 return num_new
from sympy import * from tkinter_math.calculation.common.STR import STR x = Symbol('x') def taylor(formula,dimension,center): try: f=sympify(formula) center=float(center) A=f.subs(x,center) for number in range(1,int(dimension)+1,1): f=diff(f) D=f.subs(x,center)/factorial(number) A=D*(x-center)**number+A anser=STR(formula)+"≒"+STR(A) anser_2=str(formula)+"≒"+str(A) print("------------------------------------------------------------------------------------------------------------------------") print(anser+"\n\n"+anser_2+"\n") except: anser="Error" print("Error") return anser
import tkinter from tkinter_math.calculation import * def sub_window_7(): def sub_window_7_1(): def calc_7_1(): try: a=int(txt_7_1_1.get()) root_7_1.destroy() sub_window_7_2(a) except: lbl_7_1_2=tkinter.Label(root_7_1,text="Error",font=("",15),fg="#ff0000") lbl_7_1_2.place(x=200,y=0) root_7_1=tkinter.Toplevel() root_7_1.title(u"連立方程式") root_7_1.geometry("400x180") root_7_1.resizable(False, False) btn_7_1_1=tkinter.Button(root_7_1,text="実行",command=calc_7_1,width=40,height=3) btn_7_1_1.place(x=50,y=80) btn_7_1_2=tkinter.Button(root_7_1,text="連立方程式を閉じる",command=root_7_1.destroy,width=40,height=1,bg="#ffa300") btn_7_1_2.place(x=50,y=140) lbl_7_1_1=tkinter.Label(root_7_1,text="式の数を入力してください",font=("",15)) lbl_7_1_1.place(x=20,y=30) txt_7_1_1=tkinter.Entry(root_7_1,width=4,font=("",30)) txt_7_1_1.place(x=270,y=25) root_7_1.mainloop() def sub_window_7_2(a): def calc_7_2(): try: formura=[] for i in range(0,int(a),1): formura.append(txt_7_2_1[i].get()) anser=equations.equations(formura) except: anser=["Error"] listbox.delete(0,tkinter.END) for i in range(0,len(anser),1): listbox.insert(tkinter.END,anser[i]) width=1000 height=a*40+550 root_7_2=tkinter.Toplevel() root_7_2.title(u"連立方程式") root_7_2.geometry(f"{width}x{height}") root_7_2.resizable(False, False) btn_7_2_1=tkinter.Button(root_7_2,text="計算",width=20,command=calc_7_2,font=("",20)) btn_7_2_1.place(x=380,y=a*45+45) btn_7_2_2=tkinter.Button(root_7_2,text="連立方程式を閉じる",width=20,command=root_7_2.destroy,font=("",20),bg="#ffa300") btn_7_2_2.place(x=380,y=a*45+450) lbl_7_2_1=[] lbl_7_2_2=[] for i in range(0,int(a),1): lbl_7_2_1.append(tkinter.Label(root_7_2,text="式{}".format(i+1),font=("",30))) lbl_7_2_1[i].place(x=0,y=i*45+30) lbl_7_2_2.append(tkinter.Label(root_7_2,text="=0",font=("",30))) lbl_7_2_2[i].place(x=930,y=i*45+30) lbl_7_2_a=tkinter.Label(root_7_2,text="解",font=("",30)) lbl_7_2_a.place(x=10,y=a*45+250) txt_7_2_1=[] for i in range(0,int(a),1): txt_7_2_1.append(tkinter.Entry(root_7_2,width=42,font=("",30))) txt_7_2_1[i].place(x=80,y=i*45+30) scrollbar_frame = tkinter.Frame(root_7_2) scrollbar_frame.grid(padx=80, pady=a*45+100) listbox = tkinter.Listbox(scrollbar_frame,height=8,width=42,font=("",30)) listbox.pack(side=tkinter.LEFT) yscroll_bar =tkinter.Scrollbar(scrollbar_frame, command=listbox.yview) yscroll_bar.pack(side=tkinter.RIGHT, fill=tkinter.Y) listbox.config(yscrollcommand=yscroll_bar.set) root_7_2.mainloop() sub_window_7_1()
# Keep these 2 lines text_to_translate = input("Text to translate: ") VOWELS = "aeiouyAEIOUY" # ...add your code here text_list = text_to_translate.split() translation = "" for word in text_list: if word[0] in VOWELS: word = word + "yay" translation = translation + word + " " elif word[0] not in VOWELS: while word[0] not in VOWELS: word = word[1:]+word[0] word =word +"ay" translation = translation + word +" " # Keep this line print("Translation:", translation)
a = bool(int(input("A"))) b = bool(int(input("B"))) c = bool(int(input("C"))) d = int((a and not b)or(not b and c)) # compute d print("D is", d)
# is_prime function definition goes here def is_prime(number): for x in range(2, number): if number % x == 0: return False else: pass if number % number == 0 and number % 1 == 0: return True max_num = int(input("Input an integer greater than 1: ")) for x in range (2, max_num+1): if is_prime(x) == True: print("{} is a prime".format(x)) else: print("{} is not a prime".format(x)) # Call the function here repeatadly from 2 to max_num and print out the appropriate message
#Algorithm #1 make loop that loops n time #2 make variables and get the sum of them n = int(input("Enter the length of the sequence: ")) # Do not change this line count = 0 sequence1 = 1 sequence2 = 2 sequence3 = 3 while count < n: if sequence1 < sequence2: print(sequence1) sequence1 = sequence3 + sequence2 count +=1 elif sequence2 < sequence3: print(sequence2) sequence2 = sequence1 + sequence3 count +=1 elif sequence3 < sequence1: print(sequence2) sequence2 = sequence1 + sequence3 count +=1
secs_str = input("Input seconds: ") # do not change this line hours = int(secs_str) // 3600 minutes = (int(secs_str) % 3600) // 60 seconds = (int(secs_str) % 3600) % 60 print(hours,":",minutes,":",seconds) # do not change this line
num = int(input("Input a number: ")) # Do not change this line # Fill in the missing code below print("Negative") # Do not change this line print("Positive") # Do not change this line print("Zero") # Do not change this line
''' ANKIT KHANDELWAL 15863 Exercise 4 Square Wave ''' from math import floor import matplotlib.pyplot as plt import numpy as np def f(t): if floor(2 * t) % 2 == 0: return 1 else: return -1 xv = np.linspace(0, 1, 1000) values = [] for i in range(1000): values.append(f(xv[i])) plt.plot(xv, values, label='Square Wave') v_fft = np.fft.rfft(values) v_fft[10:] = 0 v_inverse = np.fft.irfft(v_fft) plt.plot(xv, v_inverse, label='Smoothing using first 10 coefficients') plt.legend(loc='lower left', framealpha=0) plt.show() ''' As the function must be periodic, it needs to deviate to acheive periodicity. This results in large fluctuations at end points. Also, because we are only using 10 modes, we get wiggles in the result. We need to use more modes to get better result here. This is because FT is by definition using sines and cosines. And we are approximating a straight line with these. '''
''' ANKIT KHANDELWAL 15863 Exercise 9 ''' import math prime = [2] for n in range(3, 10000): low_i = int(math.sqrt(n)) for i in prime: if n % i == 0: break if i > low_i: prime.append(n) break print('Prime numbers upto 10000 are:') print(prime)
''' ANKIT KHANDELWAL 15863 Exercise 1 ''' import math def altitude(T): R_Earth = 6378100 g_Earth = 9.803 R_sat = ((T * R_Earth * math.sqrt(g_Earth)) / 2 / math.pi) ** (2 / 3) return R_sat - R_Earth # 1a T = int(input('Enter period of rotation in seconds: ')) print('The altitude of satellite above Earth\'s surface is:', altitude(T), 'meters.\n') # 1b print('The altitude of satellite above Earth\'s surface is:', altitude(90 * 60), 'meters for orbit period of 90 minutes.\n') print('The altitude of satellite above Earth\'s surface is:', altitude(45 * 60), 'meters for orbit period of 45 minutes.\n') print('The altitude of satellite above Earth\'s surface is:', altitude(1 * 24 * 60 * 60), 'meters for orbit period of 1 day.\n') ''' The result shows that we can not have an orbit period of 45 minutes. ''' # 1c print('The altitude of satellite above Earth\'s surface is:', altitude(24 * 60 * 60), 'meters for orbit period of 24 hours.\n') print('The altitude of satellite above Earth\'s surface is:', altitude(23.93 * 60 * 60), 'meters for orbit period of 23.93 hours.\n') print('The difference between the two is:', altitude(24 * 60 * 60) - altitude(23.93 * 60 * 60), 'meters.\n') ''' Earth does not take complete 24 hours for one rotation around its axis. Thus if we use 24 days, the satellite will not remain geosynchronous. '''
''' ANKIT KHANDELWAL 15863 Exercise 2 ''' import math def polar(x, y): r = math.sqrt(x ** 2 + y ** 2) if x == 0: if y > 0: theta_degrees = 90 elif y == 0: theta_degrees = 0 else: theta_degrees = 270 else: theta = math.atan(abs(y / x)) theta_degrees = math.degrees(theta) if y >= 0 and x > 0: theta_degrees = theta_degrees elif y > 0 and x < 0: theta_degrees = theta_degrees + 90 elif y <= 0 and x < 0: theta_degrees = theta_degrees + 180 elif y < 0 and x > 0: theta_degrees = theta_degrees + 270 return (r, theta_degrees) x = int(input('Enter X cordinate: ')) y = int(input('Enter Y cordinate: ')) (r, theta_degrees) = polar(x, y) print('\nThe point in polar cordinates is: (', r, ',', theta_degrees, ')')
""" Ankit Khandelwal 15863 Exercise 2 """ from math import sqrt a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) [x1, x2] = [(-b + sqrt(b ** 2 - 4 * a * c)) / 2 / a, (-b - sqrt(b ** 2 - 4 * a * c)) / 2 / a] print('Solutions of ', a, 'x^2 +', b, 'x +', c, '= 0 is by first formula: ', [x1, x2]) [x11, x22] = [2 * c / (-b - sqrt(b ** 2 - 4 * a * c)), 2 * c / (-b + sqrt(b ** 2 - 4 * a * c))] print('\nSolutions of ', a, 'x^2 +', b, 'x +', c, '= 0 by modified formula is: ', [x11, x22], ) if b < 0: xA = 2 * c / (-b + sqrt(b ** 2 - 4 * a * c)) xB = (-b + sqrt(b ** 2 - 4 * a * c)) / 2 / a else: xA = (-b - sqrt(b ** 2 - 4 * a * c)) / 2 / a xB = 2 * c / (-b - sqrt(b ** 2 - 4 * a * c)) print('\nSolutions of ', a, 'x^2 +', b, 'x +', c, '= 0 by modified general formula is: ', xA, xB)
import statistics import json class TestResultContainer: """ This is a class for holding test results and calculating statistics on the values Attributes: results (dictionaty): holds input values with key as type of input and value as list of values avgMeans (dictionary): holds calculated mean statstic for variables avgStDevs (dictionary): holds calculated standard deviation for variables """ def __init__(self): """ Initalizes instance of class Attributes: results (dictionaty): holds input values with key as type of input and value as list of values avgMeans (dictionary): holds calculated mean statstic for variables avgStDevs (dictionary): holds calculated standard deviation for variables """ self.results = {"Throughput": [], "RTT": [], "ConnectionStatus": []} self.avgMeans = {"Throughput": 0, "RTT": 0, "ConnectionStatus": 0} self.avgStDevs = {"Throughput": 0, "RTT": 0, "ConnectionStatus": 0} def addThroughput(self, inputThroughput): """ Adds throughput value to dictionary Parameters: inputThroughput: value for throughput entered by user for test case """ self.results["Throughput"].append(inputThroughput) def addRTT(self, inputRTT): """ Adds RTT value to dictionary Parameters: inputRTT: value for RTT entered by user for test case """ self.results["RTT"].append(inputRTT) def addConnectionStatus(self, inputConnectionStatus): """ Adds connection status value to dictionary Parameters: inputConnectionStatus: value for connection status entered by user for test case """ self.results["ConnectionStatus"].append(inputConnectionStatus) def calcAvg(self): """ calculate average of the three values and add to dictionary round to 3 decimal places """ self.avgMeans["Throughput"] = round(statistics.mean(self.results["Throughput"]), 3) self.avgMeans["RTT"] = round(statistics.mean(self.results["RTT"]), 3) self.avgMeans["ConnectionStatus"] = round(statistics.mean(self.results["ConnectionStatus"]), 3) def calcStDev(self): """ calculate standard deviation of the three values and add to dictionary round to 3 decimal places """ self.avgStDevs["Throughput"] = round(statistics.stdev(self.results["Throughput"]), 3) self.avgStDevs["RTT"] = round(statistics.stdev(self.results["RTT"]), 3) self.avgStDevs["ConnectionStatus"] = round(statistics.stdev(self.results["ConnectionStatus"]), 3) def write_to_json(self): """ write results dictionary to json file """ with open('results.json', 'w') as fp: json.dump(self.results, fp)
import string alphabet = string.ascii_letters def is_pangram(phrase): import pdb; pdb.set_trace() words = phrase.split() count = 0 for word in words: letters = word.split() count += letters.count() return count >= 26
def feets_to_meters(a): return (a*0.3048) def meters_to_feet(b): return(b/0.3048) c=50 d=10 print("{0} feets are {1} meters.".format(c,feets_to_meters(c))) print("{0} meters are {1} feets.".format(d,meters_to_feet(d)))
#from: https://realpython.com/python3-object-oriented-programming/ import dog_father dog = dog_father.Dog # Instantiate the Dog ob# Class Attribute philo = dog("Philo", 15) mikey = dog("Mikey", 16) # Access the instance attributes print("{} is {} and {} is {}.".format( philo.name, philo.age, mikey.name, mikey.age)) # Is Philo a mammal? if philo.species == "mammal": print("{0} is a {1}!".format(philo.name, philo.species))
""" Algorithm to categorize elements into equivalence classes http://code.activestate.com/recipes/499354-equivalence-partition/ """ def equivalence_partition( iterable, relation, verbose=False ): """ Partitions a set of objects into equivalence classes\n", Args:\n", iterable: collection of objects to be partitioned\n", relation: equivalence relation. I.e. relation(o1,o2) evaluates to True\n", if and only if o1 and o2 are equivalent\n", Returns: classes, partitions\n", partitions: A dictionary mapping objects to equivalence classes\n", """ class_representatives = [] partitions = {} try: for counter, obj in enumerate(iterable): # for each object # find the class it is in\n", found = False for k, element in enumerate(class_representatives): if relation( element, obj ): # is it equivalent to this class? partitions[counter] = k found = True break if not found: # it is in a new class\n", class_representatives.append( obj ) partitions[counter] = len(class_representatives) - 1 if verbose: print('Tested {:d} elements and found {:d} classes'.format(counter+1,len(class_representatives))) except KeyboardInterrupt: pass return class_representatives, partitions
def arithmetic_arranger(problems: list, result=False): if len(problems) > 5: return "Error: Too many problems." line1 = "" line2 = "" line3 = "" line4 = "" for idx, problem in enumerate(problems): first, op, second = problem.split() if op not in ["+", "-"]: return "Error: Operator must be '+' or '-'." if not first.isdecimal() or not second.isdecimal(): return "Error: Numbers must only contain digits." if len(first) > 4 or len(second) > 4: return "Error: Numbers cannot be more than four digits." num_length = len(max([first, second], key=len)) line1 += first.rjust(num_length + 2) line2 += op + second.rjust(num_length + 1) line3 += "-" * (num_length + 2) if result: res = int(first) + int(second) if op == "+" else int(first) - int(second) line4 += str(res).rjust(num_length + 2) if idx < len(problems) - 1: line1 += " " line2 += " " line3 += " " line4 += " " final_str = line1 + "\n" + line2 + "\n" + line3 if result: final_str += "\n" + line4 return final_str
############ # Pecoraro Cyril # Design and Analysis of Algorithms - Week 1 # Merge-sort algorithm # August 2016 ############ from Week1.functions import merge_sort import numpy as np input_Array = np.loadtxt("test1.txt", dtype="int") n = len(input_Array) #Largest possible number of inversion max_inversion = n*(n-1)/2 #Merge-sort output_Array,total_inv = merge_sort(input_Array) #print output_Array print ("number of inversions :") print (total_inv)
#!/bin/env python2.7 # !Important! # To execute the program, in your commandline prompt, type in the following command: # python clockAngles.py <test file name> > ClockAngles.txt # replace <test file name> with your own file name import sys times = [] class Time: def __init__(self, time_str): times_list = time_str.split(':') self.h = int(times_list[0]) # hour self.m = int(times_list[1]) # minutes self.s = int(times_list[2]) # seconds self.s_tot = self.h * 3600 + self.m * 60 + self.s # time in seconds def __str__(self): return str(self.h) + ":" + str(self.m) + ":" + str(self.s) def getHourAngle(self): # angle = 360 / (12 * 60 * 60) = 1/120 deg/s angle = self.s_tot/120.0 return angle % 360 def getMinuteAngle(self): # angle = 360 / (60 * 60) = 1/10 deg/s angle = self.s_tot/10.0 return angle % 360 def getSecondAngle(self): # angle = 360 / 60 deg/s = 6 deg/s angle = self.s_tot*6.0 return angle % 360 def printAngles(self): print "Angles: h = %.2f, m = %.2f, s = %.2f" % (self.getHourAngle(), self.getMinuteAngle(), self.getSecondAngle()) def getHourMinuteAngle(self): angle_diff = abs(self.getHourAngle() - self.getMinuteAngle()) if (angle_diff > 180): angle_diff = 360 - angle_diff return angle_diff def getHourSecondAngle(self): angle_diff = abs(self.getHourAngle() - self.getSecondAngle()) if (angle_diff > 180): angle_diff = 360 - angle_diff return angle_diff def getMinuteSecondAngle(self): angle_diff = abs(self.getMinuteAngle() - self.getSecondAngle()) if (angle_diff > 180): angle_diff = 360 - angle_diff return angle_diff def printAngleDifferences(self): # format: hour-minute, hour-second, minute-second print "%.2f, %.2f, %.2f" % (round(self.getHourMinuteAngle(),2), round(self.getHourSecondAngle(),2), round(self.getMinuteSecondAngle(),2)) def main(): f = open(sys.argv[1], 'r') # Read in number of inputs n = int(f.readline()) # Read in each line (corresponds to one time HH:MM:SS and it put it in times for i in range(n): line = f.readline() time = line.rstrip('\n\r') times.append(Time(time)); f.close() # Print number of times print n # Print each set of angle differences for time in times: time.printAngleDifferences() main()
''' A program to test hash function variations ''' from collections import Counter import statistics as stats from Hash import * def testHash(radix, modulus, fName): print() print("Using radix " + str(radix) + " and modulus " + str(modulus) + ".") print() print(" Input | hash value") print("----------------------") file = open(fName) for line in file: for word in line.strip().split(' '): if (word != ''): print('{0:10s} {1:8d}'.format(word, hash(word, radix, modulus))) print() def count_hash(radix, modulus, fName): print() print("Using radix " + str(radix) + " and modulus " + str(modulus) + ".") print() print("Hash value | Occurences") print("-----------------------") hashes = [] with open(fName) as file: for line in file: for word in line.strip().split(' '): if (word != ''): hashes.append(hash(word, radix, modulus)) # print('{0:10s} {1:8d}'.format(word, hash(word, radix, modulus))) print() count = Counter(hashes) f = open("../Data files/results.dat", 'w') for val, cnt in count.items(): f.write('{0:8d} {1:8d}\n'.format(val, cnt)) print('{0:8d} {1:8d}'.format(val, cnt)) # print(get_avg_collision(count)) stats = print_stats(count.values()) f.close() return stats def run_man_test(how): while True: inp = input("Enter the radix, modulus, and file: ") r, m, f = inp.split(',') if(how == "test"): testHash(int(r), int(m), f.lstrip()) elif(how == "count"): count_hash(int(r), int(m), f.lstrip()) def run_auto_test(how): files = ["5lw-s.dat", "5lw-m.dat", "5lw.dat", "wordList"] radices = [128] moduli = [32, 127, 97] print("Starting auto test with the following values:\n") print("Files: " + str(files)) print("Radices: " + str(radices)) print("Moduli: " + str(moduli)) for radix in radices: for mod in moduli: for file in files: file = "../Data files/" + file if(how == "test"): testHash(radix, mod, file) elif(how == "count"): count_hash(radix, mod, file) input() def find_best_prime(): file = "../Data files/5lw.dat" primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,] for rdx in primes: for mod in primes: sts = count_hash(rdx, mod, file) if sts[0] < 50 and sts[0] > 25: print('radix: {0:8d}, modulus: {1:8d} => {2:f}' .format(rdx, mod, sts[0])) input() print('radix: {0:8d}, modulus: {1:8d} => {2:}' .format(rdx, mod, sts)) def print_stats(list): mean = stats.mean(list) stdev = stats.stdev(list) var = stats.variance(list) print('Mean : {0:f}'.format(mean)) print('StDev: {0:f}'.format(stdev)) print('Var : {0:f}'.format(var)) return (mean, stdev, var) def get_avg_collision(count): sum = 0 # print('values: {0:s}'.format(str(count.values()))) for val, cnt in count.items(): print(cnt) sum += cnt return sum / len(count) if __name__ == "__main__": while True: print("Enter one of the following options to begin:") print("1. Run the auto test for hash") print("2. Run the auto count for hash") print("3. Run the manual test for hash") print("4. Run the manual count for hash") inp = int(input()) if inp == 1: run_auto_test("test") elif inp == 2: run_auto_test("count") elif inp == 3: run_man_test("test") elif inp == 4: run_man_test("count") elif inp == 5: find_best_prime() else: print("Please enter a valid option!")
### 汉诺塔问题 # def hannoi(n,from_tower,mid_tower,to_tower): # if n==1: # print('Move {} to {}'.format(from_tower,to_tower)) # else: # hannoi(n-1,from_tower,to_tower,mid_tower) # print('Move {} to {}'.format(from_tower,to_tower)) # hannoi(n-1,mid_tower,from_tower,to_tower) # # try : # n = int(input("please input a integer :")) # print ("移动步骤如下: ") # hannoi(n, 'A', 'B', 'C') # except ValueError: # print ("please input a integer n(n > 0)!") import numpy as np def fab(n,ser): if n==1 or n==2: return 1 elif n<=len(ser): return ser[n-1] else: f=fab(n-1,ser)+fab(n-2,ser) ser.append(f) return f print(fab(i,[1,1]))
""" Global function is used when we want to make the variable outside the function to behave as global variable which is declared inside function.It can also change the value of global variable. Global keyword is used when we want global variable which is present inside the function.(function body) Date-2nd Nov 2020 """ #normal way b=10 def f(): b=9 print("IN ",b) f() print("OUT ",b) print() #global keyword a=10 def func(): global a a=9 print("IN ",a)#9 #a=8 func() print("OUT ",a)#9 print() #global function c=7 def ff(): c=9 #when we are writing c here,it is accessing the c varibale which is outside the function that is 7. x=globals()['c'] print("IN ",c)#9 #we can also change the global variable inside the function. globals()['c']=12 ff() print("OUT ",c) #12
""" Class is a blue print(design) of an object(thing). To define attributes(variables),we need __init__method. To define behaviours,we need methods(function). Date-10th Nov 2020 """ class Computer: def __init__(self,a,b): self.a=3 self.b=b def config(self): print("config is",self.a,self.b) com1=Computer("lenovo","32") com1.a=4 com2=Computer("dell","16") com1.config() #Computer.config(com1) com2.config() #Computer.config(com2) if com1.a==com2.a: print("same") else: print("different")
""" 4 types of argument-1.Position 2.Default 3.Keyword 4.Varibale length 5.Keyword variable length Date-1st Nov 2020 """ #position def sum(a,b): return a+b print(sum(5,6))#11 #default def info(name,age=16): print(name,age)#Yash 16 info("Yash") #or info("yash",age=20) #Keyword def infor(name,age): age-=2 print(name,age) infor(age=5,name="R")#R 3 #variable length def summ(a,*b): sum=a for i in b: sum+=i print(sum) summ(2,3,4,5,6,7)#27 #or def addition(*b): print(b)#(2, 3, 4, 5),returns a tuple sum=0 for i in b: sum+=i print(sum) addition(2,3,4,5) #14 #keyword variable length def person(name,**data): print(name)#xxx print(data)#{'age': 15, 'home': 'Delhi', 'mob': 37898},returns a dictionary for i in data: print(i,data[i]) person("xxx",age=15,home="Delhi",mob=37898)#age 15 #home Delhi #mob 37898
# A turtle draws a fractal that is a circle with squares # derived from Programming Foundations with Python on Udacity.com import turtle import webbrowser def draw_square(some_turtle): for i in range(0, 4): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(3) webbrowser.open("https://www.youtube.com/watch?v=xoHECVnQC7A&list=PLOwGIqWnQ8XLazEMg6_hZmpl87lXnukXm&index=4") for i in range(0, 36): draw_square(brad) brad.right(10) #angie = turtle.Turtle() #angie.shape("arrow") #angie.color("blue") #angie.circle(100) window.exitonclick() draw_art()
def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y): return x/y if __name__== "__main__": print(add(1,2)) print(sub(400, 1000)) print(mul(100, 2300)) print(div(8,2))
mydict = { } mydict['홍길동'] = '010-111-1111' mydict['이순신'] = '010-222-2222' print(mydict) del mydict['이순신'] print(mydict) #딕셔너리에 포함된 값들은 keys, values, items 함수들을 사용하여 리스트의 형태로 얻을 수 있다.' mydict2 = {'kim':'111', 'park':'2222', 'lee':'3333'} for k in mydict2.keys() : v = mydict2[k] print("{0:10s} {1:10s}".format(k,v)) for item in mydict2.items() : print(item) print(item[0]) # key print(item[1]) # value
dictionary = { "name": "7D 건조 망고", "type": "당절임", "ingradient": ["망고", "설탕", "메타중아황산나트륨", "치자황색소"], "origin": "필리핀" } print("name: ", dictionary["name"]) print("type: ", dictionary["type"]) print("ingradient: ", dictionary["ingradient"]) print("origin: ", dictionary["origin"]) print() dictionary["name"] = "8D 건조 망고" print("name: ", dictionary["name"]) dictionary["price"] = 5000 print("After add new element: ", dictionary) key = input("> 접근하고자 하는 키: ") if key in dictionary: print(dictionary[key]) else: print("존재하지 않는 키에 접근하고 있습니다.") #get value = dictionary.get("name"); print("value: ", value) value = dictionary.get("존재하지 않는 키") print("value: ", value) # none if value == None: print("존재하지 않는 키에 접근했었습니다.") for key in dictionary: print(key, ":", dictionary[key]) #items example_dictionary = { "키A": "값A", "키B": "값B", "키C": "값C", } print("# items() function of dictionanry") print("items(): ", example_dictionary.items()) print() print("# combination of items() and iterate statement") for key, element in example_dictionary.items(): print("dictionary[{}] = {}".format(key, element))
# 리스트와 튜플의 차이점은 "자료가 변경될 수 있는가? " # 튜플은 한번 생성되면 그 항목들이 추가되거나 삭제될 수 없다. # 튜플은 리스트보다 빠른 사용속도를 지원 mylist = [10,20,30,40,50] mytuple = (10,20,30,40,50) print(mylist) print(mytuple) len(mytuple) 30 in mytuple mytuple[0] for x in mytuple : print(x) mylist2 = list(mytuple) mylist2.append(60) mylist2.remove(20) newtuple = tuple(mylist2) print(newtuple)
guess = input("Guess a number between 1 and 10: ") guess = int(guess) if guess == 5: print("Your guess was correct.") else: print("Your guess was incorrect")
#Que1-->Write a python script to create a databse of students named Students. import pymongo client=pymongo.MongoClient() database=client['Studentdb'] print("database created") collection=database['studenttbl'] print("table created") print() #Que2-->Take students name and marks(between 0-100) as input from user 10 times using loops. print('Enter Detail Of Student') for i in range (10): fn=input('enter the name:') mrk=int(input('enter the marks:')) #Que3-->Add these values in two columns named "Name" and "Marks" with the appropriate data type. for i in range(10): collection.insert_one({'Name':fn,'Mark':mrk}) print('VALUES INSERTED IN TABLE') #Que4-->Print the names of all the students who scored more than 80 marks. print('MARKS GREATER THAN 80') data=collection.find({'Mark':{"$gt" : 80}}) for document in data: print(document)