text
stringlengths
37
1.41M
''' ----------------------------- EJERCICIO N°4 Más sobre listas ----------------------------- Calcularemos la suma de todos los valores en la lista miLista ----------------------------- ''' # MÉTODO 1 miLista = [10, 1, 8, 3, 5] suma = 0 for i in range(len(miLista)): suma += miLista[i] print(suma) ''' # MÉTODO 2 miLista = [10, 1, 8, 3, 5] suma = 0 for i in miLista: suma += i print(suma) '''
from timeit import timeit from typing import * @timeit def part1(inputValues: List[List[str]]) -> int: return count_trees(inputValues, 1, 3) # Right 1, down 1. # Right 3, down 1. # Right 5, down 1. # Right 7, down 1. # Right 1, down 2. @timeit def part2(inputValues: List[List[str]]) -> int: return count_trees(inputValues, 1, 1) \ * count_trees(inputValues, 1, 3) \ * count_trees(inputValues, 1, 5) \ * count_trees(inputValues, 1, 7) \ * count_trees(inputValues, 2, 1) def count_trees(grid: List[List[str]], r: int, c: int) -> int: trees = 0 row, col = r, c while row < len(grid): if grid[row][col] == '#': trees += 1 row += r col = (col + c) % len(grid[0]) return trees def main(): inputValues = [] with open("day3input.txt", "r") as f: for line in f.readlines(): curr_line = [] for char in line: if char == "." or char == "#": curr_line.append(char) inputValues.append(curr_line) res = part1(inputValues) print(res) res = part2(inputValues) print(res) if __name__ == '__main__': main()
""" PROBLEM STATEMENT ----------------- link: https://www.hackerrank.com/challenges/pangrams """ import sys f = sys.stdin s = f.readline().strip() unique_chars = set() for char in s: unique_chars.add(char.lower()) for i in range(ord('a'), ord('z') + 1): if not chr(i) in unique_chars: print("not pangram") break else: print("pangram")
""" PROBLEM STATEMENT ------------------ Two kingdoms are at war. Kingdom 1 has N soldiers (numbered as 1 to N) and the war goes on for K days. Each day only one soldier from each kingdom fights. Kingdom 1 can select one soldier from soldier number Ni to Nj. Ni and Nj are provided to you for each day. Selection criteria: Each soldier has 2 parameters - A & B. A soldier is/are selected if A is max. If more than one soldier has A max then the soldier with min. B (of the shortlisted soldiers) is/are selected. If more than one soldier is still available, then the soldier with least index (of the shortlisted soldiers) is selected. Print the soldier number selected for each day of the war. Input: Line 1 contains number of soldiers of Kingdom1 => N Line 2 contains N space-separated values of A Line 3 contains N space-separated values of B Line 4 contains number of days fight goes on => K Next K lines contain space separated values of Ni and Nj Output: K lines contain soldier number selected for each day of the war. Sample Input: 10 2 5 3 7 9 2 9 8 7 15 5 2 1 8 3 1 2 9 0 5 3 1 5 3 8 4 10 Result: 5 7 10 """ import sys def find_all_max_val_indexes(li): ''' finds all occurances of max in given list ''' max_val_indexes = [0] for idx, val in enumerate(li[1:], start=1): if val > li[max_val_indexes[0]]: max_val_indexes = [idx] elif val == li[max_val_indexes[0]]: max_val_indexes.append(idx) return max_val_indexes def find_all_min_val_indexes_with_second_min(li): ''' finds all occurances of min, and index of second min in given list ''' min_val_indexes = [0] second_min_index = 1 for idx, val in enumerate(li[1:], start=1): if li[min_val_indexes[0]] < val < li[second_min_index]: second_min_index = idx elif li[second_min_index] < li[min_val_indexes[0]]: second_min_index = min_val_indexes[0] elif val < li[min_val_indexes[0]] < li[second_min_index]: second_min_index = min_val_indexes[0] if val < li[min_val_indexes[0]]: min_val_indexes = [idx] elif val == li[min_val_indexes[0]]: min_val_indexes.append(idx) return min_val_indexes, second_min_index if __name__ == '__main__': f = sys.stdin N = int(f.readline().strip()) A = map(int, f.readline().strip().split(' ')) B = map(int, f.readline().strip().split(' ')) K = int(f.readline().strip()) for val in xrange(K): ninj = map(int, f.readline().strip().split(' ')) max_indexes = find_all_max_val_indexes(A[ninj[0]-1:ninj[1]]) if len(max_indexes)>1: min_indexes, second_min_index = find_all_min_val_indexes_with_second_min(B[ninj[0] - 1:ninj[1]]) if len(min_indexes)>1: print second_min_index + ninj[0] else: print min_indexes[0] + ninj[0] else: print max_indexes[0] + ninj[0]
height = float(input("please enter your height in meters \n")) weight = float(input("please enter your weight in kg's \n")) bmi = weight / (height ** 2) bmi =round(bmi,2) print("your bmi is " + str(bmi)) if(bmi<=18.5): print("You are underweight") elif(bmi<=25): print("you have a norml weight") elif(bmi<30): print("you are over weight") elif(bmi<35): print("you are obese") else: print("you are clinically obese")
import random def hard(random_number,attempt): while attempt!=0: user_input = int(input("please guess any input you think ")) if(user_input==random_number): print("CONGRATULATION ! you have find the correct number🥳") return elif(random_number>user_input): print("please take another input with larger number😄") attempt=attempt-1 print(f"you have only {attempt} attempts") elif(random_number<user_input): print("please choose a smaller number🧐") attempt=attempt-1 print(f"you have only {attempt} attempts") if attempt == 0: print("you have used you attempts to maximum🙄.Please try agin later🤐") print(f"actual number was {random_number}") def easy(random_number,attempt): while attempt!=0: user_input = int(input("please guess any input you think ")) if(user_input==random_number): print("CONGRATULATION ! you have find the correct number🥳") return elif(random_number>user_input): print("please take another input with larger number😄") attempt=attempt-1 print(f"you have only {attempt} attempts") elif(random_number<user_input): print("please choose a smaller number🧐") attempt=attempt-1 print(f"you have only {attempt} attempts") if attempt == 0: print("you have used you attempts to maximum🙄.Please try agin later🤐") print(f"actual number was {random_number}") print("welcome to the guess the number") random_number=random.randint(0,100) level = input("choose the level \n 1-hard level (only 5 attempts) \n 2-easy level(ony 10 attempts)\n ") if(level=="hard" or level == "1"): attempt = 5 print(f"You have choosen hard level you have only {attempt} attempts") hard(random_number,attempt) elif(level=="easy" or level == "2"): attempt = 10 print(f"You have choosen easy level you have only {attempt} attempts") easy(random_number,attempt)
# normal function # def greet(): # print("hello") # print("hello") # print("world") # greet() # user input function def greet_with_name(name): print(f"you name is {name}") print(f"how are you {name}") print(f"whats up {name}?") # greet_with_name("miku") greet_with_name(input("enter your name"))
def create_enemies(): i=3 enemies = ["alien","monsters","vampires"] if i >5: price =enemies[1] print(f"enemies are {enemies[0]}") print(price) # print(price)
# Keyword Method with iterrows() # {new_key:new_value for (index, row) in df.iterrows()} #TODO 1. Create a dictionary in this format: # {"A": "Alfa", "B": "Bravo"} #TODO 2. Create a list of the phonetic code words from a word that the user inputs. import pandas data = pandas.read_csv("E:\\python on udemy\\Day26\\nato_phonetic_alphabet.csv") # print(data) data_letters = {row.letter:row.code for (index,row) in data.iterrows()} # print(data_letters) user_input = input("please enter your name :").upper() new_name=[data_letters[letters] for letters in user_input] print(new_name)
you = input("Please eneter your name here : \n") you = you.lower() pat = input("Please eneter your partner name here : \n") pat = pat.lower() name = you + pat print (name) t= name.count("t") r= name.count("r") u= name.count("u") e= name.count("e") true = t+ r+ u+ e l= name.count("l") o= name.count("o") v= name.count("v") e= name.count("e") love = l+o+v+e score = str(true) + str(love) print(score) print(type(score)) score = int(score) print(f"you total score is {score}") if(score<10 or score>90): print(f"your score is {score} and you go together like coke and mentos") elif(score<40 or score>50): print(f"your score is {score} and you are alright together") else: print("your score is " + str(score))
height = int(input("please enter your height in centimeter \n")) bill=0 age = int(input("please enter your age \n")) if(height>=120): print("you can have a rollar coster ride") if(age<12): print("your ticket price is $7") bill=7 elif(age<18): print("your ticket price is $10") bill=10 else: print("your ticket price is $15") bill=15 answer=input("do you want any photos press y / n") if(answer == "y"): bill=bill+5 print("you are charged $5 extra ") print(f"you total price is ${bill}") if(answer == "n"): print("ok") print(f"you total price is ${bill}") else: print("sorry you cant ride now")
input1=[15,27,12] def quick_sort(array): if len(array) <= 1: return array pivot = array[0] tail = array[1:] left_side=[i for i in tail if i >= pivot] right_side=[i for i in tail if i < pivot] return quick_sort(left_side)+[pivot]+quick_sort(right_side) print(quick_sort(input1))
""" This module has functions associated with analyzing the geometry of a molecule. It can be run as a script with an xyz file. """ import os import argparse import numpy def open_xyz(xyz_filename): """ This function opens xyz file, separates the coordinates and the symbols and recasts the coordinates as floats. """ xyz_filename = numpy.genfromtxt(fname=xyz_filename, skip_header=2, dtype='unicode') symbols = xyz_filename[:,0] coordinates = xyz_filename[:,1:] coordinates = coordinates.astype(numpy.float) return symbols, coordinates def calculate_distance(atom1_coord, atom2_coord): """ Calculates the distances between two points in 3D spcae. Inputs: Coordinates of two atoms Return: distance between the atoms """ x_distance = atom1_coord[0] - atom2_coord[0] y_distance = atom1_coord[1] - atom2_coord[1] z_distance = atom1_coord[2] - atom2_coord[2] atom_distance = numpy.sqrt(x_distance**2 + y_distance**2 + z_distance**2) return atom_distance def bond_check(distance, minimum_length =0, maximum_length=1.5): """ This function checks the atom distance and assigns as a bond if it falls within the minimum_length and maximum_length """ if distance > minimum_length and distance <= maximum_length: return True else: return False if __name__ == "__main__": parser = argparse.ArgumentParser(description='The script analyses a user given xyz file and outputs the length of the bond') parser.add_argument('xyz_file', help="The file path for xyz file") args = parser.parse_args() xyzfilename = args.xyz_file symbols, coords = open_xyz(xyzfilename) num_atoms = len(symbols) for num1 in range(0,num_atoms): for num2 in range(0,num_atoms): if num1<num2: atom_distance = calculate_distance(coords[num1], coords[num2]) if bond_check(atom_distance) is True: print(F'{symbols[num1]} to {symbols[num2]} : {atom_distance: .3f}')
def main(): while True: try: x = int(input('Enter a positive number:\n')) print(iter_fib(x)) break except ValueError: continue def rec_fib(x): """Recursive implementation of Fibonacci's algorithm.""" if x < 0: raise ValueError("Only positive integers allowed") if x == 0: return 0 elif x == 1: return 1 else: return rec_fib(x - 1) + rec_fib(x - 2) def iter_fib(x): """Iterative implementation of Fibonacci's algorithm.""" if x < 0: raise ValueError("Only positive integers allowed") f0, f1 = 0, 1 for _ in range(x): f0, f1 = f1, f0 + f1 return f0
name = input("What is your name? ") print(name) size_input = input("How big is your house is sqaure feet? ") squareFeet = int(size_input) squareMeters = squareFeet /10.8 print(f"The size of your house is {squareMeters:.2f} sq meters") ##The point .2f will format the syntax to two decimal places
#A first class function just means that functions can be passed as arguments to functions. def calculate(*values, operator): return operator(*values) def divide(dividend, divisor): if divisor != 0: return dividend / divisor else: return "You fool!" ##Passing the divide as the value of the function (its name and space in memory) divide is first class function result = calculate(20, 4, operator=divide) print(result) ##Get_friend_name is the finder, which will run on each element of the sequence (friends) and try to find the expected value (Bob Smith) def search(sequence, expected, finder): for elem in sequence: if finder(elem) == expected: return elem raise RuntimeError(f"Could not find an element with {expected}.") friends = [ {"name": "Rolf Smith", "age": 24}, {"name": "Adam Wool", "age": 30}, {"name": "Anne Pun", "age": 27}, ] def get_friend_name(friend): return friend["name"] print(search(friends, "Bob Smith", get_friend_name)) ##Could be done this way with a lambda function ##print(search(friends, "Bob Smith", lambda friend: friend["name"])) ##Or ##print(search(friends, "Rolf Smith", itemgetter("name")))
import functools user = {"username": "jose", "access_level": "admin"} ##This replaces line 20, now the get_admin_password is replaced by secure_function ##make_secure is the decarator while secure_function is just a function def make_secure(func): ##Keeps the name of the original function (get_admin_secure) @functools.wraps(func) def secure_function(): if user["access_level"] == "admin": return func() return secure_function @make_secure def get_admin_password(): return "1234" #!This line calls the make_secure function, which defines the secure function and returns the secure_function function. Then get_admin_password is set to secure_function. So in line 16 when get_admin_password is called, you actually call make_secure which returns get_admin_password through the key word func #!get_admin_password = make_secure(get_admin_password) print(get_admin_password()) print(get_admin_password.__name__)
friends = {"Bob", "Rolf", "Anne"} abroad = {"Bob", "Anne"} ##If building a one element set, put a comma after to show that it is not doing any math localFriends = friends.difference(abroad) ##This takes the elements of abroad and subtracts them from the friends elements localFriendsEXAMPLE = abroad.difference(friends) ##This takes the elements of friends out of the abroad elements and give the results, an empty list print(localFriends) print(localFriendsEXAMPLE) friends = localFriends.union(abroad) print(friends) both = friends.intersection(abroad) print(both)
users = [ (0, "Bob", "password"), (1, "Rolf", "bob123"), (2, "Jose", "longp4assword"), (3, "username", "1234"), ] usernameMapping = {user[1]: user for user in users} ##This gets the username for user[1] and associating that name with the whole user tuple for each user ##The user name becomes the keys and the values become all the user information print(usernameMapping["Bob"]) usernameInput = input("What is your Username? ") passwordInput = input("What is your Password? ") _, username, password = usernameMapping[usernameInput] if passwordInput == password: print("You are correct!") else: print("Go away!")
def max(x,y): if x > y: print(x) elif y > x: print(y) max(5,6)
#!/usr/bin/env python """ @author: camilla eldridge """ import sys input_file=sys.argv[1] output_file=sys.argv[2] fasta_file=open(input_file, 'r') fasta_lines=fasta_file.read().split('>')[0:] unique_sequences=open(output_file,'w') def remove_complete_duplicates(fasta_lines): outputlist=[] setofuniqsequence=set() for sequence in fasta_lines: if sequence not in setofuniqsequence: outputlist.append(sequence) setofuniqsequence.add(sequence) return outputlist result=remove_complete_duplicates(fasta_lines) unique_sequences.write('>'.join(result)) unique_sequences.close()
from scipy.integrate import simps import random import numpy as np import matplotlib.pyplot as plt def mysimps(y, x=None, dx=1, axis=-1): ''' Integrate y(x) using samples along the given axis and the composite Simpson's rule. This method needs at least 3 point, so if the number of point is 2, then it uses trapezoidal rule. Parameters ---------- y : array_like Array to be integrated. x : array_like, optional If given, the points at which `y` is sampled. See Also -------- quad: adaptive quadrature using QUADPACK romberg: adaptive Romberg quadrature quadrature: adaptive Gaussian quadrature fixed_quad: fixed-order Gaussian quadrature dblquad: double integrals tplquad: triple integrals romb: integrators for sampled data cumtrapz: cumulative integration for sampled data ode: ODE integrators odeint: ODE integrators Examples -------- >>> from scipy import integrate >>> x = np.arange(0, 10) >>> y = np.arange(0, 10) >>> integrate.simps(y, x) 40.5 >>> y = np.power(x, 3) >>> integrate.simps(y, x) 1640.25 ''' n = len(y) count = 0 for i in range(2, n): if abs((x[i-2] - x[i-1]) - (x[i-1] - x[i])) < 1e-8: count = count + 1 if x is not None: if count != n-2: flag = 0 else: flag = 1 if x is not None and count != n-2: if len(x) != len(y): raise ValueError("len (x) must be the same as len (y)") if n <= 1: result = 0 elif n == 2: result = 0.5*(x[1] - x[0])*(y[0] + y[1]) elif (n-1) % 2 == 0: result = 0 for i in range(0, len(y) - 2, 2): d10 = x[i+1] - x[i] d21 = x[i+2] - x[i+1] d20 = d21 + d10 slope10 = (y[i+1] - y[i])/d10 slope21 = (y[i+2] - y[i+1])/d21 braket210 = (slope21 - slope10)/d20 result += (y[i]*d20 + (d20*d20*slope10/2) + 0.5*braket210*(d20*d21*d21 - d21**3/3 - d10**3/3)) elif (n-1) % 3 == 0: result = 0 for i in range(0, len(y) - 3, 3): d10 = x[i+1] - x[i] d21 = x[i+2] - x[i+1] d32 = x[i+3] - x[i+2] d20 = d21 + d10 d31 = d32 + d21 d30 = d32 + d21 + d10 slope10 = (y[i+1] - y[i])/d10 slope21 = (y[i+2] - y[i+1])/d21 slope32 = (y[i+3] - y[i+2])/d32 braket210 = (slope21 - slope10)/d20 braket321 = (slope32 - slope21)/d31 braket3210 = (braket321 - braket210)/d30 result += (y[i]*d30 + (d30*d30*slope10/2) + 0.5*braket210*(d30*d31*d31 - d31**3/3 - d10**3/3) + 0.5*braket3210*(d30*d31*d32*d32 - d31*d32*d32*d32/3 + d10*d20*d20*d20/3) + d32**4/12 - d20**4/12) else: result = 0 for i in range(0, len(y) - 4, 2): d10 = x[i+1] - x[i] d21 = x[i+2] - x[i+1] d20 = d21 + d10 slope10 = (y[i+1] - y[i])/d10 slope21 = (y[i+2] - y[i+1])/d21 braket210 = (slope21 - slope10)/d20 result += (y[i]*d20 + (d20*d20*slope10/2) + 0.5*braket210*(d20*d21*d21 - d21**3/3 - d10**3/3)) d10 = x[n-3] - x[n-4] d21 = x[n-2] - x[n-3] d32 = x[n-1] - x[n-2] d20 = d21 + d10 d31 = d32 + d21 d30 = d32 + d21 + d10 slope10 = (y[n-3] - y[n-4])/d10 slope21 = (y[n-2] - y[n-3])/d21 slope32 = (y[n-1] - y[n-2])/d32 braket210 = (slope21 - slope10)/d20 braket321 = (slope32 - slope21)/d31 braket3210 = (braket321 - braket210)/d30 result += (y[n-4]*d30 + (d30*d30*slope10/2) + 0.5*braket210*(d30*d31*d31 - d31**3/3 - d10**3/3) + 0.5*braket3210*(d30*d31*d32*d32 - d31*d32*d32*d32/3 + d10*d20*d20*d20/3) + d32**4/12 - d20**4/12) return result else: h = x[1] - x[0] y1 = 0 y2 = 0 if n <= 1: result = 0 elif n == 2: result = 0.5*h*(y[0]+y[1]) elif (n-1) % 2 == 0: for i in range(1, len(y) - 1): if i % 2 == 0: y1 = y1 + y[i] else: y2 = y2 + y[i] result = h*(y[0]+2*y1+4*y2+y[n-1])/3 elif (n-1) % 3 == 0: for i in range(1, len(y) - 1): if i % 3 == 0: y1 = y1 + y[i] else: y2 = y2 + y[i] result = 3*h*(y[0]+2*y1+3*y2+y[n-1])/8 else: for i in range(1, len(y) - 4): if(i % 2 == 0): y1 = y1 + y[i] else: y2 = y2 + y[i] result = (h*(y[0] + 2*y1 + 4*y2 + y[n-4])/3 + 3*h*(y[n-4] + 3*y[n-3] + 3*y[n-2] + y[n-1])/8) return result # slice non-equally for j in range(1, 70): x = [] y = [] x.append(0) for i in range(0, j): x.append(random.uniform(0, 4)) x.append(4) x = sorted(x) for i in range(0, len(x)): y.append(x[i]**3) print("%d %.6f %.6f" % (len(x), simps(y, x), mysimps(y, x))) ''' # slice equally for j in range(3, 270): x = [] y = [] x = np.linspace(0,4,j) for i in range(0, len(x)): y.append(x[i]**3) print("%d %.6f %.6f" % (len(x), simps(y, x), mysimps(y, x))) ''' #plt.plot(x, y)
student_score = list() i = 1 print('請依序輸入五個人的成績') while i < 6: score = int(input('請輸入成績')) student_score.append(score) i = i + 1 print('所有輸入的成績',student_score) print('平均分數是:', sum(student_score)/len(student_score)) print('最高分數是:', max (student_score)) print('最低分數是:', min (student_score))
#!/usr/bin/env python3 # Created by: Teddy Sannan # Created on: November 2019 # This program takes user input # and calculates the volume of a pyramid def volume_caclculation(base, height): # This function uses the input to calculate and print the answer # process volume = base ** 2 * height / 3 # output print(str(base) + "^2 x " + str(height) + "/3 =", volume) def main(): # This function takes the input for the shape # helps ask again while True: # input baseEdge_as_string = input("Enter the base edge: ") height_as_string = input("Enter the height: ") print() try: # converst string to int baseEdge_as_int = int(baseEdge_as_string) height_as_int = int(height_as_string) # enters the volume_calculation function volume_caclculation(baseEdge_as_int, height_as_int) # prevents crashing from false input except ValueError: print("Invalid Input") print() continue # break out of loop else: break if __name__ == "__main__": main()
alphabet = "abcdefghijklmnopqrstuvwxyz" numbers = "1234567890" print ("Encryption tool") choice = input ("Encrypt, Decrypt or Quit: ") if choice.lower() == "encrypt": plaintext = input ('Enter Message: ') cipher = '' key = input ('Enter Key: ') key = int (key) for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c)-key)%(len(alphabet))] print ('Your encrypted message is: ' + cipher) choice = input ("Encrypt, Decrypt or Quit: ") if choice.lower() == "encrypt": plaintext = input ('Enter Message: ') cipher = '' key = input ('Enter Same Key: ') key = int (key) for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c)-key)%(len(alphabet))] print ('Your encrypted message is: ' + cipher) elif choice.lower() == "decrypt": key = input ('Enter Same Key: ') key = int (key) plaintext = input ('Enter Encrypted Message: ') cipher = '' for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c)+key)%(len(alphabet))] print ('Your decrypted message is: ' + cipher) elif choice.lower() == "quit": print ("Game Over") elif choice.lower() == "decrypt": key = input ('Enter Key: ') key = int (key) plaintext = input ('Enter Encrypted Message: ') cipher = '' for c in plaintext: if c in alphabet: cipher += alphabet [(alphabet.index(c)+key)%(len(alphabet))] print ('Your decrypted message is: ' + cipher) elif choice.lower() == "quit": print ("Game Over")
string1=input() string2=input() string2+=string2 if string1 in string2: print('Yes') else: print('No')
string1=input() string2=input() dic={} for i in string1: if i not in dic.keys(): dic[i]=1 else: dic[i]+=1 for j in string2: if j not in dic.keys(): print('Not permutation') else: dic[j]-=1 if max(dic.values())==0 and min(dic.values())==0: print('permutated') else: print('not permutation')
#coding=utf-8 import os import os.path import sys def test_movimiento_de_archivos(file_name, is_valid): '''Chequea que el archivo pasado por parámetro sea pasado al directorio correcto''' if is_valid.upper() == "TRUE": is_valid = True else: is_valid = False if is_valid: prefix = "procesados/procesadas/" else: prefix = "rechazados/" was_moved_to_correct_directory = os.path.isfile(prefix + file_name) was_moved_not_copied = not os.path.isfile("aceptados/" + file_name) if was_moved_not_copied: print "EXITO: el archivo {} ya no se encuentra en arribados".format(file_name) else: print "ERROR: el archivo {} todavía se encuentra en arribados".format(file_name) if was_moved_to_correct_directory: print "EXITO: el archivo {} fue movido al directorio correspondiente".format(file_name) else: print "ERROR: el archivo {} no fue movido al directorio correspondiente".format(file_name) test_movimiento_de_archivos(sys.argv[1], sys.argv[2])
import sqlite3 import pandas as pd conn = sqlite3.connect('buddymove_holidayiq.sqlite3') df = pd.read_csv('buddymove_holidayiq.csv') df.columns = df.columns.str.replace(" ", "_") curs = conn.cursor() curs.execute('DROP TABLE review;') df.to_sql('review', conn) q1 = 'SELECT COUNT(*) FROM review' rows = curs.execute(q1).fetchall() print(f'There are {rows[0][0]} rows in the review table') q2 = """ SELECT COUNT(User_Id) FROM review WHERE Nature >= 100 AND Shopping >= 100; """ result = curs.execute(q2).fetchall() print(f'There are {result[0][0]} users that have at least 100 Nature and 100 Shopping reviews')
print("Програма, яка визначає чи є натуральне число, парним або закінчується число на 5 що ввів користувач") num = int(input("Введіть ваше число = ")) if num == 0: print("Ваше число дорівнює нулю") elif num % 10 == 5: print("Ваше число закінчується на 5") elif num % 2 == 0: print("Ваше число парне") else: print("Ваше число не парне і не закінчується на 5")
import csv import pandas as pd def main(): class_list = { 'car' : '1', 'bus' : '2', 'van' : '3', 'others' : '4', } column_name = ['class_name','id'] classes = ['car','bus','van','others'] class_list = [] for (i,item) in enumerate(classes): value = (item, str(i + 1)) class_list.append(value) data = pd.DataFrame(class_list, columns=None) data.to_csv(('images/class_map.csv'), index=None, header=None) print('Successfully generated class_map.csv') main()
"""Animacion de la cola.""" class anCola(object): """docstring for anCola.""" def __init__(self, sup, us): """Intancia.""" super(anCola, self).__init__() posInicial = [10, 400] self.v = sup self.usuario = us self.cola = [] self.caja = crear_caja(4) self.velocidad = 1 self.movimientoCola = [[posInicial[:], 0] for _ in range(4)] self.entrando = [580, 400] def agregar_cola(self): """Agregar Usuario.""" if len(self.cola) < 1: self.cola.append([10, 400]) else: pos = [self.cola[-1][0] + 72, 400] self.cola.append(pos) def mover_Usuario(self): """MoverUsuario.""" for i in range(len(self.movimientoCola)): pos = self.movimientoCola[i][0] if self.movimientoCola[i][1]: self.movimientoCola[i][0] = self.atender_cliente(pos, i) if type(self.movimientoCola[i][0]) == int: self.movimientoCola[i][1] = 0 self.movimientoCola[i][0] = [10, 400] return 1 self.crear_Usuario(self.movimientoCola[i][0]) def entrando_cola(self): """Entrando la simulacion.""" if len(self.cola) > 1: u = self.cola[-1][0] else: u = 10 if self.entrando[0] > u: self.entrando[0] -= self.velocidad else: self.entrando = [580, 400] return 1 self.crear_Usuario(self.entrando) def atender_cliente(self, pos, ncaja): """Atender cliente.""" if pos[0] < self.caja[ncaja][0][0]: pos[0] += self.velocidad if pos[1] > self.caja[ncaja][0][1]: pos[1] -= self.velocidad if pos == self.caja[ncaja][0]: return 1 return pos def mostrar_cola(self): """Prueba de cola.""" for pos in self.cola: self.crear_Usuario(pos) def crear_Usuario(self, pos): """Entra un usuario.""" self.v.blit(self.usuario, pos) def sacar_cola(self): """Eliminar uno de la cola.""" self.cola.pop() def crear_cola(ncola): """Crear cola.""" primer = [10, 400] listpos = [primer] for i in range(1, ncola): pos = [listpos[i - 1][0] + 72, 400] listpos.append(pos) return listpos def crear_caja(ncola): """Crear caja.""" primer = [[136, 70], 1] listpos = [primer] for i in range(1, ncola): pos = [[listpos[i - 1][0][0] + 150, 70], 1] listpos.append(pos) return listpos
class BestCourse: # this is a class website = 'www.cleverprogrammer.com' # tied directly to a class (not to any object) def __init__(self,name): self.name = name python = BestCourse('Learn Python Programming') math = BestCourse('Learn Basic Mathematics') # python and math are both an object print(python.name) # printing object's variable print(BestCourse.website) # printing class' variable print(math.name) # printing object's variable print(BestCourse.website) # printing class' variable
import io import re fname=input("enter filename:") f=open(fname) line=f.readline() #print(line) while line != "": y = line[::-1] print(y) line= f.readline()
""" Exercício 03 Preencha uma lista com 5 nomes de pessoas, informados pelo usuário. a) Criar uma função que recebe como parâmetro de entrada a lista e uma posição (índice) dessa lista e retorna o nome que está nessa posição. - Essa função deve gerar e tratar uma exceção do tipo IndexError caso o índice não exista na lista. """ def pessoaDoIndice(listaDePessoa, indice): try: total = len(listaDePessoa) - 1 i = 0 while i <= total: if i == indice: print(listaDePessoa[i]) i += 1 if indice > total: raise IndexError except IndexError: print("Não existe o índice") pessoaDoIndice(["matheus", "marcello", "maria", "Grey", "isis"], 2)
''' 简单要求: 自己写一个加密程序,能够加密的内容是英文和汉字。同时加密并且解密 就是说,一段话中既有中文又有英文,标点符号不用处理。 加密规则,获取ascii码数字,中间用|分割 # 思路提示: print(ord("我")) print(chr(25105)) 扩展内容:自定义规则玩起来 规则: 加密:先将字符转化为ASCII码对应的十进制数,再针对不同的字符按照各个不同的公式的转化为不同的数据,加上类型进行存储 解密:根据不同类型及公式,进行反向转化 不足: 1、转化公式比较随机,没什么逻辑,其他人看可能不太好理解,但这就不是优势嘛 2、注释写得有点乱 ''' # 加密过程 def encrypt_string(message): encode_result = "" for char in message: char_int = ord(char) if char.isalpha(): # 判断是否为字母 if 64 < char_int < 78 or 96 < char_int < 110: # 针对其中的部分字母进行加密 encode_result += "00" + str((char_int + 13) * 2) + "|" else: # 对剩下字母进行加密 encode_result += "01" + str(char_int - 23) + "|" elif '\u4e00' <= char <= '\u9fff': # 单个汉字可以这么判断 encode_result += "02" + str(char_int + 24) + "|" else: # 对数字、特殊字符进行加密 encode_result += "03" + str(char_int) + "|" print("Encode result: {}".format(encode_result)) return encode_result # 解密过程 def decrypt_string(message): decode_result = "" # 将message转换为list message_list = message.split("|") message_list.remove("") # 移除list中的空元素 for i in message_list: type_ = i[:2] char_number = int(i[2:]) if type_ == "00": char_number = int(char_number / 2 - 13) elif type_ == "01": char_number = char_number + 23 elif type_ == "02": char_number = char_number - 24 else: char_number = char_number decode_result += chr(char_number) print("Decode result: {}".format(decode_result)) if __name__ == '__main__': # 输入要加密的字符 message = input("Please input your message>>>>") print("Input message: {}".format(message)) # 加密 mes = encrypt_string(message) # 解密 decrypt_string(mes)
import math import os import random import re import sys # Complete the staircase function below. def staircase(n): for i in range(0,n): p=n-i-1 g=i+1 if p!=0: p=n-i-2 print " "*p, else: pass print "#"*g, print "\n", if __name__ == '__main__': n = int(raw_input()) staircase(n)
class Solution: def searchMatrix(self, matrix, target): #edge case if len(matrix)==0: return False m=len(matrix) n=len(matrix[0]) i=0 j=n-1 #traversing through array while i<m and j>=0: #condition where target is found if matrix[i][j]==target: return True #condition for column change elif matrix[i][j]>target: j-=1; else: i+=1 return False #Time-Complexity: O(m+n) #Space-Complexity:O(1)
# 坐标 class Coordinate(object): """docstring for Coordition""" def __init__(self, arg): super(Coordition, self).__init__() self.arg = arg # 点 class Point(object): """docstring for Point""" def __init__(self, arg): super(Point, self).__init__() self.arg = arg # 线 class Line(object): """docstring for Line""" def __init__(self, arg): super(Line, self).__init__() self.arg = arg # 面 class Plane(object): """docstring for Plane""" def __init__(self, arg): super(Plane, self).__init__() self.arg = arg # 体
# 核酸 # 脱氧核糖核酸类 DNA class DeoxyribonucleicAcid(object): """docstring for DeoxyribonucleicAcid""" def __init__(self, name): super(DeoxyribonucleicAcid, self).__init__() self.name = name # 核糖核酸类 RNA class RibonucleicAcid(object): """docstring for RibonucleicAcid""" def __init__(self, name): super(RibonucleicAcid, self).__init__() self.name = name # 基因类 class Gene(object): """docstring for Gene""" def __init__(self, name): super(Gene, self).__init__() self.name = name
# Project 1 # Step 5 # Numerical Simulation Model # Model.py # # Jessica Nordlund # Faith Seely # ################################## # IMPORT STATEMENTS ################################## import numpy as np import matplotlib.pyplot as plt import math import time # GLOBAL VARIABLES ################################## GRAVITY = -386.09 #inches/ses/sec INIT_VEL = 0 INIT_POS = math.pi/4 TIME = 2 #seconds # CUSTOM FUNCTION DEFINITIONS ################################### # function: getInitAcc # purpose: finds initial accelertaion given the length of the pendulum # paramter: length of pendulum (float) # return: float (initial acceleration) def getInitAcc(length): return (GRAVITY/length)*math.sin(INIT_POS) # function: newTime # purpose: adds a new time in seconds to the given array and returns new # paramter: numpy array of times # return: modified numpy array of times def newTime(times): return np.append(times, time.time()) # function: newVel # purpose: finds a new angular velocity given an old angular acceleration # paramter: 3 numpy arrays of velocities, accelerations, and times # return: numpy array of velocities with calculated velocity added def newVel(accs, vels, times): # old w + acc*t time_elapsed = times[len(times)-1] - times[len(times)-2] new_vel = vels[len(vels)-1] + (accs[len(accs)-1] * time_elapsed) return np.append(vels,new_vel) # function: newPos # purpose: finds a new angular position given an old angular velocity # paramter: 3 numpy array of velocities, positions, and times and length of # pendulum # return: numpy array of positions with calculated position added def newPos(vels, pos, times, length): # old pos + old vel*t + (1/2)(g/L sin (old theta) t^2), t = time step time_elapsed = times[len(times)-1] - times[len(times)-2] term1 = vels[len(vels)-1] term2 = (1/2)*(GRAVITY/length)*(math.sin(pos[len(pos)-1])) new_pos = pos[len(pos)-1] + term1*time_elapsed + term2*(time_elapsed**2) return np.append(pos,new_pos) # function: newAcc # purpose: finds a new angular acceleration given an old angular position # paramter: numpy array of positions and a numpy array of accelerations and # the length of the pendulum # return: numpy array of accelerations with calculated acceleration added def newAcc(pos, accs, times, length): # G/L SIN THETA new_acc = (GRAVITY/length) * math.sin(pos[len(pos)-1]) return np.append(accs,new_acc) # function: normalizeTimes # purpose: takes the times numpy array and scales it to start at 0 # paramter: numpy array of times # return: modified numpy array of times def normalizeTimes(times): np_len = len(times) result = [0] temp = times[0] for i in range(1,np_len-1): new_t = (times[i] - temp) + result[i-1] temp = times[i] result = np.append(result,new_t) return result # function: graphValues # purpose: graphs angular accelertaion, velocity , and position over time # paramter: 4 numpy array of accelerations, velocities, positions, and times # return: void def graphValues(accs, vels, pos, times): plt.subplot(211) plt.plot(times, accs, "b") plt.xlabel("Time (s)") plt.ylabel("Angular Accleration (radians/s^2)") plt.title("Pendulum Acceleration vs Time") plt.show() plt.subplot(212) plt.plot(times, vels, "r") plt.xlabel("Time (s)") plt.ylabel("Angular Velocity (radians/sec)") plt.title("Pendulum Velocity vs Time") plt.show() plt.plot(times, pos, "g") plt.xlabel("Time (s)") plt.ylabel("Angular Position (radians)") plt.title("Pendulum Position vs Time") plt.show() # function: calcPeriod # purpose: finds the period of the pendulum # paramter: numpy array of angles and numpy array of times # return: float (calculated period) def calcPeriod(angles, times): p_times = [] #just need one period (two data points since simulated) while (len(p_times) < 2): for i in range(1,len(angles)): #check conditional (anytime changes sign) if ((angles[i-1] > 0 and angles[i] < 0) or (angles[i-1] < 0 and angles[i] > 0)): p_times = np.append(p_times,times[i]) break #multiply by 2 to get full period return abs(p_times[1] - p_times[0])*2 # function: graphPvL # purpose: graphs period vs length of pendulums # paramter: numpy array of periods and corresponding lengths # return: void def graphPvL(periods, lengths): plt.plot(lengths, periods, "b") plt.ylabel("Period (s)") plt.xlabel("Length (inches)") plt.title("Pendulum Period vs Length") plt.show() # function: graphLog # purpose: takes an array of lengths and an array of periods of a pendulum # and graphs the logs of these arrays # paramter: numpy array of lengths of pendulum and numpy of periods # return: void def graphLog(lens, periods): plt.plot(lens, periods, "-bo") plt.xlabel("Length (inches)") plt.ylabel("Period (s)") plt.title("Pendulum Period vs Length (log scale)") plt.yscale('log') plt.xscale('log') plt.show() # MAIN SCRIPT ################################### periods = [] lengths = np.array([21.0, 17.0, 13.0, 9.0, 4.75]) for length in lengths: times = [time.time()] ang_v = [INIT_VEL] ang_x = [INIT_POS] ang_a = [getInitAcc(length)] elapsed_time = 0 while (elapsed_time < TIME): times = newTime(times) ang_v = newVel(ang_a,ang_v,times) ang_x = newPos(ang_v,ang_x,times,length) ang_a = newAcc(ang_x,ang_a,times,length) elapsed_time = time.time() - times[0] #scale time times = normalizeTimes(times) #make arrays the same shape times = times[:30000] ang_a = ang_a[:30000] ang_v = ang_v[:30000] ang_x = ang_x[:30000] print('****************************************') print() print('Data for pendulum of length ', length) graphValues(ang_a,ang_v,ang_x,times) period = calcPeriod(ang_x,times) print('Period: ', period, '(pendulum of length ', length,')') periods = np.append(periods,period) graphPvL(periods,lengths) graphLog(lengths, periods)
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] a = list(set(a)) b = list(set(b)) l = [] for i in a: if i in b: l.append(i) print(list(set(l)))
import numpy as np import matplotlib.pyplot as plt from basic_linear_model import LinearModel if __name__ == '__main__': x_train = [0.04, 0.08, 0.12] y_train = [0.2, 0.4, 0.6] W = 1.0 weight_list = [] mse_list = [] linear_model = LinearModel(x_train, y_train) for W in np.arange(0.01, 1.1, 0.01): print("Weight = \n", W) loss_sum = linear_model.predict(W) mse = loss_sum / 3 print("MSE: \n", mse) weight_list.append(W) mse_list.append(mse) plt.plot(weight_list, mse_list) plt.xlabel("weight") plt.ylabel("mse") plt.show()
# -*- coding: utf-8 -*- """ Parses csv files containing distances and scales and outputs JSON object file """ import pandas as pd import numpy as np def read_dist(filename): """ Reads distance from distance table produced by Arseny's script. return: list containing lists (i.e. dist[0][3]) """ f = open(filename, "r") dist_list = [] for line in f: split_line = line.split() dist_list.append(split_line) f.close() return dist_list def print_properties(dist, scale): """ Prints out descriptive informations about dist and scale data variables. return: Nothing """ print("Analytics on dist and scale data variables below.") print("scale.head()=\n", scale.head()) print("len(scale)=", len(scale)) print("scale.color.unique()=", scale.color.unique()) print("np.shape(dist)=", np.shape(dist)) return def get_group(char): """ Maps colors to arbitrary groups. """ if char == "W": return 1 elif char == "U": return 2 elif char == "B": return 3 elif char == "R": return 4 elif char == "G": return 5 elif char == "M": return 6 elif char == "0": return 7 else: return 8 def create_json(dist, scale, json_path, cutoff=0.8): """ Creates a .json file for graph visualization named json_path. """ num_cards = len(scale) #Write the first few lines. f = open(json_path, 'w') f.write('{\n') f.write(' "nodes": [\n') #Write the node data to file for card in range(num_cards): #Create nodes in json. str2write = ' {"id": "' + scale["name"][card] + '", "group": ' \ + str(get_group(scale["color"][card])) + '}' #Handle trailing commas. if card < num_cards-1: str2write+="," #Write to file. f.write(str2write + "\n") #Intermediate section. f.write(' ],\n') f.write(' "links": [\n') #Check each unique pair of points. list_link = [] for card1 in range(num_cards): for card2 in range(card1+1, num_cards): #Display only closely related cards. cur_dist = float(dist[card1][card2]) if cur_dist<=cutoff: list_link.append(' {"source": "' + scale["name"][card1] \ + '", "target": "' + scale["name"][card2] + '", "value": 1}') #Write link data to file with no trailing comma. num_link = len(list_link) for n in range(num_link-1): f.write(list_link[n] + ",\n") f.write(list_link[num_link-1] + "\n") #Write the last few lines. f.write(" ]\n") f.write("}\n") f.close() print("Created json file.") #Read in the relevant files. dist = read_dist("dist.csv") scale = pd.read_csv("scale.csv") #print_properties(dist, scale) create_json(dist, scale, "test.json")
income = int(input('enter your income ')) costs = int(input('enter your costs ')) pure = income - costs if income < costs: print(f'income lower than costs by {pure}') elif income > costs: print(f'your pure income equals {pure}') profitability = pure / income print(f'your profitability = {profitability:.2f}') incomePerEmployee = pure / int(input('enter number of employee ')) print(f'income per employee = {incomePerEmployee:.2f}') else: print('income equals costs')
with open('num3_file_L5.txt', 'r', encoding='utf-8') as file: average_salary = 0 names_salary = file.readlines() print('names whose salaries are less than 20 thousand:') for i in names_salary: average_salary += int(i.split()[1]) if int(i.split()[1]) < 20000: print(i.split()[0]) else: continue print(f'average salary = {average_salary / len(names_salary)}')
class Car: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def show_speed(self): return self.speed def go(self): print('start key') def stop(self): print('stop it now') def turn(self): print('turn!!!') class TownCar(Car): def show_speed(self): if self.speed > 60: print('over speed!') class WorkCar(Car): def show_speed(self): if self.speed > 40: print('over speed!') class PoliceCar(Car): def __init__(self, speed, color, name): super().__init__(speed, color, name) self.is_police = True class SportCar(Car): pass town = TownCar(120, 'white', 'bmw') print(town.color, town.speed, town.name, town.is_police) town.go() town.turn() town.stop() town.show_speed() police = PoliceCar(90, 'black', '911') print(police.color, police.speed, police.name, police.is_police) police.go() police.turn() police.stop() police.show_speed()
# 6. Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. # lastОбратите внимание, что создаваемый цикл не должен быть бесконечным. # Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. # Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено. from itertools import count from itertools import cycle start_num = int(input('please enter the initial value ')) last_num = int(input('enter the end value ')) for i in count(start_num): if i > last_num: break else: print(i) list_from_user = input('please enter your string ') counter = int(input('enter the number of times ')) tmp = 0 for n in cycle(list_from_user): if tmp > counter: break print(n) tmp += 1
#!/user/bin/env python # -*- coding: utf-8 -*- # @property 的使用 class Student(object): @property def score(self): return self.__score @score.setter def score(self, value): if(0 < value < 100): self.__score = value else : raise ValueError("score must between 0~100") lix = Student() lix.score = 90 # lix.score = 900 print lix.score
"""16 - Faça um algoritmo que leia os valores de COMPRIMENTO, LARGURA e ALTURA e apresente o valor do volume de uma caixa retangular. Utilize para o cálculo a fórmula VOLUME = COMPRIMENTO * LARGURA * ALTURA.""" def volume(comprimento, largura, altura): print('O volume é {:.2f}'.format(comprimento * largura * altura)) def valores(): print('Digite os valores:') while True: try: comprimento = float(input('Comprimento: ')) largura = float(input('Largura: ')) altura = float(input('Altura: ')) break except ValueError: print('Digite apenas valores!') volume(comprimento, largura, altura) valores()
"""5 - Ler um valor e escrever se é positivo ou negativo (considere o valor zero como positivo), se é par ou ímpar""" def par_ou_impar(numero): if numero % 2 == 0: print('Par!') else: print('Impar!') def positivo_ou_negativo(numero): if numero >= 0: print('Positivo!') else: print('Negativo!') while True: try: valor = int(input('Digite um número inteiro: ')) break except ValueError: print('Digite apenas números inteiros!') par_ou_impar(valor) positivo_ou_negativo(valor)
"""4 - Faça um programa que receba um valor que é o valor pago, um segundo valor que é o preço do produto e retorne o troco a ser dado. (modifique para receber um valor de desconto e subtraia do valor do produto)""" while True: try: valor_pago = float(input('Digite o valor pago: ')) if valor_pago > 0: break except ValueError: print('Não é um valor válido!') while True: try: valor_produto = float(input('Digite o valor do produto: ')) if valor_produto > 0: break except ValueError: print('Não é um valor válido!') while True: try: desconto = float(input('Digiter a % do desconto: ')) if desconto >= 0 and desconto <= 100: break except ValueError: print('Não é um valor válido!') valor_final = valor_produto - ((valor_produto / 100) * desconto) troco = valor_pago - valor_final if troco >= 0: print('Valor do produto: {:.2f}'.format(valor_produto)) print('Desconto {}%'.format(desconto)) print('Valor Final: R$ {:.2f}'.format(valor_final)) print('Troco: R$ {:.2f}'.format(troco)) else: print('Valor do produto: {:.2f}'.format(valor_produto)) print('Desconto {}%'.format(desconto)) print('Valor Final: R$ {:.2f}'.format(valor_final)) print('Faltam: R$ {:.2f}'.format(troco))
from Imovel import Imoveis class Menu: imovel = Imoveis() while True: print('----------------Imobiliária Tabajara----------------\n' '1 - Adicionar imóvel\n' '2 - Listar imóvel\n' '3 - Listar todos os imóveis\n' '4 - Alterar imóvel\n' '5 - Remover imóvel\n' '6 - Sair do sistema') opcao = input('Digite a opção desejada: ') if opcao == '1': imovel.novo_imovel() elif opcao == '2': imovel.listar_imovel() elif opcao == '3': imovel.listar_imoveis() elif opcao == '4': imovel.remover_imovel() imovel.novo_imovel() elif opcao == '5': imovel.remover_imovel() elif opcao == '6': exit() else: print('Opção inválida!')
"""6 - Faça um algoritmo que leia um nº inteiro e mostre uma mensagem indicando se este número é par ou ímpar, e se é positivo ou negativo""" def par_ou_impar(numero): if numero % 2 == 0: print('Par!') else: print('Impar!') def positivo_ou_negativo(numero): if numero >= 0: print('Positivo!') else: print('Negativo!') while True: try: valor = int(input('Digite um número inteiro: ')) break except ValueError: print('Digite apenas números inteiros!') par_ou_impar(valor) positivo_ou_negativo(valor)
def compare_strings(string1, string2): if not isinstance(string1, str) or not isinstance(string2, str): return 0 elif string1 == string2: return 1 elif len(string1) > len(string2): return 2 elif string2 == 'learn': return 3 cs = compare_strings('11231313','learn') print(cs)
# Make a class LatLon that can be passed parameters `lat` and `lon` to the # constructor # YOUR CODE HERE class LatLon: def __init__(self, lat, lon): self.lat = lat self.lon = lon # class Robot: # def __init__(self, name, color, weight): # constructor function syntax in python. We still need the "self" arg, # self.name = name # self.color = color # self.weight = weight # def introduce_self(self): # method of a class, we have to add self as an arg to methods # print("My name is " + self.name, self.color, self.weight) # like "this" in Java/Javascript # r1 = Robot() # default constructor to instantion a new object of a class # r1.name = "Tom" # this is how to set attributes for each object # r1.color = "red" #r1.weight = 30 # This is not an optimal way to set attributes, it's easy to make mistakes # r1 = Robot("Elijah", "Purple", 200) # r1.introduce_self() # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the # constructor. It should inherit from LatLon. Look up the `super` method. # YOUR CODE HERE class Waypoint(LatLon): def __init__(self, name, lat, lon): super().__init__(lat, lon) self.name = name # print(self) def __str__(self): return 'the location is {self.name} and the coordinates are {self.lat} by {self.lon}'.format(self = self) wp = Waypoint("Hello", 100, 200) print(wp.lat, wp.name, wp.lon) # Make a class Geocache that can be passed parameters `name`, `difficulty`, # `size`, `lat`, and `lon` to the constructor. What should it inherit from? class Geocache(Waypoint): def __init__(self, name, difficulty, size, lat, lon): super().__init__(lat, lon, name) self.difficulty = difficulty self.size = size def __str__(self): return 'the location is {self.name}, the size is {self.size} and the coordinates are {self.lat} by {self.lon}'.format(self = self) geocache = Geocache("Richard", "hard", 135, 1, 2409) # print(geo.lat, geo.lon, geo.name, geo.difficulty) # Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 # YOUR CODE HERE waypoint = Waypoint('Catacombs', 41.70505, -121.51521) # Without changing the following line, how can you make it print into something # more human-readable? Hint: Look up the `object.__str__` method print(waypoint) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 # YOUR CODE HERE geocache = Geocache(44.052137, 121.41556, "Newberry Views", 1.5, 2) # Print it--also make this print more nicely print(geocache) # example from Youtube # class Tweet: # the class is like a "factory" that provides default behavior # pass # most basic class # a = Tweet() # calling a class, a is known as an instance object (convention is to start with lowercase letters) # a.message = "140 characters" # one way of assigning attributes to a class. These stay and die with the instance # # print(Tweet.message) # this won't print anything, because we have not instantiated an instance object of this class yet # #print(a.message) # this will, because we've instantiated the instance object "a" # b = Tweet() # this is entirely different from a # b.message = "different message" # print(b.message) # redefining the Tweet class to include a dunder init method, aka a constructor method # class Tweet: # def __init__(self, message): # self.x = message # a = Tweet('something here') # #print(a) # "__init__() takes 0 positional arguments but 1 was given" error even though none was provided # # WHEN A CLASS IS CALLED, THE INSTANCE IS ALWAYS PASSED AS THE FIRST ARGUMENT # # Now that self is added, this will work # print(a.x) # b = Tweet("another instanct") # print(b.x)
def steps(array): if len(array) == 0: return 0 pivot = array[0] count = 0 lesser = [] greater = [] for element in array: count += 1 if element < pivot: lesser.append(element) elif element > pivot: greater.append(element) return count + steps(lesser) + steps(greater) a=list(map(int, input().split())) print(steps(a))
n=int(input()) a=[list(map(int, input().split())) for _ in range(n)] if any(a[i][0]!=a[i][1] for i in range(n)): print('rated') elif a==list(reversed(sorted(a))): print('maybe') else: print('unrated')
import RPi.GPIO as GPIO #Add the GPIO library to a Python sketch import time #Add the time library to a Python sketch def clearLED(): GPIO.output(8,GPIO.LOW) #Set LED pin 8 to LOW GPIO.output(10,GPIO. LOW) #Set LED pin 10 to LOW GPIO.output(12,GPIO. LOW) #Set LED pin 12 to LOW GPIO.output(16,GPIO. LOW) #Set LED pin 16 to LOW pin=[8,10,12,16] #Number of LED pin counter=0 GPIO.setmode(GPIO.BOARD) #Setup GPIO using Board numbering for i in range(0,4): GPIO.setup(pin[i], GPIO.OUT)#Setup pin 8,10,12,16 to output while True: clearLED() GPIO.output(pin[counter],GPIO.HIGH) #Set LED to HIGH time.sleep(1) #Delay 1 second counter=counter+1 if (counter>3): counter=0
# 890457906 # Alexander Sigler # Question 2 class Student: def __init__(self, firstname, lastname): self._firstName = firstname # Assign instance variable self._lastName = lastname # Assign instance variable self.compareKey = '_firstName' # Default value for compare def firstName(self): # Getter function for first name return self._firstName def lastName(self): # Getter function for last name return self._lastName def configCompKey(self, key): self.compareKey = key # Assign the comparison method def __ge__(self, other): if self.compareKey in self.__dict__: # If it exists as an attribute in dict, return it return self.__dict__.get(self.compareKey) >= other.__dict__.get(self.compareKey) else: # Not an attribute, but a property, so get it and call it as a function return getattr(self, self.compareKey)() >= getattr(other, self.compareKey)() def __str__(self): return 'First Name: <' + self._firstName + '> +++ Last Name: <' + self._lastName + '>' student = Student("Alexander", "Sigler") student2 = Student("Bob", "Adams") print('*** STARTING STUDENT COMPARISON OUTPUT ***') student.configCompKey('_firstName') print(student >= student2) # Should Assert False student.configCompKey('firstName') print(student >= student2) # Should Assert False student.configCompKey('_lastName') print(student >= student2) # Should Assert True student.configCompKey('lastName') print(student >= student2) # Should Assert True
import random def bubblesort(data): for index in range(len(data) - 1): swap = False for index2 in range (len(data) - index - 1): if data[index2] > data[index2 + 1]: data[index2], data[index2 + 1] = data[index2 + 1], data[index2] swap = True if swap == False: break data_list = random.sample(range(100), 50) print(data_list) bubblesort(data_list) print(data_list)
import tkinter import re import tkinter.messagebox Calculator=tkinter.Tk() Calculator.title("Calculator") #The size of the window Calculator.geometry("400x400+0+0") #Do not let the user to change the size of the page Calculator.resizable(False,False) '''Label''' #Add a entry to our window and set it to Read only #This give a way for user to change the text in the entry Var=tkinter.StringVar(Calculator,'') #Create the entry Entry=tkinter.Entry(Calculator,textvariable=Var) #Set the entry to Read only Entry['state']='readonly' #place our entry Entry.place(x=10, y=10, width=390, height=30)
print('Sample assignment') #定义一个 元组(不可变的,不可以编辑或更改元组,即不可修改元素的内容) shoplist=['apple','mango','carrot','banana'] #mylist 只是指向同一对象的另一种名称 mylist=shoplist del shoplist[0] print('shoplist is',shoplist) print('mylist is',mylist) #shoplist 和 mylist 输出了同样的结果,因此我们确认它们指向的是同一个对象 print('Copy by making a full slice') mylist=shoplist[:]#通过生成一份完整的切片制作一份列表的副本 del mylist[0]#删除mylist中的内容,不影响 shoplist的内容 print('shoplist is',shoplist) print('mylist is',mylist) #你要记住如果你希望创建一份诸如序列等复杂对象的副本(而非整数这种简单的对象(Object)), # 你必须使用切片操作来制作副本
def powersum(power,*args): ''' Return the sum of each raised to the specified power.''' total=0 for i in args: total+=pow(i,power) return total print(powersum(2,3,4))
#print 总是会以一个不可见的“新一行”字符( \n )结尾 age=20 name='kyle' print('{0} was {1} years old when he wrote this book'.format(name,age)) print('Why is {0} playing that python?'.format(name)) print('{} was {} years old when he wrote this book'.format(name,age)) print('Why is {} playing that python?'.format(name)) #对于浮点数 '0.333' 保留小数点(.) 后三位 print('{0:.3f}'.format(1.0/3)) #使用下划线填充文本,并保持文本处于中间位置 #使用(^) 定义 ’____hello____‘字符长度为11 print('{0:^11}'.format('hello')) print('{0:_^11}'.format('hello')) #基于关键词输出,’Swaroop wrote A Byte of Python‘ print('{name} wrote {book}'.format(name=name,book='A byte of python'))#’=‘前面的name 必须要有,类似于匿名参数 print('my name=', end='') print('kyle', end='') print(' Li') #转义 print('what\'s are name?')#单引号 print("what's your \\ name?")#双引号 print("Newlines are indicated by \n") print(r"Newlines are indicated by \n")#如果你需要指定一些未经过特殊处理的字符串,比如转义序列,那么你需要在字符串前增加 r 或 R 来指定一个 原始(Raw) 字符串 #一个物理行拆分成多个逻辑行 id= \ 5 print(id) i=5 print('Value is',i)
# 通过算法判断,打印1900到2100间(包括1900和2100)的所有闰年 years = range(1900, 2101, 1) def is_leap_year(year): ''' 判断一个年份是否为闰年 year 代表一个正确的年份 年份是4的倍数而不是100的倍数的年份是闰年 年份是400的倍数的年份是闰年。 ''' if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return False for year in years: if is_leap_year(year): print("the Year {} a Leap Year".format(year)) else: continue
# textentrydialog.py # Simple dialog for entering a string. # Note: Not based on wxPython's TextEntryDialog. from dialog import Dialog from textbox import TextBox from label import Label from keys import keys class TextEntryDialog(Dialog): def __init__(self, parent, title="Enter some text", prompt="Enter some text", default="", cancel_button=1): self.prompt = prompt self.default = default Dialog.__init__(self, parent, title, cancel_button=cancel_button) def Body(self): label = Label(self, self.prompt) self.AddComponent(label, expand='h', border=7) self.text = TextBox(self, size=(100,25), process_enter=1) self.text.SetValue(self.default) self.text.OnChar = self.OnTextBoxChar self.AddComponent(self.text, expand='h', border=5) def OnTextBoxChar(self, event=None): # pressing Enter in the TextBox is the same as clicking OK if event.GetKeyCode() == keys.enter: self.OnClickOKButton(event) else: event.Skip() def GetValue(self): return self.text.GetValue()
import pandas def read_csv(path, columns=None): df = pandas.read_csv(path, sep=";", usecols=columns) return df def sort_dates(sequence) -> dict: res = {} for (key, value) in sorted(sequence.items()): res[key] = value return res def filter_on_threshold(sequences, threshold) -> dict: res = {} for sequence in sequences.keys(): for date in sequences[sequence]: if abs(sequences[sequence][date]) > threshold: if sequence in res: res[sequence][date] = sequences[sequence][date] else: res[sequence] = {date: sequences[sequence][date]} return res def filter_description_on_threshold(sequences, threshold) -> dict: for sequence in sequences.keys(): for date in sequences[sequence]: if abs(sequences[sequence][date][0]) < threshold: sequences[sequence][date][1] = "" sequences[sequence][date][2] = "" return sequences def get_sequences(df, sequence_row_name, x_row_name, y_row_name) -> dict: sequences = {} for index, row in df.iterrows(): key = row[sequence_row_name] y_value = row[x_row_name] x_value= row[y_row_name] if key in sequences: sequences[key][x_value] = y_value else: sequences[key] = {x_value: y_value} return sequences
''' Created on 22 Mar 2018 @author: olaska ''' import pandas as pd import csv import json import requests #DataFrame is created from file get from url df=pd.read_json('url.someaddress') #this allow to change name columns from original file df.columns=['col_1','col_2','col_3','etc'] #DataFrame transformed into csv file csv=df.to_csv() #retrieve data(can be as json/csv file - depends on available API r = requests.get('url.someadress').json() #pandas retrieve json file from url json = pd.read_json('http://someadress') #creates csv file as a string csv = str(json.to_csv()) #splits string into numerous line representing rows csv = csv.split('\n') #loop for row in csv: print(type(row)) #row = row.split(',') #row = row[1:] #row = ','.join(row) #print(row) #csv = csv[1:] #glues again #csv = '\n'.join(csv) #it creates /writes into and close a csv file with open('someFile.csv', 'w') as f: f.write(csv)
bill = float(input("How much is the bill?")) service = input("How was the service: GOOD, FAIR, BAD?").upper() guests = int(input("How many people?")) goodtip = float(.20 * bill) fairtip = float(.15 * bill) badtip = float(.10 * bill) goodtotal = float(goodtip + bill) fairtotal = float(fairtip + bill) badtotal = float(badtip + bill) if service == "GOOD": print("tip:" , goodtip) print("grandtotal" , goodtotal) print("pay per guest" , (goodtotal / guests) if service == "FAIR": print("tip:" , fairtip) print("grandtotal:" , fairtotat) print("pay per guest" , (fairtotal / guests) if service == "BAD": print("tip:" , badtip) print("grandtotal:" , badtotal) print("amount per guests" , (badtotal / guests)
# user input for box size #number = 4 #for n in range(0,4): # print("*" * number) # user input border box #num1 = int(input("How big is the box?")) width = int(input('Width? ')) height = int(input('Height? ')) # draw the top border print('*' * width) print("*" * height)
dog_age = int(input("Input dog's age: ")) # Do not change this line begin_human_age = 15 if dog_age == 1: print("Human age: ", begin_human_age) if dog_age == 2: human_age=begin_human_age+9 print("Human age: ",human_age) if dog_age >= 3 and dog_age <= 16: human_age_2 = (begin_human_age)+((4*dog_age)+1) print("Human age: ",human_age_2) if dog_age < 1: print("Invalid age") if dog_age > 16: print("Invalid age")
quiz = (input("Input f|a|b (fibonacci, abundant or both): ")) if quiz == "f": length = int(input("Input the length of the sequence: ")) a = 0 b = 1 print("Fibonacci Sequence:") print("-------------------") print(a) print(b) for i in range (2,length): c = a + b a = b b = c print(c) elif quiz == "a": max_number = int(input("Input the max number to check: ")) print("Abundant numbers:") print("-----------------") sum = 0 max_number +=1 for i in range(1, max_number): for j in range(1, int(i)): if (i % j == 0): sum = sum + j if (sum > i): print( i) sum = 0 elif quiz == "b": length = int(input("Input the length of the sequence: ")) a = 0 b = 1 print("Fibonacci Sequence:") print("-------------------") print(a) print(b) for i in range (2,length): c = a + b a = b b = c print(c) max_number = int(input("Input the max number to check: ")) print("Abundant numbers: ") print("-----------------") sum = 0 max_number +=1 for i in range(1, max_number): for j in range(1, int(i)): if (i % j == 0): sum = sum + j if (sum > i): print( i) sum = 0
# # [1] Two Sum # # https://leetcode.com/problems/two-sum/description/ # # algorithms # Easy (38.94%) # Total Accepted: 1.1M # Total Submissions: 2.9M # Testcase Example: '[2,7,11,15]\n9' # # Given an array of integers, return indices of the two numbers such that they # add up to a specific target. # # You may assume that each input would have exactly one solution, and you may # not use the same element twice. # # Example: # # # Given nums = [2, 7, 11, 15], target = 9, # # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. # # # # # class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i, num in enumerate(nums): # Check if the current number is the missing number needed. if target - num in d: return [i, d[target - num]] # Otherwise, take note of the number and it's index. d[num] = i return None
def factorial(number): if not isinstance(number,int): raise TypeError("numara sayi değil") if not number >= 0: raise ValueError("sayi 0 dan küçük olmamalı") def inner_factorial(number): if number <= 1: return 1 return number * inner_factorial(number-1) return number * inner_factorial(number) print(factorial(4))
# -*- coding: utf-8 -*- ### first count all aa base number, then caculate average sequence number ### filein = open("psc_cluster_file_sorted/ortholog_sorted341.fasta", "r") dic, k, v = {}, '', [] for i in filein: if i.startswith('>'): dic[k] = v k = i[1:-1] v = [] else: v.append(i) dic[k] = v dic.pop('') print("sequences in total: %s" %len(dic)) a=len(dic) b=0 for (k, v) in dic.items(): print("SEQUENCE: %s\nLENGTH:%s" %(k, sum(map(len, v)))) b = b + int(sum(map(len,v))) average = int(b/a) print("average sequence number: %s" %average) filein.close()
import db class Recipe(object): recipeCnt = 0 def __init__(self,name,ingredients): self.Name = name.lower() self.Ingredients = ingredients Recipe.recipeCnt += 1 def display_count(self): print "Recipe Count: ", Recipe.recipeCnt def need_ingredients(self): print "SELF.IN: ",self.Ingredients missing = [] stock = dict() #contains key: (mfg,liquor,typ) value: amount #First: fill a dict with our stock that matches the liquor type for i in self.Ingredients: for item in db.check_inventory_for_type(i[0]): #returns mfg/liquor tuples with liquor == {ingredient name} #fetches from the inventory the amount db._c.execute("SELECT amount FROM inventory WHERE \ mfg = ? AND liquor = ?",(item[1],item[2])) amount = int(db._c.fetchone()[0]) if item in stock.keys(): #add to temp dictionary stock[(item[2],item[3])] += float(amount) else: stock[(item[2],item[3])] = float(amount) if len(stock) == 0: #no ingredients of that type(s) in db for i in self.Ingredients: amount = db.convert_to_ml(i[1]) missing.append((i[0],amount)) return missing #next: check to see if we have bottles with enough liquor for each ingredient in the recipe (to refrain from mixing bottles) for i in self.Ingredients: needed = db.convert_to_ml(i[1]) #print "\nWe need %s ml of %s" % (needed, i[0]) most = 0 #greatest amount per bottle, overwritable flag = False #False implies not enough liquor in any given bottle to satisfy the ingredient amount for item, amt in stock.items(): #print "looking for greatest amount: %s -- %s?" % (item, amt) print item[1], i[0] if str(item[1]) == str(i[0]): if amt >= needed: flag = True #print " greater than needed!" if amt > most: most = stock[item] #print " new greatest amount!" if flag == False: miss = i[0],(needed-most) missing.append(miss) if len(missing) != 0: return missing else: return False
#!/usr/bin/env python # coding: utf-8 # In[22]: H,W = input("縦の長さと横の長さを入力してください").split() H=int(H) W=int(W) if(3<= H <= 300 and 3<= W <= 300): for y in range(H): y+=1 x=0 for x in range (W): x+=1 if(y==1 or x==1 or y==H or x==W): print("#",end ="") else: print(". ",end ="") print() # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[8]: s=str(input()) p=str(input()) a=0 if(1<=len(p)<=len(s)<=100): a = set(s) & set(p) if(a!=0): print("Yes") else: print("No") # In[ ]:
# Create a list called instructors instructors = [] # Add the following strings to the instructors list # "Colt" # "Blue" # "Lisa" instructors.append("Colt") instructors.append("Blue") instructors.append("Lisa") # Remove the last value in the list instructors.pop() # Remove the first value in the list instructors.pop(0) # Add the string "Done" to the beginning of the list instructors.insert(0, "Done") # Run the tests to make sure you've done this correctly!
num = input("How many times do I have to tell you: ") phrase = "Clean your room!" if num: times = int(num) for x in range(times): print(phrase.upper())
''' kombucha_song = make_song(5, "kombucha") next(kombucha_song) # '5 bottles of kombucha on the wall.' next(kombucha_song) # '4 bottles of kombucha on the wall.' next(kombucha_song) # '3 bottles of kombucha on the wall.' next(kombucha_song) # '2 bottles of kombucha on the wall.' next(kombucha_song) # 'Only 1 bottle of kombucha left!' next(kombucha_song) # 'No more kombucha!' next(kombucha_song) # StopIteration default_song = make_song() next(default_song) # '99 bottles of soda on the wall.' ''' def make_song(num=99, beverage='soda'): msg = "" while num >= 0: if num == 0: msg = f'No more {beverage}!' elif num == 1: msg = f'Only 1 bottle of {beverage} left!' else: msg = f'{num} bottles of {beverage} on the wall.' yield msg num -= 1 song = make_song(5, "beer") print(next(song)) print(next(song)) print(next(song)) print(next(song)) print(next(song)) print(next(song)) print(next(song)) print(next(song))
# flesh out intersection pleaseeeee def intersection(list1, list2): return list(set(list1) & set(list2)) print(intersection([1, 2, 3], [2, 3, 4])) # [2, 3] print(intersection(['a', 'b', 'z'], ['x', 'y', 'z'])) # ['z']
''' Exercise Involving Closures Write a function called letter_counter which accepts a string and returns a function. When the inner function is invoked it should accept a parameter which is a letter, and the inner function should return the number of times that letter appears. This inner function should be case insensitive. counter = letter_counter('Amazing') counter('a') # 2 counter('m') # 1 counter2 = letter_counter('This Is Really Fun!') counter2('i') # 2 counter2('t') # 1 ''' def letter_counter(msg): letters = {x: msg.lower().count(x) for x in msg.lower()} def inner(cha): if cha.lower() in letters: return letters[cha.lower()] return 0 return inner counter = letter_counter('Amazing') print(counter('a')) # 2 print(counter('m')) # 1 counter2 = letter_counter('This Is Really Fun!') print(counter2('i')) # 2 print(counter2('t')) # 1
''' This is another trickier exercise. Don't feel bad if you get stuck or need to move on and come back later on! Write a function called mode. This function accepts a list of numbers and returns the most frequent number in the list of numbers. You can assume that the mode will be unique. mode([2,4,1,2,3,3,4,4,5,4,4,6,4,6,7,4]) # 4 ''' # define mode below: def mode(nums): freq = {num: nums.count(num) for num in nums} freq_max = max(freq.values()) temp = [k for k,v in freq.items() if v == freq_max] return temp[0] print(mode([2,4,1,2,3,3,4,4,5,4,4,6,4,6,7,4,8])) # 4
''' sevens = get_unlimited_multiples(7) [next(sevens) for i in range(15)] # [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105] ones = get_unlimited_multiples() [next(ones) for i in range(20)] # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ''' def get_unlimited_multiples(num=1): total = num while True: yield total total += num sevens = get_unlimited_multiples(7) print([next(sevens) for i in range(15)]) ones = get_unlimited_multiples() print([next(ones) for i in range(20)])
''' list_check([[],[1],[2,3], (1,2)]) # False list_check([1, True, [],[1],[2,3]]) # False list_check([[],[1],[2,3]]) # True ''' def list_check(input_list): for i in input_list: if type(i) != list: return False return True print(list_check([[],[1],[2,3], (1,2)])) # False print(list_check([1, True, [],[1],[2,3]])) # False print(list_check([[],[1],[2,3]])) # True
''' Write a function called min_max_key_in_dictionary which returns a list with the lowest key in the dictionary and the highest key in the dictionary. You can assume that the dictionary will have keys that are numbers. min_max_key_in_dictionary({2:'a', 7:'b', 1:'c',10:'d',4:'e'}) # [1,10] min_max_key_in_dictionary({1: "Elie", 4:"Matt", 2: "Tim"}) # [1,4] ''' def min_max_key_in_dictionary(dictionary): nums = set(dictionary.keys()) return [min(nums), max(nums)] print(min_max_key_in_dictionary({2:'a', 7:'b', 1:'c',10:'d',4:'e'})) # [1,10] print(min_max_key_in_dictionary({1: "Elie", 4:"Matt", 2: "Tim"})) # [1,4]
print("Hey, how's it going?") msg = "" while "you win" not in msg.lower(): msg = input() print(msg) print("HA HA, I Win!")
''' Write a function called truncate that will shorten a string to a specified length, and add "..." to the end. Given a string and a number n, truncate the string to a shorter string containing at most n characters. For example, truncate("long string", 5) should return a 5 character truncated version of "long string". If the string gets truncated, the truncated return string should have a "..." at the end. Because of this, the smallest number passed in as a second argument should be 3. truncate("Super cool", 2) # "Truncation must be at least 3 characters." truncate("Super cool", 1) # "Truncation must be at least 3 characters." truncate("Super cool", 0) # "Truncation must be at least 3 characters." truncate("Hello World", 6) # "Hel..." truncate("Problem solving is the best!", 10) # "Problem..." truncate("Another test", 12) # "Another t..." truncate("Woah", 4) # "W..." truncate("Woah", 3) # "..." truncate("Yo",100) # "Yo" truncate("Holy guacamole!", 152) # "Holy guacamole!" ''' def truncate(msg, trun): if trun < 3: return "Truncation must be at least 3 characters." elif trun <= len(msg): return msg[0: trun - 3] + "..." else: return msg print(truncate("Super cool", 2)) # "Truncation must be at least 3 characters." print(truncate("Super cool", 1)) # "Truncation must be at least 3 characters." print(truncate("Super cool", 0)) # "Truncation must be at least 3 characters." print(truncate("Hello World", 6)) # "Hel..." print(truncate("Problem solving is the best!", 10)) # "Problem..." print(truncate("Another test", 12)) # "Another t..." print(truncate("Woah", 4)) # "W..." print(truncate("Woah", 3)) # "..." print(truncate("Yo",100)) # "Yo" print(truncate("Holy guacamole!", 152)) # "Holy guacamole!"
''' SOLUTION: mode Mode Solution This is another trickier exercise. Don't feel bad if you were unable to complete it! I start by defining the function, which accepts a single argument we'll call collection . Next, I create a new dictionary that maps items in the collection to the number of times they appear in the collection. I used a dictionary comprehension along with count() to achieve this. count = {val: collection.count(val) for val in collection} If collection was the string "happy", the resulting count dict would look like this: ''' { 'h': 1, 'a': 1, 'p': 2, 'y': 1 } ''' Now, I just need to find the maximum number in all the values (2 in my example). To do that, I use max_value = max(count.values()) Now we know what the maximum value is, we just have to find the corresponding key. (we have 2, and need to work backwards to find 'p'). This is harder than you might think. I convert the values in the dict to a list. I do the same thing to all the keys. Then, I find the index of max_value in the values and use that to access the corresponding key. #find index of max_value in the values correct_index = list(count.values()).index(max_value) #use that index to find the correct key return list(count.keys())[correct_index] Here is the complete code: ''' def mode(collection): count = {val: collection.count(val) for val in collection} # find the highest value (the most frequent number) max_value = max(count.values()) # now we need to see at which index the highest value is at correct_index = list(count.values()).index(max_value) # finally, return the correct key for the correct index (we have to convert cou) return list(count.keys())[correct_index]
Quicksort_test.py import timeit def test1(array=["Xavier","Galarza","Henny"]): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x > pivot: greater.append(x) return test1(less) + equal + test1(greater) else: return array if __name__ == '__main__': print(timeit.timeit("test1()", setup="from __main__ import test1"))
# * Matching and Extracting Data # import re # x = 'My 2 favorite numbers are 19 and 42' # y = re.findall('[0-9]+', x) # print(y) # y = re.findall('[AEIOU]+', x) # print(y) # * Warning: Greedy MAtching # import re # x = 'From: Using the : character' # y = re.findall('^F.+:', x) # print(y) # * Non-Greddy Matching # import re # x = 'From: Using the : character' # y = re.findall('^F.+?:', x) # print(y) # * Fine-Tuning String Extraction import re x = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' y = re.findall('\\S+@\\S+', x) print(y) y = re.findall('^From (\\S+@\\S+)', x) print(y)
# * Counting Pattern # counts = dict() # print('Enter a line of text:') # line = input('') # words = line.split() # print('Words:', words) # print('Counting...') # for word in words: # counts[word] = counts.get(word, 0) + 1 # print('Counts', counts) # * Define Loops and Dictionaries # counts = {'chuck': 1, 'fred': 42, 'jan': 100} # for key in counts: # print(key, counts[key]) # * Retrieving list of Keys and Values # jjj = {'chuck': 1, 'fred': 42, 'jan': 100} # print(list(jjj)) # print(jjj.keys()) # print(jjj.values()) # print(jjj.items()) # * Bonus: Two Iteration Variables! jjj = {'chuck': 1, 'fred': 42, 'jan': 100} for aaa, bbb in jjj.items(): print(aaa, bbb)
# * Best Friends: Strings and Lists # abc = 'With three words' # stuff = abc.split() # print(stuff) # print(len(stuff)) # print(stuff[0]) # print(stuff) # for w in stuff: # print(w) # * Split # line = 'A lot of Spaces' # etc = line.split() # print(etc) # line = 'first;second;third' # thing = line.split() # print(thing) # print(len(thing)) # thing = line.split(";") # print(thing) # print(len(thing)) # * More Split # line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' # words = line.split() # print(words) # * The Double Split Pattern line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' words = line.split() email = words[1] print(email) pieces = email.split('@') print(pieces[1])
# * While loop n = 5 while n > 0: print(n) n = n - 1 print('Blastoff') print(n) # ! An Infinite Loop # n = 5 # while n > 0: # print('Lather') # print('Rinse') # print('Dry off') # * Breaking Out of a Loop # while True: # line = input('> ') # if line == 'done': # break # print(line) # print('Done!') # * Finishing an Iteration with continue while True: line = input('> ') if line[0] == '#': continue if line == 'done': break print(line) print('Done!')
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def select_task(conn, sql,params): """ Query tasks by priority :param conn: the Connection object :param priority: :return: """ cur = conn.cursor() cur.execute(sql, params) rows = cur.fetchall() return rows def create_task(conn, task): """ Create a new task :param conn: :param task: :return: """ sql = ''' INSERT INTO tasks(temp,hum,date) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, task) return cur.lastrowid database = "kiss.db" sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks ( id integer PRIMARY KEY, temp integer NOT NULL, hum integer NOT NULL, date text NOT NULL );""" # create a database connection conn = create_connection(database) # create tables if conn is not None: # create tasks table create_table(conn, sql_create_tasks_table) else: print("Error! cannot create the database connection.") print(create_task(conn, (15, 20, "2020-01-22 19:43:36"))) select_task(conn,"SELECT * FROM tasks WHERE date like ?",(date)) conn.commit()
#定义空字符串 s="" if s: print("s 不是空字符串") else: print("s 是空字符串") #定义空列表 my_list = [] if my_list: print("my_list 不是空列表") else: print("my_list 是空列表") #定义空字典 my_dict = {} if my_dict: print("my_dict 不是空字典") else: print("my_dict 是空字典") my_set = {} print(type(my_set))
#去除重复的字符串 s = input("输入n个字符串,用逗号分隔:") lists = list((s.split(","))) print(lists) newdict = {} for item in lists: newdict[item] = item klist = list(newdict.keys()) print(klist) #print(dict(lists))
def fn(a:int,b:bool,c:str='hello')->int: '''这是一个文档示例--函数 返回值 int fn()->int 函数参数: a:作用 类型 int 不是强制,主要用于说明int b:作用 类型 bool c:作用 类型 str 默认 hello ''' return 10 print(fn.__doc__) #只输出说明的部分没有help函数的返回来的详细 #help(fn)