blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
bcb92112d57bf053065767c681bfaa10896762a8
djackreuter/coding-challenges-and-algorithms
/coding-challenges/rps.py
2,383
4.03125
4
import random class RockPaperScissors: def __init__(self): self.user_score = 0 self.computer_score = 0 self.options = ["rock", "paper", "scissors"] def get_user_input(self): return input("Choose rock, paper, scissors\n").lower() def get_computer_pick(self, options): return random.choice(options) def check_score(self): if self.computer_score < 3 and self.user_score < 3: self.play() else: self.display_score() return def display_score(self): print("WINS: User: %s Computer: %s" % (self.user_score, self.computer_score)) def play(self): self.display_score() computerPick = self.get_computer_pick(self.options) userPick = self.get_user_input() if (userPick != 'rock' and userPick != 'paper' and userPick != 'scissors'): print("**** Invalid entry ****") if computerPick == userPick: print("You both picked %s" % computerPick) if computerPick == "rock" and userPick == "paper": self.user_score += 1 print("You picked %s, computer picked %s. You win!" % (userPick, computerPick)) elif computerPick == "rock" and userPick == "scissors": self.computer_score += 1 print("You picked %s, computer picked %s. Computer wins!" % (userPick, computerPick)) if computerPick == "paper" and userPick == "rock": self.computer_score += 1 print("You picked %s, computer picked %s. Computer wins!" % (userPick, computerPick)) elif computerPick == "paper" and userPick == "scissors": self.user_score += 1 print("You picked %s, computer picked %s. You win!" % (userPick, computerPick)) if computerPick == "scissors" and userPick == "rock": self.user_score += 1 print("You picked %s, computer picked %s. You win!" % (userPick, computerPick)) elif computerPick == "scissors" and userPick == "paper": self.computer_score += 1 print("You picked %s, computer picked %s. Computer wins!" % (userPick, computerPick)) self.check_score() rpc = RockPaperScissors() rpc.play()
11b3a0032cf6388234b005b4df976b769a16f22c
German-Programmers/python-Course
/4-list-array/exercise.py
702
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 6 17:48:27 2020 @author: ahmad """ # 0 1 2 3 4 5 x = [2, 6, 8, 9, -5, 6] # write a code to print the sum of even numbers inside x storage = 0 for i in range(len(x)): if x[i] % 2 == 0: storage += x[i] print(storage) print("/////////////////////////////") # write a code to print the sum of odd numbers inside x storage = 0 for i in range(len(x)): if x[i] % 2 != 0: storage += x[i] print(storage) print("/////////////////////////////") # write a code to print the max number in x print(max(x)) print("/////////////////////////////") # write a code to print the max number in x print(min(x))
1a444d71dd8fc94e560b751259ba44d4913a612d
German-Programmers/python-Course
/2-for-loop/app.py
486
3.96875
4
#for x in range(10): # print(x) #for x in range(1, 11): # print(x) #for x in range(0, 21, 2): # print(x) #for x in range(1, 11): # print(x * x) # sum nimbers between 1 and 100 #storage = 0 #for x in range(1, 101): # storage = storage + x #print(storage) #//////////////////////// for x in range(10, 0, -1): print(x) # write a function to calculate the factor of the number # example user enter 5 # 5 *4 * 3 * 2 * 1 # check the input is a positive number and
874924405ba9b255f5387a4c6f65ab03d1230b32
arthurnguyen510/GoogleCodeJam
/2016/QualificationRound/B/Revenge_of_the_Pancakes.py
1,704
3.765625
4
def flip_pancake(pancake, length): flipped = '' count = 0 for x in pancake: if count <= length: if x == '-': flipped += '+' elif x == '+': flipped += '-' else: flipped += x count += 1 return flipped def is_happy(stack_of_pancakes): non_happy = 0 for pancake in stack_of_pancakes: if pancake == '-': non_happy += 1 if non_happy == len(stack_of_pancakes): stack_of_pancakes = flip_pancake(stack_of_pancakes, len(stack_of_pancakes) - 1) return True, 1, stack_of_pancakes elif non_happy == 0: return True, 0, stack_of_pancakes else: return False, 0, stack_of_pancakes def serve_pancake(stack_of_pancakes): flips = 0 if len(stack_of_pancakes) == 0: return flips if len(stack_of_pancakes) == 1: if stack_of_pancakes[0] == '-': flips += 1 return flips else: return flips for iter_pancake in range(1, len(stack_of_pancakes)): if stack_of_pancakes[iter_pancake] != stack_of_pancakes[iter_pancake - 1]: stack_of_pancakes = flip_pancake(stack_of_pancakes, iter_pancake - 1) flips += 1 all_happy, curr_flips, stack_of_pancakes = is_happy(stack_of_pancakes) flips += curr_flips return flips def serve_pancake_w_file(input_file): with open(input_file) as input_file: next(input_file) for line in input_file: print(line.strip(), serve_pancake(line.strip())) if __name__ == '__main__': serve_pancake_w_file('GoogleCodeJam/2016/QualificationRound/B/B-small-practice.in')
24e29b35cbfddc136eb812a52019b07bcd14915f
eishk/Python-Soccer-Project
/transfers_scrape.py
4,694
3.671875
4
""" Eish Kapoor & Kunal Bhandarkar CSE 163 AD Final Project This file contains the code that uses the BeautifulSoup library to scrape the TransferMarkt database for the transfers that occurred in the British Premier League. Includes transfers in and out, and scrapes the player's name, position, market value, actual fee paid, new team, and old team. """ import csv import urllib.request as urllib2 from bs4 import BeautifulSoup def main(): """ Method that preprocesses the years and feeds the correct url and file name to the function necessary for creating the csv of soccer transfers for listed years. """ year = ['2017', '2018', '2020'] url = 'https://www.transfermarkt.us/premier-league/transfers/wettbewerb/' 'GB1/plus/?saison_id=2017&s_w=&leihe=0&intern=0&intern=1' url_begin = 'https://www.transfermarkt.us/premier-league/transfers' '/wettbewerb/GB1/plus/?saison_id=' url_end = '&s_w=&leihe=0&intern=0&intern=1' for y in year: url = url_begin + y + url_end file_path = 'transfers_' + y + '.csv' write_transfer_file(url, file_path) def write_transfer_file(url, file_path): """ Takes given website url and given file_path, and appends to the file specified by the file_path rows containing the transfer information for every player transferred in and out of the British Premier League in the season specified by the TransferMarkt url. Writes row for each player in the form of ['Name', 'Position', 'Market Value', 'Actual Fee', 'New Team', 'Old Team']. """ file = open(file_path, 'w', encoding='utf8') writer = csv.writer(file) writer.writerow(['Name', 'Position', 'Market Value', 'Actual Fee', 'New Team', 'Old Team']) request = urllib2.Request(url, headers={'user-agent': 'Mozilla/5.0 ' '(Macintosh; Intel Mac OS' ' X 10_14_6)' ' AppleWebKit/537.36 (KHTML,' ' like Gecko) Chrome/81.0.' '4044.138' 'Safari/537.36'}) page = urllib2.urlopen(request) soup = BeautifulSoup(page, 'html.parser') b = soup.find("div", class_="large-8 columns") boxes = b.find_all("div", class_="box", recursive=False) for box in boxes: tables = box.find_all("div", class_="responsive-table", recursive=False) if (tables): team = box.find("h2").find("a").text in_play = tables[0] in_rows = in_play.find("tbody").find_all("tr") for row in in_rows: infos = row.find_all("td") name = infos[0].find("a", class_="spielprofil_tooltip").text position = infos[4].text market_value = actual_val(infos[5].text) old_team = infos[7].find('a').text actual_fee = actual_val(infos[8].find('a').text) new_team = team writer.writerow([name, position, market_value, actual_fee, new_team, old_team]) out_play = tables[1] out_rows = out_play.find("tbody").find_all("tr") for row in out_rows: infos = row.find_all("td") name = infos[0].find("a", class_="spielprofil_tooltip").text position = infos[4].text market_value = actual_val(infos[5].text) new_team = infos[7].find('a').text actual_fee = actual_val(infos[8].find('a').text) old_team = team writer.writerow([name, position, market_value, actual_fee, new_team, old_team]) file.close() def actual_val(value): """ Helper function for taking the given value and converting it into a format that can be used for further processing of data for the tasks. Turns all the unknown data into zero, free transfers into zero, and turns given fees into their numerical values without the dollar sign. """ if (value == "-"): return 0 elif (value == "Free transfer"): return 0 else: value = value[1:].strip() if not value: return 0 if (value[-1].endswith('m')): value = value[:-1] value = float(value) value = value * 1000000 else: value = value[:-3] value = float(value) value = value * 1000 return value if __name__ == '__main__': main()
634f2f49a02150d44b9cda513c10e381ba547fee
pusiyugithub/codes
/Huawei_exercises/Python3_Implementations/字符串加解密.py
1,272
3.9375
4
import sys def encrypt(a): s = str() for x in range(len(a)): if a[x].islower() and a[x] is not "z": s = s + str(chr(ord(a[x])+1).upper()) elif a[x] == "z": s = s + "A" elif a[x].isupper() and a[x] is not "Z": s = s + str(chr(ord(a[x])+1).lower()) elif a[x] == "Z": s = s + "a" elif a[x].isdigit() and a[x] is not "9": s = s + chr(ord(a[x])+1) elif a[x] is "9": s = s + "0" else: s = s + a[x] return s def unEncrypt(a): s = str() for x in range(len(a)): if a[x].islower() and a[x] is not "a": s = s + str(chr(ord(a[x])-1).upper()) elif a[x] == "a": s = s + "Z" elif a[x].isupper() and a[x] is not "A": s = s + str(chr(ord(a[x]) - 1).lower()) elif a[x] == "A": s = s + "z" elif a[x].isdigit() and a[x] is not "0": s = s + chr(ord(a[x])-1) elif a[x] is "0": s = s + "9" else: s = s + a[x] return s while True: a = sys.stdin.readline().strip() b = sys.stdin.readline().strip() if len(a) == 0: break print(encrypt(a)) print(unEncrypt(b))
bb4c03b87e7c1eed351c0adc16f19e85ad75093d
RomanKhripunov/LearningPython
/OneMoreTime/encrypt_data.py
395
3.5625
4
from simplecrypt import decrypt, DecryptionException with open("encrypted.bin", "rb") as inp_file: encrypted_data = inp_file.read() passwords = [line.rstrip() for line in open("password.txt")] for password in passwords: try: result = decrypt(password, encrypted_data).decode('utf8') except DecryptionException: continue print(result)
f943693e92feb6a7ec50f7202bcb0022a10c4317
RomanKhripunov/LearningPython
/Checkio_org/HOME/checkio_sun_angle.py
561
3.65625
4
def sun_angle(time): splited_time = [int(i) for i in time.split(":")] angle = ((splited_time[0] - 6) * 15) + (splited_time[1] * 0.25) return angle if 0 <= angle <= 180 else "I don't see the sun!" if __name__ == '__main__': assert sun_angle("07:00") == 15 assert sun_angle("18:00") == 180 assert sun_angle("18:01") == "I don't see the sun!" assert sun_angle("06:00") == 0 assert sun_angle("06:15") == 3.75 assert sun_angle("01:23") == "I don't see the sun!" print("Coding complete? Click 'Check' to earn cool rewards!")
db910935e1f36a6c09ceb3ffed2f9dcbf599e61d
RomanKhripunov/LearningPython
/Checkio_org/ELECTRONIC STATION/brackets.py
1,300
3.859375
4
def checkio(expression): left_brackets = ('(', '{', '[') right_brackets = {')': left_brackets[0], '}': left_brackets[1], ']': left_brackets[2]} brackets_only = [ch for ch in expression if ch in left_brackets or ch in right_brackets] queue_brackets = [] if len(brackets_only) == 0: return True if len(brackets_only) % 2 != 0: return False for symbol in brackets_only: if symbol in left_brackets: queue_brackets.append(symbol) elif symbol in right_brackets and len(queue_brackets) > 0 and queue_brackets[-1] == right_brackets[symbol]: queue_brackets.pop() return not queue_brackets # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("((5+3)*2+1)") == True, "Simple" assert checkio("{[(3+1)+2]+}") == True, "Different types" assert checkio("(3+{1-1)}") == False, ") is alone inside {}" assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert checkio("2+3") == True, "No brackets, no problem" assert checkio("[{}]]") == False, "Failed in checkio" assert checkio("[1+202]*3*({4+3)}") == False, "Failed in checkio"
a1b1bdced1aa97a4b83b1b5bcc893be5fd7dad3d
RomanKhripunov/LearningPython
/Checkio_org/ELEMENTERY/checkio_easy_unpack.py
703
3.921875
4
def easy_unpack(elements): return elements[0], elements[2], elements[-2] def easy_unpack_2(elements): return tuple(elements[i] for i in (0, 2, -2)) if __name__ == '__main__': import time start = time.time() assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7) assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1) assert easy_unpack((6, 3, 7)) == (6, 7, 3) end = time.time() print("{:0.7f}".format(end - start)) start = time.time() assert easy_unpack_2((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7) assert easy_unpack_2((1, 1, 1, 1)) == (1, 1, 1) assert easy_unpack_2((6, 3, 7)) == (6, 7, 3) end = time.time() print("{:0.7f}".format(end - start))
039163c6f95b4b0b8f906a76c33a67f31478fd46
RomanKhripunov/LearningPython
/Checkio_org/HOME/checkio_safe_pawns.py
868
3.65625
4
def safe_pawns(pawns): cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] saved_pawns = set() pawn_positions = [[pawn[:1], int(pawn[1:])] for pawn in pawns] for pawn_position in pawn_positions: print(pawn_position) p_list = [] for i in [+1, -1]: p_list.append(cols[cols.index(pawn_position[0]) + i] + str(pawn_position[1] + 1)) print(p_list) for item in p_list: if item in pawns: saved_pawns.add(item) return len(saved_pawns) 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!")
7b8241125841ad4f17077ed706af394576f6a0dc
briand27/LPTHW-Exercises
/ex20.py
1,172
4.15625
4
# imports System from sys import argv # creates variables script and input_file for arguments script, input_file = argv # define a function that takes in a file to read def print_all(f): print f.read() # define a function that takes in a file to seek def rewind(f): f.seek(0) # defines a function that prints out the given line of a given file def print_a_line(line_count, f): print line_count, f.readline() # creates a variable that represents the open input_file current_file = open(input_file) print "First let's print the whole file:\n" # calls print_all on the given file print_all(current_file) print "Now let's rewind, kind of like a tape." # calls rewind on the given current_file rewind(current_file) print "Let's print three lines:" # sets current_line to 1 the prints that line of the current_file current_line = 1 print_a_line(current_line, current_file) # sets the current_line one higher then prints that line of the current_file current_line += 1 print_a_line(current_line, current_file) # sets the current_line one higher again then prints that line of # the current_file current_line += 1 print_a_line(current_line, current_file)
38aa94d68254fe0903e6eb1de10d10c23eab47b6
mlbudda/Checkio
/home/sort_by_frequency.py
542
4.34375
4
# Sort Array by Element Frequency def frequency_sort(items): """ Sorts elements by decreasing frequency order """ return sorted(items, key=lambda x: (-items.count(x), items.index(x))) # Running some tests.. print(list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]) print(list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']) print(list(frequency_sort([17, 99, 42])) == [17, 99, 42]) print(list(frequency_sort([])) == []) print(list(frequency_sort([1])) == [1])
b2edfeef59563ca85ae59503a385cc2119619b36
mlbudda/Checkio
/home/non_unique_elements.py
566
3.734375
4
# Non-unique Elements def checkio(data: list) -> list: numbers_remove = [] for number in data: if data.count(number) == 1: numbers_remove.append(number) for number in numbers_remove: data.remove(number) return data # Running some tests... print(list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example") print(list(checkio([1, 2, 3, 4, 5])) == [], "2nd example") print(list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example") print(list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example")
08453389f502d9b6bd1737a01e085fe31973d18e
mlbudda/Checkio
/home/three_words.py
553
4.03125
4
# Three Words def checkio(words: str) -> bool: counter = 0 a = 0 for i in words.split(): if i.isalpha(): counter += 1 else: counter = 0 if counter >= 3: a = 1 if a == 0: return False else: return True # Running some print(checkio("Hello World hello") == True, "Hello") print(checkio("He is 123 man") == False, "123 man") print(checkio("1 2 3 4") == False, "Digits") print(checkio("bla bla bla bla") == True, "Bla Bla") print(checkio("Hi") == False, "Hi")
e664d5093b90287e72a19e2b31627eb4e996893c
mlbudda/Checkio
/home/right_to_left.py
540
3.84375
4
# Right to Left def left_join(phrases: tuple) -> str: new = '' for i in phrases: changed = str(i) new = new + changed.replace('right', 'left') + ',' return new[:-1] # Running some tests... print(left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left") print(left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left") print(left_join(("brightness wright",)) == "bleftness wleft", "One phrase") print(left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace")
03389bd8ab6b7f1a14d681c6f209c264e2e27aad
mlbudda/Checkio
/o_reilly/index_power.py
440
4.15625
4
# Index Power def index_power(array: list, n: int) -> int: """ Find Nth power of the element with index N. """ try: return array[n] ** n except IndexError: return -1 # Running some tests.. print(index_power([1, 2, 3, 4], 2) == 9, "Square") print(index_power([1, 3, 10, 100], 3) == 1000000, "Cube") print(index_power([0, 1], 0) == 1, "Zero power") print(index_power([1, 2], 3) == -1, "IndexError")
d6760387a314db3a6de96e480e522257c8e015eb
mlbudda/Checkio
/home/counts_digits.py
582
4.03125
4
# Count Digits def count_digits(text: str) -> int: """ Count Digits """ counter = 0 for digit in text: if digit.isdigit(): counter += 1 return counter # Running some tests.. print(count_digits('hi') == 0) print(count_digits('who is 1st here') == 1) print(count_digits('my numbers is 2') == 1) print(count_digits('This picture is an oil on canvas ' 'painting by Danish artist Anna ' 'Petersen between 1845 and 1910 year') == 8) print(count_digits('5 plus 6 is') == 2) print(count_digits('') == 0)
d732bfc4c9ecf3121a0bdf897eddf0b3cd414638
mlbudda/Checkio
/elementary/first_word_simplified.py
256
3.96875
4
# First Word (simplified) def first_word(text): """ Splits and returns first word """ return text.rsplit()[0] # Running some tests... print(first_word("Hello world") == "Hello") print(first_word("a word") == "a") print(first_word("hi") == "hi")
4a442936b64bfd63e155d557db6dad95e4af3acb
jcktng/NNFS
/network.py
1,513
3.578125
4
import numpy as np import nnfs from nnfs.datasets import spiral_data nnfs.init() class Layer_Dense: ''' n_inputs = number of features (per data sample or per output of the previous layer) n_neurons = number of neurons (per layer) ''' def __init__(self, n_inputs, n_neurons): # Returns an array of shape n_inputs x n_neurons of the standard normal distribution self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) # Returns a zero array of shape 1 x n_neurons self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLU: def forward(self, inputs): self.output = np.maximum(0,inputs) class Activation_Softmax: def forward(self, inputs): # Exponentiation and subtraction of max (calculated per row) exp_values = np.exp(inputs) - np.max(inputs, axis=1, keepdims=True) # Normalization of the values probabilities = exp_values / np.sum(exp_values, axis=1, keepdims=True) self.output = probabilities # Returns a spiral shape dataset of 100 samples per class, with 3 classes X, y = spiral_data(100, 3) # 2 input features, 3 neurons dense1 = Layer_Dense(2,3) activation1 = Activation_ReLU() # 3 input features, 3 output neurons (3 predicted classes) dense2 = Layer_Dense(3,3) activation2 = Activation_Softmax() dense1.forward(X) activation1.forward(dense1.output) dense2.forward(activation1.output) activation2.forward(dense2.output) print(activation2.output[:5])
473d7d7500ffc160f056d661b0ef8a1d297a84a7
mnsupreme/artificial_intelligence_learning
/normal_equation.py
2,911
4.3125
4
#This code solves for the optimum values of the parameters analytically using calculus. # It is an alternative way to optimizing iterarively using gradient descent. It is usually faster # but is much more computationally expensive. It is good if you have 1000 or less parameters to solve for. # complexity is O(n^3) # This examply assumes the equation y = param_0(y-intercept) + param_1 * input_1 + param_2 * input_2.... # If you have an equation in a different form such as y = param_0(y-intercept) + param_1 * input_1 * input_2 + param_2 * (input_2)^2 # then you must make adjustments to the design matrix accordignly. (Multiply the inputs acordingly and use those results in the design matrix) import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data from matplotlib import cm import numpy as np from numpy.linalg import inv data = np.loadtxt('gradient_descent/ex3Data/ex3x.dat',dtype=float) #this function helps put the inputs in vector form as the original data already came as a design matrix. #This way the data is more realistic. Technically, this function is unecessary def vectorize_data(): #regular python list vectorized_data = [] for row in data: # inserts a 1 in the beginning every row of the matrix to represent x_0 input row = np.insert(row,0,1) print "row {0}, \n row_transpose {1}".format(row, row.reshape((-1,1))) #converts [element1, element 2] to [ form. # element1, # element2, # ] vectorized_data.append(row.reshape((-1,1))) #you need to convert design matrix into a numpy array because it starts out as a regular python list. vectorized_data = np.array(vectorized_data) print vectorized_data return vectorized_data x = vectorize_data() #converts vectorized data into a design matrix. # The design matrix looks like this: design_matrix = [transpose_of_each_input_vector or transpose_of_each_row_in_vectorized_data] def assemble_design_matrix(): #regulare python list design_matrix = [] for row in x: design_matrix.append(row.transpose()) #you need to convert design matrix into a numpy array before you convert it to a matrix because it starts out asa regular python list. design_matrix = np.matrix(np.array(design_matrix)) print "design_matrix {0} \n design_matrix_transpose {1}".format(design_matrix, design_matrix.transpose()) return design_matrix def normal(): design_matrix = assemble_design_matrix() y = np.loadtxt('gradient_descent/ex3Data/ex3y.dat', dtype=float) y = y.reshape(47,1) # THIS IS THE NORMAL EQUATION FORMULA # the function is inverse(design_matrix_transpose * design_matrix) * (design_matrix_transpose * y_vector) # this will yield a matrix full of your optimized theta parameter values result = inv((design_matrix.transpose() * design_matrix)) * (design_matrix.transpose() * y) print result return result if __name__ == '__main__': normal()
d1f3e0538d8573baf8ab25baa9377a17ffb7ce45
imneeteeshyadav98/KNN
/main.py
898
3.609375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset=pd.read_csv("/home/data_science/Desktop/Mlops-ws/KNN/Social_Network_Ads.csv") X=dataset[['Age', 'EstimatedSalary']] y=dataset['Purchased'] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.30,random_state=42) from sklearn.neighbors import KNeighborsClassifier model=KNeighborsClassifier(n_neighbors=5) model.fit(X_train,y_train) y_pred=model.predict(X_test) error_rate=[] for i in range(1,50): model=KNeighborsClassifier(n_neighbors=i) model.fit(X_train,y_train) y_pred=model.predict(X_test) error_rate.append(np.mean(y_test != y_pred)) from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score accuracy=accuracy_score(y_test, y_pred)*100 print(accuracy) print(accuracy,file=open("accuracy.txt", "w"))
3182e9c532d11a9a035662a522591d301ca21c57
code-lucidal58/python_inception
/examples/guess_the_number.py
837
3.734375
4
from random import randint print("Hi! Welcome to Guess the Number Game!") r_no = 0 play = True while play: max_no = 500 min_no = -500 r_no = randint(-500, 500) g_no = -501 c = 0 while g_no != r_no: g_no = int(input(f"start guessing in the range: {min_no} and {max_no}: ")) if r_no > g_no > min_no: min_no = g_no elif r_no < g_no < max_no: max_no = g_no c = c + 1 print(f"Voila! you guessed the number {g_no} in {c} trials!") condition = True res = '' while condition: allowedChars = ['Y', 'y', 'N', 'n'] res = input("Want to play again? (y/n)") if len(res) == 1 and res in allowedChars: condition = False if res == 'N' or res == 'n': print("Have a Nice day! Goodbye!") play = False
ef2fb36ea0588d36aa6b49ad55d57ee4a5d64bc0
dguest/example-text-parser
/look.py
1,851
4.15625
4
#!/usr/bin/env python3 import sys from collections import Counter from csv import reader def run(): input_name = sys.argv[1] csv = reader(open(input_name), skipinitialspace=True) # first read off the titles titles = next(csv) indices = {name:number for number, name in enumerate(titles)} # keep track of something (proj_by_company) in this case proj_by_company = Counter() # iterate through all the records for fields in csv: # build up a dictionary of fields named_fields = {titles[idx]:val for idx, val in enumerate(fields)} company = named_fields['Company Name'] # The empty string us used in the CSV to represent zero. comp_projs_as_string = named_fields['# projects completed'] # Unfortunately, this means that we have to manually enter # zero in the case of en empty string. Empty strings evaluate # to False. # # Note that this whole operation could be represented with some # more magic as: # > comp_projs = int(named_fields['# projects completed'] or 0) # but it's a bit confusing to understand why that works. if not comp_projs_as_string: comp_projs = 0 else: comp_projs = int(comp_projs_as_string) # add to the counter proj_by_company[company] += comp_projs # Do some sorting. The sort function works on a container, which # we get by using `.items()` to return a list of (key, value) # pairs. In this case we're sorting by the second value, thus the # anonymous function created with `lambda`. sorted_companies = sorted(proj_by_company.items(),key=lambda x: x[1]) for company, count in reversed(sorted_companies): if count > 0: print(company, count) if __name__ == '__main__': run()
0a89fb4a194227f7463e9945df4fed52a1304e83
kingbhtang/leetcode
/two_sum/two_sum.py
1,125
3.515625
4
#!/usr/local/bin/python3 #-*- encoding=utf-8 -*- def two_sum(nums, target): for idx_a, number_a in enumerate(nums): for idx_b, number_b in enumerate(nums): if idx_a == idx_b: continue if number_a + number_b == target: return [idx_a, idx_b] return [] def two_sum_fast(nums, target): targets = {} for i,n in enumerate(nums): t = targets.get(n) if t is not None: return [t, i] targets[target - n] = i return [] def two_sum_find_all(nums, target): results = [] targets = {} for i,n in enumerate(nums): t = targets.get(n) if t is not None: results.append([t, i]) targets[target - n] = i return results def two_sum_allow_duplicate(nums, target): results = [] targets = {} for i,n in enumerate(nums): t = targets.get(n) if t is not None: results.append([t, i]) targets[target - n] = i if n * 2 == target: results.append([i, i]) return results
958bc0788779a133eda6eb3587c5823f67c9f842
navneethkour/LeetCode-Python-1
/LinkedList/RemoveNthNodeFromEndOfList.py
575
3.78125
4
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # Given a linked list, remove the nth node from the end of list and return its head. from ListNode import ListNode class Solution(object): def removeNthFromEnd(self, head, n): tempHead = listNode = head for _ in range(n) : tempHead = tempHead.next if tempHead == None : return head.next while tempHead.next : listNode = listNode.next tempHead = tempHead.next listNode.next = listNode.next.next return head
01f2769c18ac7415bcf0038383060d5795352fa7
navneethkour/LeetCode-Python-1
/Array/ThirdMaximumNumber.py
757
3.5625
4
import sys class Solution(object): def thirdMax1(self, nums): # https: // discuss.leetcode.com / topic / 64696 / a - python - amusing - solution - which - actually - beats - 98 / 3 nums = set(nums) if len(nums) < 3: return max(nums) nums.remove(max(nums)) nums.remove(max(nums)) return max(nums) def thirdMax2(self, nums): nums = set(nums) max = max2 = max3 = -sys.maxsize - 1 for n in nums: if n > max: max, max2, max3 = n, max, max2 elif n > max2: max2, max3 = n, max2 elif n > max: max3 = n return max3 if max3 != -sys.maxsize - 1 else max s = Solution([n])
452658ce285cf8c78a12230847dc3bbf51f943c9
navneethkour/LeetCode-Python-1
/Tree/SameTree.py
332
3.65625
4
# Definition for a binary tree node. from TreeNode import TreeNode class Solution(object): def isSameTree(self, p, q): if not p and not q : return True if not p : return False if not q : return False return (p.val == q.val) and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
beb3aab77660298284a8efade6bc1f390f12d6d6
navneethkour/LeetCode-Python-1
/Number/GuessNumberHigherOrLower.py
832
4.09375
4
# https://leetcode.com/problems/guess-number-higher-or-lower/ # We are playing the Guess Game. The game is as follows: # # I pick a number from 1 to n. You have to guess which number I picked. # # Every time you guess wrong, I'll tell you whether the number is higher or lower. # # You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): # # -1 : My number is lower # 1 : My number is higher # 0 : Congrats! You got it! def guess(num,x): pass class Solution(object): def guessNumber(self, n): begin,end = 1,n while True: curNum = (begin + end) // 2 curBool = guess(curNum) if curBool == 1: end = curNum - 1 elif curBool == -1: begin = curNum + 1 else: return curNum
8f3d7b8bf0db7516cc8e9ba19669a067bf7a64a3
navneethkour/LeetCode-Python-1
/Number/ReverseInteger.py
416
3.796875
4
# https://leetcode.com/problems/reverse-integer/ # Reverse digits of an integer. # # Example1: x = 123, return 321 # Example2: x = -123, return -321 class Solution(object): def reverse(self, x): if x < 0 : return -self.reverse(-x) result = 0 while x: result = x % 10 + result * 10 x = x // 10 return result if abs(result)< 2147483648 else 0 s = Solution()
e62b1d5d3b9929032bbf080ae85e4c3b76c358e5
navneethkour/LeetCode-Python-1
/Array/SortColors.py
625
3.71875
4
# https://leetcode.com/problems/sort-colors/ class Solution(object): def sortColors(self, nums): # https://discuss.leetcode.com/topic/36160/python-o-n-1-pass-in-place-solution-with-explanation/2 red,head,tail = 0,0,len(nums) - 1 while head <= tail: if nums[head] == 0 : nums[red],nums[head] = nums[head],nums[red] head += 1 red += 1 elif nums[head] == 1: head += 1 else: nums[head],nums[tail] = nums[tail],nums[head] tail -= 1 # print(Solution().sortColors([0]))
e071ed7687d0e35c28a370463bc08c49cbd5c2ea
bpabraham123/FantasyFootball21-22
/editDF.py
5,470
3.796875
4
from bs4 import BeautifulSoup import pandas as pd from urllib.request import urlopen # This function takes an int as its input, where the input corresponds to a year # after 1999. The function returns a pandas dataFrame of the scraped data def scrape(year): url = "https://www.pro-football-reference.com/years/{}/fantasy.htm#".format(year) html = urlopen(url) #Creates a BeautifulSoup object soup = BeautifulSoup(html, features="lxml") headers = [th.getText() for th in soup.findAll('tr')[1].findAll('th')] headers = headers[1:] # finds all the rows that are not headers rows = soup.findAll('tr', class_= lambda table_rows: table_rows != "thead") player_stats = [[td.getText() for td in rows[i].findAll('td')] for i in range(len(rows))] player_stats = player_stats[2:] # creates an pandas dataframe object called stats stats = pd.DataFrame(player_stats, columns = headers) stats = stats.replace(r'', value=0, regex=True) stats['Year'] = year return stats # This function takes two ints as its inputs, both of which correspond to a year # after 1999. The function uses the scrape function to scrape the data from # each year within that range. It then creates a pandas dataframe with all of #the data, and it returns said dataframe. def createDF(startYear, endYear): stats = pd.DataFrame() years = [] # iterates through years specified for year in range(startYear, endYear + 1): years.append(year) for year in years: stats = stats.append(scrape(year)) return stats # This function cleans the data in the input dataframe by removing unneeded # columns, renaming repeated columns, and adding columns. This function requires # that the dataframe input was a dataframe made with the createDF() function. # This function returns the cleaned dataframe. def cleanDF(dataFrame): #edits df to not include unneeded statistics columnsToRemove = ['Tm', 'GS', 'Fmb', 'FL', '2PM', '2PP', 'DKPt', 'FDPt', 'FantPt'] dataFrame = dataFrame.drop(columns = columnsToRemove) # Renames repeated columns cols = [] ydsNum = 0 tdNum = 0 attNum = 0 for column in dataFrame.columns: if column == 'Yds': if ydsNum == 0: cols.append('PassYds') elif ydsNum == 1: cols.append('RushYds') elif ydsNum == 2: cols.append('RecYds') ydsNum += 1 elif column == 'Att': if attNum == 0: cols.append('PassAtt') elif attNum == 1: cols.append('RushAtt') attNum += 1 elif column == 'TD': if tdNum == 0: cols.append('PassTD') elif tdNum == 1: cols.append('RushTD') elif tdNum == 2: cols.append('RecTD') elif tdNum == 3: cols.append('TotTD') tdNum += 1 else: cols.append(column) dataFrame.columns = cols listOfColumns = ['Cmp', 'PassAtt' , 'PassYds', 'PassTD', 'Int', 'RushAtt', 'RushYds', 'RushTD', 'Tgt', 'Rec', 'RecYds', 'RecTD', 'TotTD'] # Creates columns for stats per game for column in listOfColumns: newColumn = column + '/G' dataFrame[newColumn] = (pd.to_numeric(dataFrame[column]) / pd.to_numeric(dataFrame['G'])) dataFrame[newColumn] = dataFrame[newColumn].round(decimals = 3) dataFrame = dataFrame.drop(columns = listOfColumns) # Creates column of points per game dataFrame['PPG'] = (pd.to_numeric(dataFrame['PPR']) / pd.to_numeric(dataFrame['G'])) dataFrame['PPG'] = dataFrame['PPG'].round(decimals=3) # edits name for uniformity year over year dataFrame['Player'] = dataFrame.Player.str.replace('[^a-zA-Z]', '', regex = True) # creates unique player ID to make stats for different years easier to see playerID = [] for index, row in dataFrame.iterrows(): playerID.append(row['Player'] + str(row['Year'])) dataFrame['ID'] = playerID # Sorts dataFrame to make it easier to find the value of the next year ppg dataFrame = dataFrame.sort_values(by = ['ID'], ascending = False) # Creates a list of the next year's PPG nextYearPPG = [] lastPlayer = 'NaN' lastPlayerPPG = 'NaN' for index, row in dataFrame.iterrows(): player = row['Player'] if lastPlayer == player: nextYearPPG.append(lastPlayerPPG) else: nextYearPPG.append('NaN') lastPlayer = row['Player'] lastPlayerPPG = row['PPG'] dataFrame['Next Year PPG'] = nextYearPPG dataFrame = dataFrame.sort_values(by = ['ID'], ascending = True) dataFrame = dataFrame.reset_index(drop = True) return dataFrame # This function takes a list of dataframes created with the createDF() function, # and combines and sorts them and returns the new dataframe. def combineData(listOfDataFrames): # creates a df which contains the dataframes in the list which is passed in df = pd.concat(listOfDataFrames) df = df.sort_values(by = ['Predicted PPR'], ascending = False) # gives players an overall ranking rankings = [] rank = 1 for index, row in df.iterrows(): rankings.append(rank) rank += 1 df['Ovr Rank'] = rankings df = df.reset_index(drop = True) return df
084937315f25b39e07f7c402bc6c1442336bc86b
ldj5123/Linux
/PYTHON/chapter4/chap4_lab6_temperature.py
233
3.640625
4
maxCelsius = int(input('몇 도씨까지 출력 : ')) increase = int(input('증가 폭을 입력 : ')) for i in range(0, maxCelsius + increase, increase): celsius = (i - 32) * 5 / 9 print(i, ' -> ', round(celsius, 2))
868537b2701e31b1eaf2351a0083a857c7c0d08e
ldj5123/Linux
/PYTHON/chapter4/chap4_lab2_middlechar.py
229
3.71875
4
str = input('문자열을 입력하시오 : ') print(len(str)) if (len(str) % 2 == 0): i = len(str) // 2 print('중앙글자는 ', str[i-1], str[i]) else: i = len(str) // 2 print('중앙글자는 ', str[i])
e6e895f5e7de73079d1e1a90b53060a7856fcb63
ldj5123/Linux
/PYTHON/chapter3/chap3_memory.py
127
3.703125
4
a = 300 b = 300 print(a is b) print(a == b) a = [5, 4, 3, 2, 1] b = [1, 2, 3, 4, 5] b = a print(b) a.sort() print(b)
dd0ec030f8e21fe2a8fc177625345bf8a2385a2d
ldj5123/Linux
/PYTHON/chapter6/chap6_lab2_stringFind.py
265
3.578125
4
str = input('문서를 작성하세요\n') findStr = input('찾을 문자를 입력하세요 : ') findIndex = 0 for i in range(len(str)): if findStr == str[i]: findIndex = i+1 print(findStr, '/', findIndex, '/', str.count(findStr))
d03469d76411573347da07d8f7c766e17ea189d3
ldj5123/Linux
/PYTHON/chapter7/chap7_lab4_samename.py
320
3.828125
4
def findSameName(name): for i in range(len(name)): for j in range(len(name)): if i != j and name[i] == name[j]: print(name[i]) name = ['Tom', 'Jerry', 'Mike', 'Tom'] print(findSameName(name)) name2 = ['Tom', 'Jerry', 'Mike', 'Tom', 'Mike'] print(findSameName(name2))
4b7b6de8a345ea1f72d74e666e7888fe80d694cb
helloworld/AI
/lab2.py
2,051
3.640625
4
from string import ascii_lowercase from pprint import pprint import pickle ''' +======================+ | Sashank Thupukari | | Period 6 | | Lab 2 | | 9/9/2014 | +======================+ Objective: Create a dictionary with a list of six letter words as the keys and their neighbors as the values. ''' def main(): wordArray = openFile() dictionary = createDictionary(wordArray) #pprint(dictionary) checkNumWords(dictionary) def openFile(): fileName = "words.txt" wordFile = open (fileName, 'r') wordArray = wordFile.readlines() return wordArray def createDictionary(wordArray): dictionary = {} for x in range(len(wordArray)): currentWord = wordArray[x].strip() dictionary[currentWord] = getNeighbors(currentWord, wordArray) return dictionary def getNeighbors(word, wordArray): neighborArray = [] for x in range(len(wordArray)): levenshteinDistance = 0 currentWord = wordArray[x].strip() if not((word[0] != currentWord[0]) and (word[1] != currentWord[1]) and (word[2] != currentWord[2])): for y in range(6): if(levenshteinDistance>1): break if word[y] != currentWord[y]: levenshteinDistance += 1 if levenshteinDistance == 1: neighborArray.append(currentWord) return neighborArray def saveFile(dictionary): dictFile = open("dictionary.txt", 'wb') pickle.dump(dictionary, dictFile) dictFile.close() def checkNumWords(dictionary): print("Number of words in the dictionary: ", len(dictionary)) if __name__ == '__main__': from time import clock; START_TIME = clock(); main(); print('\n+===<RUN TIME>===+'); print('| %5.2f'%(clock()-START_TIME), 'seconds |'); print('+================+')
bdaafba3b5d899455166d1ba58bf9035becbb04b
alex-huff/advent-of-code-2020
/day3.py
1,184
3.90625
4
def wrapHorizontal(index, size): return index % size def multipliedList(mList): return multiplied(mList, 0, len(mList) - 1) def multiplied(mList, start, finish): if start == finish: return mList[start] return mList[start] * multiplied(mList, start + 1, finish) biome = [] horizontalLength = 0; verticleLength = 0; with open('input/day3input.txt') as file: for line in file: biome.append([True if obstacle == '#' else False for obstacle in line.rstrip()]) verticleLength += 1 horizontalLength = len(biome[0]) # length of the map horizontally # part 1 dh = 3 dv = 1 hits = 0 posH = 0 posV = 0 while posV < verticleLength: if biome[posV][wrapHorizontal(posH, horizontalLength)]: hits += 1 posH += dh posV += dv print(hits) # part 2 slopes = [ [1, 1], [3, 1], [5, 1], [7, 1], [1, 2] ] hitlist = [] for slope in slopes: hits = 0 posH = 0 posV = 0 while posV < verticleLength: if biome[posV][wrapHorizontal(posH, horizontalLength)]: hits += 1 posH += slope[0] posV += slope[1] hitlist.append(hits) print(multipliedList(hitlist))
73e4a5f278d5137ed57e5156b5db882a99acf242
min1378/-algorithm
/kakao/12918_문자열다루기기본.py
324
3.703125
4
def solution(s): answer = True length = len(s) # check = "123456789" # for i in check: # print(i, ord(i)) if (length != 4 and length != 6): return False for char in s: if ord(char) < 48 or ord(char) > 57: return False return answer print(solution("12345s"))
3ae8a473cdbcfbda6aff5ad96626344e9e147996
min1378/-algorithm
/kakao/12903_가운데글자가져오기.py
226
3.6875
4
def solution(s): answer = '' length = len(s) if length % 2 : answer = s[length//2] else : answer = s[length//2-1:length//2+1] return answer print(solution("abcde")) print(solution("qwer"))
7d3b5507f0793d9b9b3753b78aedd9c95d1d988e
min1378/-algorithm
/kakao 2020/2.py
190
3.5625
4
def solution(expression): multi_index = [] for char in expression: if char == "*": print(check) return check print(solution( "100-200*300-500+20"))
e44ea727e4ae4cf4dcc9fd168a1e2f2aceebd7d8
min1378/-algorithm
/SWEA/4873. 반복문자 지우기.py
391
3.515625
4
import sys sys.stdin = open("input.txt", "r") def inspect(temp): stack = [] for i in temp: if stack != [] and stack[-1] == i : stack.pop() else : stack.append(i) return len(stack) T = int(input()) for test_case in range(1, T + 1): temp = list(str(input())) result = inspect(temp) print('#{} {}'.format(test_case, result))
deab3bf5eb74028a99be9e9b7c7fb0db849a5b5b
min1378/-algorithm
/kakao/17681.py
523
3.5625
4
def check(list, n): if len(list) != n: list = "0" * (n - len(list)) + list return list def check2(str): temp = "" for st in str: if st == "1": temp += "#" elif st == "0": temp += " " return temp def solution(n, arr1, arr2): answer = [] for i in range(n): result = bin(arr1[i] | arr2[i]) result2 = result[2:] result3 = check(result2, n) result4 = check2(result3) answer.append(result4) return answer
b9c95b485860f5d260e7faadc550d64be48ac8f4
min1378/-algorithm
/hyundaecard/3.py
793
3.640625
4
def check(string): for s in string: if ord("a") <= ord(s) <= ord("z"): continue return string[:string.index(s)],int(string[string.index(s):]) return string, 0 def solution(registered_list, new_id): answer = '' temp_id = new_id string, number = check(temp_id) while True: if temp_id not in registered_list: answer = temp_id return answer number += 1 temp_id = string + str(number) print(solution(["card", "ace13", "ace16", "banker", "ace17", "ace14"], "ace15")) print(solution(["bird99", "bird98", "bird101", "gotoxy"], "bird98")) print(solution(["apple1", "orange", "banana3"], "apple")) print(solution(["cow", "cow1", "cow2", "cow3", "cow4", "cow9", "cow8", "cow7", "cow6", "cow5"], "cow"))
ae777ad793df0bc4ffd15c783e398307b3993df4
min1378/-algorithm
/kakao/12921_소수찾기.py
389
3.828125
4
def solution(n): answer = 0 is_prime = [False, False] + [True] * (n - 1) primes = [] # print(is_prime) for number in range(2, n + 1): if is_prime[number]: primes.append(number) for multiple_prime in range(2 * number, n + 1, number): # 4 6 8 10 is_prime[multiple_prime] = False # print(prime) return len(primes)
3326854b4be059c4b69da4a65be09e8f44de2b77
min1378/-algorithm
/SWEA/중위순회.py
1,764
3.828125
4
class Node(object): def __init__(self, val): self.val = val # 자신이 관리하는 값 self.left = None self.right = None class Tree: # Tree(object) def __init__(self): # 초기화 함수 self.root = None # 트리는 루트노드의 필수 def add(self, val): if self.root is None: self.root = Node(val) else: self._add(val, self.root) # 재귀적인 저장 함수 def _add(self, val, node): if node.val > val: # val 은 저장하려는 숫자, 작으면 왼쪽, 크면 오른쪽. if node.left is None: node.left = Node(val) else: # left 에 node 가 있으면 그 아래에 저장 self._add(val, node.left) else: if node.right is None: node.right = Node(val) else: self._add(val, node.right) def printAll(self): if self.root is None: return self._print(self.root) def _print(self, node): if node is not None: print(node.val) # 자기자신출력 self._print(node.left) self._print(node.right) def find(self, key): return self._find(self.root, key) def _find(self, node, key): if node is None: return False if node.val == key: return True if node.val > key: return self._find(node.left, key) return self._find(node.right, key) t = Tree() s = [40, 4, 34, 35, 14, 55, 48] for i in range(len(s)): t.add(s[i]) # 숫자추가 t.printAll() # 전체저장값 출력하기. 전위, 중위, 후위검색 print('t.find(34)', t.find(34)) print('t.find(44)', t.find(44))
21ebaf035e0a5bda9b9836a8c77221f20c9f4388
timomak/CS-1.3
/First try 😭/redact_problem.py
692
4.21875
4
def reduct_words(given_array1=[], given_array2=[]): """ Takes 2 arrays. Returns an array with the words from the first array, that were not present in the second array. """ output_array = [] # Array that is gonna be returned for word in given_array1: # For each item in the first array, loop O(n) if word not in set(given_array2): # Check if the current item is present in the second array. output_array.append(word) # Append to output array return output_array # return the final array after for loop # Custom test ;) if reduct_words([1,2,3,4,5,10], [1,2,3,4,5,6,7,8,9,0]) == [10]: print("works") else: print("Doesn't work")
fb38793cd1651ae6b6304889e08f4d99d7fa8afd
bastiaanhoeben/bikeshare
/bikeshare.py
8,324
4.25
4
import math import time import pandas as pd # prevent collapsing of dataframe columns in output pd.set_option('display.max_columns', 200) CITY_DATA = { 'chicago': 'data/chicago.csv', 'new york city': 'data/new_york_city.csv', 'washington': 'data/washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!\n') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city = input('Please select a city (Chicago, New York City or Washington): ').lower() while city not in ['chicago', 'new york city', 'washington']: city = input('Incorrect city name given! \n' 'Please type in either Chicago, New York City or Washington: ').lower() # get user input for month (all, january, february, ... , june) month = input('Please select a month (all, January, February, ... , June: ').lower() while month not in ['all', 'january', 'february', 'march', 'april', 'may', 'june']: month = input('Incorrect month given! \n' 'Please type in "all" or a month in range January - June: ').lower() # get user input for day of week (all, monday, tuesday, ... sunday) day = input('Please select a day of the week (all, Monday, Tuesday, ... , Sunday: ').lower() while day not in ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']: day = input('Incorrect day given! \n' 'Please type in "all" or any day from Monday - Sunday: ').lower() print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['Month'] = df['Start Time'].dt.month df['Day of Week'] = df['Start Time'].dt.day_name() # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['Month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['Day of Week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month if applicable if df['Month'].nunique() > 1: popular_month = df['Month'].mode()[0] months = ['January', 'February', 'March', 'April', 'May', 'June'] popular_month = months[popular_month - 1] print(f'The most popular month to travel is: {popular_month}') # display the most common day of week if applicable if df['Day of Week'].nunique() > 1: popular_day = df['Day of Week'].mode()[0] print(f'The most popular day of the week to travel is: {popular_day}') # display the most common start hour df['Hour'] = df['Start Time'].dt.hour popular_hour = df['Hour'].mode()[0] print(f'The most popular hour of day to travel is: {popular_hour}h\n') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station popular_start_station = df['Start Station'].mode()[0] print(f'The most commonly used start station is: {popular_start_station}') # display most commonly used end station popular_end_station = df['End Station'].mode()[0] print(f'The most commonly used end station is: {popular_end_station}') # display most frequent combination of start station and end station trip df['Trip'] = df['Start Station'] + ' - ' + df['End Station'] popular_trip = df['Trip'].mode()[0] print(f'The most frequent combination of start and end station is: {popular_trip}\n') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time total_travel_time = df['Trip Duration'].sum() print(f'The total travel time for the given time window is: {math.trunc(total_travel_time/3600)} hours') # display mean travel time mean_travel_time = df['Trip Duration'].mean() print(f'The total travel time for the given time window is: {math.trunc(mean_travel_time)} seconds') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types user_types = df['User Type'].value_counts() for row_number in range(0, len(user_types)): print(f'Number of "{user_types.index[row_number]}" type customers: {user_types[row_number]}') # Display counts of gender if gender column exists if 'Gender' in df.columns: genders = df['Gender'].value_counts() print(f'\nNumber of male customers: {genders["Male"]}') print(f'Number of female customers: {genders["Female"]}\n') # Display earliest, most recent, and most common year of birth if birth year column exists if 'Birth Year' in df.columns: earliest_birth_year = int(df['Birth Year'].min()) most_common_birth_year = int(df['Birth Year'].mode()[0]) most_recent_birth_year = int(df['Birth Year'].dropna().tail(1).values[0]) print(f'The earliest customer provided birth year is: {earliest_birth_year}') print(f'The most common customer year of birth is: {most_common_birth_year}') print(f'The birth date of the most recent customer is: {most_recent_birth_year}') print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def raw_data(city): """Displays 5 rows of raw data at the time for the specified city.""" # load raw data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # define starting row for display sample starting_row = 0 # Ask user whether to display raw data, and provide data if answer received is 'yes'. while True: data_request = input('Would you like to see a raw data sample? Enter yes or no. \n') if data_request.lower() == 'no': break elif data_request.lower() == 'yes': print(df[starting_row:(starting_row + 5)]) starting_row += 5 else: print('Type in either "yes" or "no". Please try again.') def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) raw_data(city) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
3f5381b9a889715eb2ca9b1a43ae80a04be223d4
thonwhal/Algoritma-Analizi
/project2/qsort.py
12,643
3.78125
4
import time import random import sys sys.setrecursionlimit(1500000000) def insertionSort(array): # insertion sort function for j in range(1, len(array)): # 10.000 (array length) times loop key = array[j] i = j - 1 while (i > -1) and key < array[i]: # checking values lower or not array[i + 1] = array[i] # transform locations i = i - 1 array[i + 1] = key return array def mergeSort(array): # merge sort function if len(array) > 1: # if it is 1 it cannot split mid = len(array) // 2 # splitting into middle lefthalf = array[:mid] # lefthalf of list righthalf = array[mid:] # righthalf of list # recursion splitting all the list mergeSort(lefthalf) mergeSort(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): # checking sort lower if lefthalf[i] < righthalf[j]: array[k] = lefthalf[i] # make it lefthalf i = i + 1 else: array[k] = righthalf[j] # make it right half j = j + 1 k = k + 1 while i < len(lefthalf): array[k] = lefthalf[i] # make it left half i = i + 1 k = k + 1 while j < len(righthalf): array[k] = righthalf[j] # make it right half j = j + 1 k = k + 1 def partition(arr, low, high): i = (low - 1) # its needed because of changed values pivot = arr[high] # pivot is last value of array for j in range(low, high): if arr[j] <= pivot: i += 1 # increment i by 1 arr[i], arr[j] = arr[j], arr[i] # swap arr[i + 1], arr[high] = arr[high], arr[i + 1] # swap return i + 1 # return value as pi def quickSort(arr, low, high): if low < high: # basic logic need to start algorithm pi = partition(arr, low, high) # pull the value from partition function quickSort(arr, low, pi - 1) # recursion whenever low greater than pi-1 or equal quickSort(arr, pi + 1, high) # recursion again def partition_2(arr, low, high): pivot = arr[low] # this time first value is pivot while True: # because of that continous loop while arr[low] < pivot: low += 1 # increment by 1 until equals to pivot while arr[high] > pivot: high -= 1 # decrement by 1 until equals to pivot if low < high: if arr[low] == arr[high]: # if it is equal return high as pi, or it could be low return high arr[low], arr[high] = arr[high], arr[low] # swap low and high else: return high # return high value as pi def quickSort_2(arr, low, high): # this is second function, first one is pivot if low < high: pi = partition_2(arr, low, high) if pi > 1: quickSort_2(arr, low, pi - 1) # if pi greater than 1, decrement pi by 1 and call the function again if (pi + 1) < high: quickSort_2(arr, pi + 1, high) # increment pi by 1 until its equal to high # ------------------------------------------------------------ # Somehow this method doesn't work on python # ------------------------------------------------------------ def med3(arr, low, high): mid = ((low + high) / 2) mid = int(mid) if arr[mid] < arr[low]: arr[low], arr[mid] = arr[mid], arr[low] if arr[high] < arr[low]: arr[low], arr[high] = arr[high], arr[low] if arr[high] < arr[mid]: arr[mid], arr[high] = arr[high], arr[mid] arr[mid], arr[high - 1] = arr[high - 1], arr[mid] return arr[high - 1] def partition_3(arr, low, high, pi): left = low right = high - 1 while True: while arr[left] < pi: left = left + 1 while arr[right] > pi: right = right - 1 if left >= right: break else: arr[left], arr[right] = arr[right], arr[left] arr[left], arr[right - 1] = arr[right - 1], arr[left] return left def manualSort(arr, low, high): size = high - low + 1 if size <= 1: return if size == 2: if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] return else: if arr[low] > arr[high - 1]: arr[low], arr[high - 1] = arr[high - 1], arr[low] if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low] if arr[high - 1] > arr[high]: arr[high - 1], arr[high] = arr[high], arr[high - 1] def quickSort_3(arr, low, high): size = high - low + 1 if size <= 3: manualSort(arr, low, high) else: med = med3(arr, low, high) partition = partition_3(arr, low, high, med) quickSort_3(arr, low, partition - 1) quickSort_3(arr, partition + 1, high) # ------------------------------------------------------------ def median(a, b, c): # finding median which is a positive value if (a - b) * (c - a) >= 0: return a elif (b - a) * (c - b) >= 0: return b else: # if all negative then return c value return c def partition_median(array, low, high): # Method to partition around the median left = array[low] # left hand right = array[high - 1] # right hand length = high - low # finding length obviously if length % 2 == 0: # this is because of array indicies problem of python3, it was hard to find middle = array[low + int(length / 2) - 1] # saving middle value but integer indicies else: middle = array[int(low + length / 2)] # same but exact middle point pivot = median(left, right, middle) # calling median for saving pivot value, middle pi = array.index(pivot) # only works if all values in array unique it means for example , arr[5} array[pi] = array[low] # swapping ex; arr[arr[5]] with arr[0] --> arr[22] equals arr[0} array[low] = pivot i = low + 1 # incrementation for j in range(low + 1, high): if array[j] < pivot: # swapping them until highest element array[j], array[i] = array[i], array[j] # swap i += 1 array[low], array[i - 1] = array[i - 1], array[low] # swap return i - 1 # return value as pi variable def quicksort_median(array, low, high): # Median of three method if low < high: # basic logic, if it is false there will be nothing to change pi = partition_median(array, low, high) # calling partition method and saving value of pivot quicksort_median(array, low, pi) # recursion quicksort_median(array, pi + 1, high) # recursion suminstime = 0 summertime = 0 sumqtime = 0 sumq2time = 0 sumq3time = 0 x = [] x1 = [] x2 = [] x3 = [] x4 = [] x5 = [] for k in range(1, 6): # for j in range(0, 10000): # its not 100.000 because in python insertion sort is too slow # num = random.randint(1, 2000000) # picking between 1-200000 numbers value into num variable # x.append(num) # adding num value to array with open('originalList' + str(k) + '.txt', 'r') as filehandle: # reading original lists # for listitem in x: # filehandle.write('%s\n' % listitem) for line in filehandle: currentPlace = int(line[:-1]) x1.append(currentPlace) # adding items into array x2.append(currentPlace) # adding items into array x3.append(currentPlace) # adding items into array x4.append(currentPlace) # adding items into array x5.append(currentPlace) # adding items into array n = len(x3) i_start = int(round(time.time() * 1000)) # timer start insertionSort(x1) # sort function start i_stop = int(round(time.time() * 1000)) # timer stop suminstime += (i_stop - i_start) itime = str(i_stop - i_start) # calculate time difference between start and stop time with open('i-seed' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % itime) for listitem in x1: filehandle.write('%s\n' % listitem) m_start = int(round(time.time() * 1000)) # timer start mergeSort(x2) # sort function start m_stop = int(round(time.time() * 1000)) # timer stop summertime += (m_stop - m_start) mtime = str(m_stop - m_start) # calculate time difference between start and stop time with open('m-seed' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % mtime) for listitem in x2: filehandle.write('%s\n' % listitem) q1_start = int(round(time.time() * 1000)) # timer start quickSort(x3, 0, n - 1) q1_stop = int(round(time.time() * 1000)) # timer stop sumqtime += (q1_stop - q1_start) q1time = str(q1_stop - q1_start) # calculate time difference between start and stop time with open('q1-seed' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q1time) for listitem in x3: filehandle.write('%s\n' % listitem) q2_start = int(round(time.time() * 1000)) # timer start quickSort_2(x4, 0, n - 1) q2_stop = int(round(time.time() * 1000)) # timer stop sumq2time += (q2_stop - q2_start) q2time = str(q2_stop - q2_start) # calculate time difference between start and stop time with open('q2-seed' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q2time) for listitem in x4: filehandle.write('%s\n' % listitem) q3_start = int(round(time.time() * 1000)) # timer start quicksort_median(x5, 0, n) q3_stop = int(round(time.time() * 1000)) # timer stop sumq3time += (q3_stop - q3_start) q3time = str(q3_stop - q3_start) # calculate time difference between start and stop time with open('q3-seed' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q3time) for listitem in x5: filehandle.write('%s\n' % listitem) q1_start = int(round(time.time() * 1000)) # timer start quickSort(x3, 0, n - 1) q1_stop = int(round(time.time() * 1000)) # timer stop sumqtime += (q1_stop - q1_start) q1time = str(q1_stop - q1_start) with open('q1-seed-sorted' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q1time) for listitem in x3: filehandle.write('%s\n' % listitem) q2_start = int(round(time.time() * 1000)) # timer start quickSort_2(x4, 0, n - 1) q2_stop = int(round(time.time() * 1000)) # timer stop sumq2time += (q2_stop - q2_start) q2time = str(q2_stop - q2_start) with open('q2-seed-sorted' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q2time) for listitem in x4: filehandle.write('%s\n' % listitem) q3_start = int(round(time.time() * 1000)) # timer start quicksort_median(x5, 0, n) q3_stop = int(round(time.time() * 1000)) # timer stop sumq3time += (q3_stop - q3_start) with open('q3-seed-sorted' + str(k) + '.txt', 'w') as filehandle: # write sorted list into txt file filehandle.write('%s ms..\n' % q3time) for listitem in x5: filehandle.write('%s\n' % listitem) print("Sorted array is:\n") print(x1) print(x2) print(x3) print(x4) print(x5) x = [] # these are for remove values from array because quick sort cant work without it x1 = [] x2 = [] x3 = [] x4 = [] x5 = [] a1 = "Average of insertion sort :" + str(suminstime / 5) + "\n" a2 = "Average of merge sort :" + str(summertime / 5) + "\n" a3 = "Average of quick sort 1 :" + str(sumqtime / 5) + "\n1" a4 = "Average of quic sort 2 :" + str(sumq2time / 5) + "\n" a5 = "Average of quick sort 3 :" + str(sumq3time / 5) + "\n" with open('statistics.txt', 'w') as filehandle: # write statistics list into txt file filehandle.write(a1) filehandle.write(a2) filehandle.write(a3) filehandle.write(a4) filehandle.write(a5)
b2939b6b41e11c4d33b3e6127b90ba04d5686aa3
velvet-2428/Lauchpad-Assignments
/problem3.py
155
3.71875
4
def rem(dup): list=[] for num in dup: if num not in list: list.append(num) return list dup=[1,2,2,3,4,4,5,6,7,7,8,9] print(rem(dup))
7b9a2642641246ec32dc5b16b9015d6ad311dfca
nicolegates/CS342
/set2ch9.py
1,140
3.796875
4
# pads message with PKCS#7 format with given block size def padPKCS7(message, block_size): # if the length of the given message is already equal to the block size, don't pad if len(message) == block_size: return message # otherwise compute the padding byt, pad the message, and return it ch = block_size - len(message) % block_size return message + bytes([ch] * ch) # checks if a message is padded def isPadded(binData): # take what we expect to be the padding by removing the message padding = binData[-binData[-1]:] # check that all the bytes in the range indicated by the padding are equal to the padding value itself return all(padding[b] == len(padding) for b in range(0, len(padding))) # unpads a message and returns it def unpadPKCS7(data): if len(data) == 0: raise Exception("The input data must contain at least one byte") if not isPadded(data): return data padding_len = data[len(data) - 1] return data[:-padding_len] def main(): message = b"YELLOW SUBMARINE" b = padPKCS7(message, 20) print(b) if __name__ == "__main__": main()
d562fc2499e6a84e433831975e68dc179b919bf8
sebasvj12/listasPython
/listas.py
439
3.65625
4
''' Created on 20/02/2017 @author: Casper ''' def fun(p1,p2,p3): if len(p1)==1 and len(p2)==1 and len(p3)==1: return p1+","+p2+","+p3 else: if p1[0]<p[len(p)-1]: return fun(p1[0],p2,p3) print("menores numeros de varis listas") lista1= raw_input("Ingrese lista 1: ") lista2= raw_input("Ingrese lista 2: ") lista3= raw_input("Ingrese lista 3: ") print fun(lista1,lista2,lista3)
9b46d1e08ea5eb6c128399434509361f075d5b5e
dangerous1234/print-pattern
/increment_pattern.py
154
3.71875
4
for i in range(4): for j in range(i+1): print("#",end=" ") print() for k in range(4): for l in range(4-k): range(4) print()
3ad75bebc34572759149b5a3aff62ec8d7e63396
YasminTorresMora/mi-proyecto
/codigo/seguridad.py
3,274
3.609375
4
import random def nuevo_usuario(): try: print("") print("") print(" PROGRAMA ESTADISTICA DESCRIPTIVA") print(" =================================") print(" Registro de Usuario y Clave") print("") usuario=input(" Nuevo Usuario: ") clave = input(" Nueva Clave : ") print("") usuario=usuario+"\n" clave=clave+"\n" f = open('acceso.txt','w') f.write(usuario) f.write(clave) f.close() except: print ("No pudo crear el archivo txt en su carpeta.") def validar_usuario(usuario0,clave0): global adivina global sesion reg=0 #try: f = open ('acceso.txt','r') for linea in f: reg+=1 if reg==1: usuario=linea if reg==2: clave=linea f.close() if usuario0+"\n"==usuario and clave0+"\n"==clave: sesion="paso" return sesion def adivinanzas(): print("") print(" Para verificar que eres una persona") print(" Resuelve la siguiente adivinanza") print(" con un numero de 1 a 10.") print("") adv=["_","Si soy el ganador, ¿Qué número soy?", "Tengo forma de patito, arqueado y redondito. Quién soy?", "¿Cuántos lados tiene el triángulo equilátero?", "¿Cuántas patas tiene un gato siamés?", "Soy más de cuatro sin llegar a seis, ¿Quién soy?", "Si le sumas su hermano gemelo el tres, ¿Qué número es?", "¿Cuántos días tiene la semana?", "¿Qué número se convierte en cero si le quitas la mitad?", "¿La novena navideña por cuantos días se hace?", "¿Tengo diez manzanas si las parto a la mitad, cuantas manzanas tengo?"] azar = random.randint(1, 10) print(" *** ",adv[azar], end=" ") xadv=int(input("")) if xadv==azar: return True else: return False def concedido(): global adivina global sesion print("") print("") print(" 🔣 ESTADISTICA DESCRIPTIVA 🔢") print(" =================================") print("") print(" 1-Usuario Registrado, 2-Usuario Nuevo",end=" ") regnue=int(input("")) if regnue==1: usuario0=input(" Digite su usuario: ") clave0=input (" Digite su clave : ") sesion=validar_usuario(usuario0,clave0) if sesion=="paso": adivina=adivinanzas() if adivina==True: print(" BIENVENIDO ✅") print("") x=input(" Oprima Enter para continuar.") if sesion!="paso": print(" Acceso Denegado") x=input(" Oprima Enter para continuar.") iterar1=False adivina=False if regnue==2: try: nuevo_usuario() print("") print("Reingrese con su nuevo USUARIO y CLAVE") x=input(" Oprima Enter para continuar.") except: print("") print (" Registre su usuario y contraseña.") print (" Menú Principal, opcion 2 cambiar contraseña") return adivina
7a452f765545daace2d07e255254fa9bd81250e0
filipAnt/alien_invasion
/alien.py
1,139
3.625
4
import pygame from pygame.sprite import Sprite class Alien(Sprite): """Class that represent single alien object""" def __init__(self, ai_game): """Initialize aliena and start location""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings # Load image self.image = pygame.image.load('alien.bmp') self.rect = self.image.get_rect() # Load new alien at the top self.rect.x = self.rect.width self.rect.y = self.rect.height # Store alien position self.x = float(self.rect.x) def update(self): """Move alien right""" self.x += self.settings.alien_speed self.rect.x = self.x def check_edges(self): """Returns True if alien is on the edge of screen""" screen_react = self.screen.get_rect() if self.rect.right >= screen_react.right or self.rect.left <= 0: return True def update(self): """Move alien to left or right""" self.x += (self.settings.alien_speed * self.settings.fleet_direction) self.rect.x = self.x
7065d348fa20871e65569968f68a9b9f0ad719da
Fixdq/python-learn
/day19/blog.py
1,164
3.734375
4
#!/usr/bin/env python3 # encoding: utf-8 # by fixdq # 定义一个People类 class People: country = 'China' def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def run(self): print('%s is running' % self.name) # 实例化三个对象 people1 = People('fixd01', 18, 'male') people2 = People('fixd02', 25, 'male') people3 = People('fixd03', 30, 'male') # 调用 run()方法 people1.run() people2.run() people3.run() # 查看run 的内存地址 print(people1.run) print(people2.run) print(people3.run) # # 实例化三个对象 people1 = People('fixd01', 18, 'male') people2 = People('fixd02', 25, 'male') people3 = People('fixd03', 30, 'male') # 查看country属性对应的 内存地址 print(id(People.country)) print(id(people1.country)) print(id(people2.country)) print(id(people2.country)) # # 实例化一个对象 obj # obj = People('fixd',18,'male') # # # print(obj.name) #查看 属性name的值 # obj.education='哈佛' # 添加属性 # del obj.name # 删除属性 # obj.age=19 # 修改属性值 # print(obj.__dict__) # 查看实例化对象的名称空间
270208ced7228b38c8c090ea9f62a590c519f133
Fixdq/python-learn
/day14/blog.py
484
3.546875
4
# encoding: utf-8 # by fixdq # variable = [out_exp_res for out_exp in input_list if out_exp == 2] # out_exp_res:  列表生成元素表达式,可以是有返回值的函数。 # for out_exp in input_list:  迭代input_list将out_exp传入out_exp_res表达式中。 # if out_exp == 2:  根据条件过滤哪些值可以。 var =[item for item in range(10) if item % 2 == 0] print(var) gen=('egg%s' %i for i in range(10) if i > 5) print(gen) print(list(gen))
85ac79cc496e784f44bc8f591f2182acd573206c
Fixdq/python-learn
/day19/dog_bite_person.py
929
3.765625
4
#!/usr/bin/env python3 # encoding: utf-8 # by fixdq class Person: def __init__(self, name, agg, health=100): self.name = name self.agg = agg self.health = health def bite(self, enemy): enemy.health -= self.agg print('人:%s bite 狗:%s 品种:%s 伤害:%s 狗剩余生命:%s' % (self.name, enemy.name, enemy.breed, self.agg, enemy.health)) class Dog: def __init__(self, name, agg, breed, health=100): self.name = name self.breed = breed self.agg = agg self.health = health def bite(self, enemy): enemy.health -= self.agg print('狗:%s 品种:%s bite 人:%s 伤害:%s 狗剩余生命:%s' % (self.name, self.breed, enemy.name, self.agg, enemy.health)) p = Person(name = 'Yxx', agg = 5) d = Dog(name = 'Yxx', agg = 10, breed='雪中豹') while True: p.bite(d)
cb60260754185413848dbc625c395f5eea52ebd8
leaffan/geo
/misc/custom_coordinates.py
4,248
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: custom_coordinates.py # Author: Markus Reinhold # Contact: leaffan@gmx.net # Creation Date: 2012/03/28 11:44:54 u""" Classes to represent geographic coordinates using components of degrees, minutes, and seconds. A convenient way to add dms coordinates as well as to substract them from each other is added by corresponding overloaded operators. TODO: - add constraints, i.e. latitude necessarily smaller than 90 degrees - allow for hemisphere changes """ import decimal as libdecimal from decimal import Decimal as D class GeographicCoordinates(object): def __init__(self, latitude = None, longitude = None): if latitude is None: self.latitude = DMSCoordinate(0, 0) else: self.latitude = latitude if longitude is None: self.longitude = DMSCoordinate(0, 0) else: self.longitude = longitude def __str__(self): return "[%s / %s]" % (self.latitude.__str__(), self.longitude.__str__()) class DMSCoordinate(object): def __init__(self, degrees, minutes, seconds = 0, hemisphere = ''): self.degrees = degrees self.minutes = minutes self.seconds = seconds if len(hemisphere) == 1 and hemisphere.upper() in ['N', 'S', 'E', 'W']: self.hemisphere = hemisphere.upper() else: self.hemisphere = None @classmethod def from_decimal(self, decimal_degrees, hemisphere = ''): degrees = D(int(decimal_degrees)) decimal_minutes = libdecimal.getcontext().multiply((D(str(decimal_degrees)) - degrees).copy_abs(), D(60)) minutes = D(int(decimal_minutes)) seconds = libdecimal.getcontext().multiply((decimal_minutes - minutes), D(60)) return DMSCoordinate(degrees, minutes, seconds, hemisphere) @classmethod def to_decimal(self, degrees, minutes, seconds): decimal = D(0) deg = D(str(degrees)) min = libdecimal.getcontext().divide(D(str(minutes)), D(60)) sec = libdecimal.getcontext().divide(D(str(seconds)), D(3600)) if (degrees >= D(0)): decimal = deg + min + sec else: decimal = deg - min - sec return libdecimal.getcontext().normalize(decimal) def convert_to_decimal(self): return DMSCoordinate.to_decimal(self.degrees, self.minutes, self.seconds) def __str__(self): output = "%03g°%02g'%02g\"" % (self.degrees, self.minutes, self.seconds) if self.hemisphere is not None: output = "%s%s" % (output, self.hemisphere) return output def __add__(self, other): sum_seconds = self.seconds + other.seconds minute_overflow = 0 while sum_seconds >= 60: sum_seconds -= 60 minute_overflow += 1 sum_minutes = self.minutes + other.minutes + minute_overflow degree_overflow = 0 while sum_minutes >= 60: sum_minutes -= 60 degree_overflow += 1 sum_degree = self.degrees + other.degrees + degree_overflow return DMSCoordinate(sum_degree, sum_minutes, sum_seconds, self.hemisphere) def __sub__(self, other): diff_seconds = self.seconds - other.seconds minute_overflow = 0 while diff_seconds < 0: diff_seconds += 60 minute_overflow += 1 diff_minutes = self.minutes - other.minutes - minute_overflow degree_overflow = 0 while diff_minutes < 0: diff_minutes += 60 degree_overflow += 1 diff_degree = self.degrees - other.degrees - degree_overflow return DMSCoordinate(diff_degree, diff_minutes, diff_seconds, self.hemisphere) if __name__ == '__main__': dms = DMSCoordinate.from_decimal(12.232323) print dms print dms.convert_to_decimal() print DMSCoordinate.to_decimal(dms.degrees, dms.minutes, dms.seconds) latlon = GeographicCoordinates(DMSCoordinate.from_decimal(52, 'n'), DMSCoordinate(12, 30, hemisphere = 'e')) print latlon
7bc040b7b3248290d4ac3be08714189e57e737a1
Win-Victor/algs
/algs_3_t4.py
701
3.828125
4
"""4. Определить, какое число в массиве встречается чаще всего.""" import random SIZE = 10 MIN_ITEM = -1 MAX_ITEM = 52 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array) max_count = 0 max_number = None for i in range(MIN_ITEM, MAX_ITEM + 1): i_sum = array.count(i) if i_sum > max_count: max_count = i_sum max_number = i if max_count == 1: print("Ни одно число не встречается в этом массиве более 1 раза") else: print(f'Цифра {max_number} встечается в массиве чаще всего, а именно {max_count} раз(а)')
5f21ab9fdf6d7bab8a4572054ca007bc62db42d8
Win-Victor/algs
/algs_2_t8.py
835
4.1875
4
"""8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.""" num = input('Введите цифру для подсчета в наборе чисел:\n') count = int(input('Укажите сколько наборов чисел Вы будете вводить:\n')) my_count = 0 my_sum = 0 while my_count != count: my_count += 1 numbs = input(f'Введите {my_count} число:\n') my_sum += numbs.count(num) print(f'Цифра {num} встречалась во введенных числах {my_sum} раз(а).')
18e723be3886ae08f3d2be8bebf3c6eebd9ece07
taylorschimek/treehouse_projects
/fighting_game/game.py
2,959
3.671875
4
import sys from character import Character from monster import Dragon from monster import Goblin from monster import Troll class Game: def setup(self): self.player = Character() self.monsters = [ Goblin(), Troll(), Dragon() ] self.monster = self.get_next_monster() def get_next_monster(self): try: return self.monsters.pop(0) except IndexError: return None def monster_turn(self): print("Monster's Turn!!") if self.monster.attack(): print("A {} is attacking!".format(self.monster)) if input("Dodge? [Y/n] ").lower() != 'n': if self.player.dodge(): print("Your dodge was successful!") print(self.player) else: self.player.hitPoints -=1 #exercise print("You got hit anyway!") print(self.player) else: self.player.hitPoints -= 1 print("You lost one hit point!") print(self.player) else: print("The {} isn't attacking.".format(self.monster)) def player_turn(self): print("Your turn") action = input("Do you want to [A]ttack, [R]est, or [Q]uit? ").lower() if action in 'arq': if action == 'a': if self.player.attack(): print("You attack successfully!") if self.monster.dodge(): print("The {} dodged the attack!".format(self.monster)) else: if self.player.leveledUp(): self.monster.hitPoints -= 2 else: self.monster.hitPoints -= 1 print("You hit {} with your {}!".format(self.monster, self.player.weapon)) else: print("Your attack missed.") elif action == 'r': self.player.rest() else: print("Bye") sys.exit() else: return player_turn() def cleanup(self): if self.monster.hitPoints <= 0: self.player.experience += self.monster.experience print("You killed {}!".format(self.monster)) self.monster = self.get_next_monster() def __init__(self): self.setup() while self.player.hitPoints and (self.monster or self.monsters): print('\n'+'='*20) print(self.player) self.monster_turn() print('-'*20) self.player_turn() self.cleanup() print('\n'+'='*20) if self.player.hitPoints: print("You win!") elif self.monsters or self.monster: print("You lose!") sys.exit() Game()
a15708f29f98d9c1a87029cddd54d6e02f9dfdb5
Laxous/yoyo_sele
/PycharmProjects/jiChu/test02.py
135
3.5625
4
# coding=utf-8 print("hello world") a = 'True' b = True c = str(b) d = bool(a) if b == d and a == c: print("pass") else: pass
7f35763a82a16c63edf07788c122e805992d5323
navacaty/PLFinalProject_rd
/PLFinalProject-master/Part1/.idea/Onlystring.py
298
3.625
4
def Onlystring(values): def is_string(value): try: return value == str(value) except: return False def make_sent(value): return value + "is a string item" for item in values: if is_string(item): print(make_sent(item))
53a1fc67914d8245c66296937b8b126357401f95
dinidininta/arkademy-bootcamp-2
/Nomor5.py
395
4.03125
4
def ganti(string, charA, charB): newstring = "" if charA not in string: newstring = "charA tidak terdapat pada string yang dimasukkan" else: for char in string: if char == charA: newstring += charB else: newstring += char return newstring if __name__ == '__main__': print ganti("kelompok", "k", "u")
a052610e5fd5032cd1a479121704f1dc354f2068
VigneshJanarthanan/DataScience_Assignment4
/2.1-List_OF_WORDS-to_LIST_OF_INTEGER.py
242
3.921875
4
def len_words(k): length=[] for i in range(len(k)): x=len(k[i]) length.append(int(x)) return length lst=["Vignesh","Janarthanan","ACADGILD","MACHINELEARNING"] print("Length of each word given",len_words(lst))
e5d83b472451facb2a6f38a174e0c8c760bc0182
avir100/ConsultAdd
/task2/task2_2.py
2,005
4
4
''' Write a program in Python to perform the following operator based task: Ask user to choose the following option first: If User Enter 1 - Addition If User Enter 2 - Subtraction If User Enter 3 - Division If USer Enter 4 - Multiplication If User Enter 5 - Average Ask user to enter the 2 numbers in a variable for first and second for the first 4 options mentioned above. Ask user to enter two more numbers as first and second2 for calculating the average as soon as user choose an option 5. At the end if the answer of any operation is Negative print a statement saying “NEGATIVE” NOTE: At a time user can perform one action at a time. ''' def secondinput(choice): while True: try: first, second = map(float, raw_input("Please enter 2 numbers seperated by a space \n").split()) break except ValueError: print ("Invalid input, please try again \n") if choice == "1": return (first+second) if choice == "2": return (first-second) if choice == "3": return (first/second) if choice == "4": return (first*second) if choice == "5": return ((first+second)/2) menu = {} menu['1'] = "Addition" menu['2'] = "Subtraction" menu['3'] = "Division" menu['4'] = "Multiplication" menu['5'] = "Average" while True: options = menu.keys() options.sort() print ("MENU:") for entry in options: print entry, menu[entry] choice = raw_input("Please choose an option from the menu: \n") if choice =='1': ans = secondinput(choice) if ans < 0: print ("NEGATIVE") print (ans) break elif choice == '2': ans = secondinput(choice) if ans < 0: print ("NEGATIVE") print (ans) break elif choice == '3': ans = secondinput(choice) if ans < 0: print ("NEGATIVE") print (ans) break elif choice == '4': ans = secondinput(choice) if ans < 0: print ("NEGATIVE") print (ans) break elif choice == '5': ans = secondinput(choice) if ans < 0: print ("NEGATIVE") print (ans) break else: print "Invalid input, please try again"
dfa668f57584dc42dbc99c5835ebc0a5c0b1e0cd
avir100/ConsultAdd
/task2/task2_10.py
815
4.125
4
from random import randint ''' Write a program that asks five times to guess the lucky number. Use a while loop and a counter, such as counter=1 While counter <= 5: print(“Type in the”, counter, “number” counter=counter+1 The program asks for five guesses (no matter whether the correct number was guessed or not). If the correct number is guessed, the program outputs “Good guess!”, otherwise it outputs “Try again!”. After the fifth guess it stops and prints “Game over!”. ''' counter = 1 answer = randint(1,10) print "Answer: ", answer while counter <= 5: number = int(raw_input("Guess the lucky number between 1-10: \n")) if (number == answer): print ("Good guess!") else: if counter == 5: print ("Game over!") else: print ("Try again!") counter += 1
0386d42dfae2e6489d916e10af178dd42a31cf26
TimeMachine00/pythonProject-4
/Chose-rock-paper-scissor.py
871
4.21875
4
print("created by hussainatphysics@gmail.com(hussainsha syed)") print("welcome to the game") rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' import random choice = int(input("what would you like to choose? 0 for rock, 1, paper, 2 for scissors\n")) a =[rock, paper, scissors] b= random.randint(0,len(a)-1) print(b) c=a[b] # print(c) if b==choice: print(c) print("you win the game") else: print(c) print("you lost the game, computer wins") print() but1= print(input("press enter for bye...........")) # l = random.choice(a) # print(l) # # if a.index(l)==choice: # print('you won') # else: # print('you lost')
1e3cd8b551a842059e58859e0513e053ebb260d0
goodcheer/songorithm
/medium/week1/binary-tree-inorder-traversal_32ms_14mb.py
1,482
4.0625
4
class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """solution from https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ """ def inorderTraversal(self, root: TreeNode) -> List[int]: current = root stack = [] # initialize stack values = [] while True: # Reach the left most Node of the current Node if current is not None: # Place pointer to a tree node on the stack # before traversing the node's left subtree stack.append(current) current = current.left # BackTrack from the empty subtree and visit the Node # at the top of the stack; however, if the stack is # empty you are done elif(stack): current = stack.pop() values.append(current.val) # We have visited the node and its left # subtree. Now, it's right subtree's turn current = current.right else: break return values if __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) ans = Solution.inorderTraversal(root) assert ans == [4, 2, 5, 1, 3]
ed7d751da810e5d831e3488c5d7ab8cd1849440e
goodcheer/songorithm
/medium/week1/palindromic-substrings_128ms_14.4mb(expand).py
1,057
3.578125
4
class Solution: def countSubstrings(self, s: str) -> int: def expand(left: int, right: int) -> int: count = 0 while left >= 0 and right < len(s) and s[left] == s[right]: # count the palindrome and expand outward count += 1 print(f"count: {count}, {s}[{left}] {s}[{right}]") left -= 1 right += 1 return count palindromes = 0 for i in range(len(s)): print(i) # the idea is to expand around the 'center' of the string, but the center could be 1 or 2 letters # e.g., babab and cbbd, hence the (i, i) and (i, i + 1) print(f"expand({i},{i})") palindromes += expand(i, i) print(f"expand({i},{i+1})") palindromes += expand(i, i+ 1) return palindromes if __name__ == "__main__": sol = Solution() in_put = "aaa" assert sol.countSubstrings(in_put) == 6 print("pass")
906ad6a68acfc1755487f52ac01b2612db2b10b4
ateeqmughal266/Python-Assignment
/Python Assignment3.py
1,074
3.765625
4
val1=int(input("Enter a number:")) val2=int(input("Enter a number:")) operand=str(input("Enter operand:")) if operand=="+": result=val1+val2 print(result) elif operand=="-": result=val1-val2 print(result) elif operand=="*": result=val1*val2 print(result) elif operand=="/": result=val1/val2 print(result) elif operand=="**": result=val1**2 print(result) list1=["ateeq",19,"mughal"] for i in list1: if type(i)==int: print(i) dict={} dict["name"]="ateeq" print(dict) list1=["ateeq",19,"mughal","bla bla","javed","ateeq mughal"] for i in range(0,len(list1)): if list1[i] in list1[i+1:]: print (list1[i]) print(list1[i],list1[i+1:]) dict1={'name':'ateeq','address':'saudabad','occupation':'student'} key=input("enter key :") if key in dict1.keys(): print("{} already exists".format(key)) dict1={1:'ateeq',2:6,3:'student'} sum=0 for i in dict1.keys(): if type(i)==int: print(i) sum+=i if type(dict1[i])==int: print(dict1[i]) sum+=i print(sum)
76c2eb4bd642b6af3826514cf05fd481867fe9b7
gxu12/Leetcode
/剑指Offer/7 前序中序推导二叉树.py
1,776
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 12 00:55:01 2020 @author: xuguiming """ # 根据前序以及中序 推出二叉树 # 1. 递归 def buildTree(preorder,inorder): if len(preorder) == 0: return None ind = inorder.index(preorder[0]) root = TreeNode(preorder[0]) #ind表示左子树有多少个元素,所以这里是从1到ind+1 left = buildTree(preorder[1:ind+1],inorder[:ind]) right = buildTree(preorder[ind+1:],inorder[ind+1:]) root.left = left root.right = right return root # 2. 分治思想 from typing import List class Solution: def __init__(self): self.preorder = None self.reverses = None def buildTree(self,preorder,inorder): pre_size = len(preorder) in_size = len(inorder) if pre_size != in_size: return None self.preorder = preorder self.reverses = dict() for i in range(in_size): self.reverses[inorder[i]] = i return self.__build_tree(0,pre_size-1,0,in_size-1) def __build_tree(self,pre_left,pre_right,in_left,in_right): if pre_left > pre_right or in_left > in_right: return None pivot = self.preorder[pre_left] root = TreeNode(pivot) pivot_index = self.reverses[pivot] root.left = self.__build_tree(pre_left + 1, pivot_index - in_left + pre_left, in_left, pivot_index - 1) root.right = self.__build_tree(pivot_index - in_left + pre_left + 1, pivot_index + 1, in_right)
34f95d8f063fc886569aa4b890f20beca8f19881
Awesomeplayer165/Bagels-Game-with-Python
/main.py
544
3.8125
4
# main.py secretNumber = "345" numberOfGuesses = 0 while numberOfGuesses != 10: userInput = input("Enter a 3 digit number: ") if len(userInput) != 3: print("Enter a 3 digit number and try again"); continue for index, char in enumerate(userInput): if char in secretNumber and secretNumber[index] == char: print("Fermi") elif char in secretNumber and secretNumber[index] != char: print("Pico") else: print("Bagels") if secretNumber == userInput: print("You got it!"); exit() numberOfGuesses += 1 print("Out of guesses")
9dc68b9e209f9810bc12836c0114ba18232b72e4
jake-welch/102-Lab
/Week12-utlilities.py
1,822
3.53125
4
def PrintOutput(words): print("OUTPUT",words) def LoadFile(fileName): newList = [] file = open(fileName,'r') lines = file.readlines() for i in lines: newList.append(i[0:-1]) return newList def UpdateString(daString,letter,index): newString = '' a = 0 for i in daString: if a != index: newString += i else: newString += letter a += 1 print(newString) def FindWordCount(someList, word): counter = 0 newList = [] for i in someList: newList.append(i.split()) for i in newList: for a in i: if a.lower() == word.lower(): counter += 1 PrintOutput(counter) def ScoreFinder(players, scores, name): a = 0 true = 0 score = 0.0 output = '' for i in players: if i.lower() == name.lower(): true = 1 break a += 1 if true == 1: score = scores[a] output = (players[a] + ' got a score of ' + str(score)) PrintOutput(output) else: PrintOutput('player not found') def Union(listOne,listTwo): newList = [] newList = listOne for i in listTwo: b = 1 for a in listOne: if a == i: b = 0 if b == 1: newList.append(i) PrintOutput(newList) def Intersection(listOne,listTwo): newList = [] for i in listTwo: b = 1 for a in listOne: if a == i: b = 0 if b == 0: newList.append(i) PrintOutput(newList) def NotIn(listOne,listTwo): newList = [] for i in listOne: b = 1 for a in listTwo: if a == i: b = 0 if b == 1: newList.append(i) PrintOutput(newList)
b57312d8128cc79a9360310526bd92fa765a8208
min0201ji/PythonStudy
/Ch03/data_type/01_data_type.py
277
4
4
# 정수 : int num = 100 print(num, type(num)) # 실수 : float PI = 3.14 print("PI :", type(PI)) # 문자옇 : str name = '박민지' print("name: ", type(name)) # bool done = True print("done: ", type(done)) # 변수의 자료형 a = 100 #class int a = 'hello' #class str
13cd9031d52ae07813bf35993350d2d1b94d27a1
min0201ji/PythonStudy
/Ch03/파이썬내장함수/02_lambda식.py
805
3.625
4
# 7월6일(화) - 2교시 # 람다 식 : lambda - 교재 pp123 # # lambda : 실행 시(런타임) 생성해서 사용할 수 있는 익명 함수 # # 익명함수 : 이름이 없는 함수 # # 입력과 출력이 있는 간단한 한 행짜리 함수를 만들 때 사용 # # 같은 함수를 def 문으로 정의할 때보다 간결 # # 형식 : lambda 매개변수 : 표현식(lambda 매개변수 : 리턴값) ## 두개의 정수를 인수로 입력받아 더한결과를 출력하는 함수: 함수명 add(a,b) # def로 정의한 함수 def add(a,b): return a+b print(add(3,5)) # 람다식으로 표현 (lambda a,b:a+b)(3,5) print((lambda a,b:a+b)(3,5)) # 람다식(함수)를 변수에 할당하여 재사용 lambda_add=(lambda a,b:a+b) print(lambda_add(3,5)) print(lambda_add(10,20))
e3772c13fdd37954538cdd1756e764d5dbbb6964
min0201ji/PythonStudy
/Ch03/tuple_dict_set/03_set연산.py
342
3.734375
4
A = {1,2,3} B = {3,4,5,6} # 합집합 - 반환결과 집합 #a|b print(A|B) # a.union(b) print(A.union(B)) print('===================') # 교집합 - 반환결과 집합 # a&b print(A&B) # a.intersection(b) print(A.intersection(B)) print('===================') # 차집합 # a-b print(A-B) # a.difference(b) print(A.difference(B))
f22e40906f45e94bdb50b79d8901c729dd0b9c79
min0201ji/PythonStudy
/Ch03/If/06_if_ex4.py
252
3.828125
4
x = int(input('정수1 입력: ')) y = int(input('정수2 입력: ')) z = int(input('정수3 입력: ')) if x>y and x>z: print('제일 큰 수 : %d' %x) elif y>x and y>z: print('제일 큰 수 : %d' %y) else: print('제일 큰 수: %d' %z)
c454288efe670d46e8b99e1f9a1130f1e2e08888
min0201ji/PythonStudy
/Ch03/while/while_ex2.py
198
3.65625
4
# while 연습문제2 """ sum = int(input('마지막 숫자를 입력 하시오: ')) i = 0 #초기변수 sum = 0 #누적 변수 while i <= sum: if i % 2 == 1: sum += i i += 1 """
b9ae1ed388af01992a89da01a5716bbf1046e886
min0201ji/PythonStudy
/Ch03/for/for_ex5.py
387
4.09375
4
# 다중 for문을 사용하여 다음과 같이 출력 for y in range(3): for x in range (1,5): print(x, end=' ') print() """ a = 0 for i in range(3): # a += 1 # 이 문장의 수행 횟수는? 3회 for j in range(4): a += 1 # 이 문장의 수행 횟수는? 12회 print(a, end="\t") a += 1 # 최종 a의 값은? 12회 print() """
51468ec7f20605b55b79b85a252d6839c9f579cf
min0201ji/PythonStudy
/Ch03/variable/06_constant.py
605
3.515625
4
# 상수 # 값이 변경되지 않는 값 # 파이썬에서는 별도의 상수가 없음 # 변수와 구분하기 위해 대문자로 사용할 뿐 # 나중에 상수의 값을 변경해도 오류 없음 PI = 3.141592 r = 10 area = r*r*PI print(area) INT_RATE = 0.03 #상수로 사용하기 위해 할당 deposit = 10000 interest = deposit * INT_RATE balance = deposit + interest print(balance) print(int(balance)) #int() 정수형변환 함수 # 천단위 구분기호 사용 print(format(int(balance),',')) #format(값, 구분기호) INT_RATE = '이자율' #값을 변결해도 오류 발생 X
f911e48ef0e97acc12b1f7b6c7593ca72df222b5
min0201ji/PythonStudy
/Ch03/class_object/05_classs5_클래스예제.py
1,396
3.796875
4
# 7월6일 (화) 7교시 # 1. 숫자를 하나 증가하는 메서드 # 2. 숫자를 0으로 초기화 하는 메서드 # 3. 숫자를 저장하는 속성(멤버변수) - 생성자 함수 # 4. 현재 숫자값을 출력하는 메서드 class Counter: def __init__(self): self.num = 0 def increment(self): self.num += 1 def reset(self): self.num = 0 def print_current_value(self): print('현재 저장되어 있는 숫자값은: ', self.num) # 객체 생성 c1 = Counter() c2 = Counter() c3 = Counter() # 질문: c1 인스턴스와 c2 인스턴스는 공통의 멤버변수 num을 사용한다. (O, X) # => X (메모리 공간 자체가 다름!) c1.increment() c2.increment() c1.increment() c2.increment() c1.increment() c2.reset() c1.print_current_value() print(c1.num) c2.print_current_value() print(c2.num) print(c3.num) # instance method - 객체로 호출(일반 method) # 메쏘드는 객체 레벨로 호출 되기 때문에, 해당 메쏘드를 호출한 객체에만 영향을 미침 # class method(static method) – @staticmethod 사용 # 클래스 메쏘드의 경우, 클래스 레벨로 호출되기 때문에, 클래스 멤버 변수만 변경 가능 # class Math: @staticmethod def add(a, b): return a + b @staticmethod def multiply(a, b): return a * b Math.add(10, 20) Math.multiply(10, 20)
21d59dd62eba9465bb961ae6ef9d030ddf5b302e
min0201ji/PythonStudy
/Ch03/string/isalpha_ex.py
658
3.90625
4
# print(input('문장을 입력하세요 : ')) # 알파벳: """ #선생님 강의 #count 누족변수 초기화 alphas=digits=space=others=0 #문장을 입력받는 코드 string=input('문자를 입력하세요: ') # 입력된 문장을 하나씩 추출해서 판단하는 코드 for c in string: #print(c) # c변수에 한 문자씩 대입 if c.isalpha(): #c.isalpha()==True alphas = alphas + 1 elif c.isdigit(): digits += 1 elif c.isspace(): spaces += 1 else: others += 1 print('문자: %d개' %alphas) print('숫자: %d개' %digits) print('공백: %d개' %spaces) print('기타: %d개' %others) """
69b4ba23342c953f99a48ba5dbadd2dd841ced87
min0201ji/PythonStudy
/Ch03/function/function_ex1.py
380
3.890625
4
# 연습 문제 1 def sum(): num1 = int(input('숫자1 입력: ')) num2 = int(input('숫자2 입력: ')) return num1 + num2 total = sum() print('합: %d' %total) """ 7월2일(금) - 4교시_7월1일 연습문제 풀이 def sum(): num1 = int(input('숫자1 입력: ')) num2 = int(input('숫자2 입력: ')) print('합: %d' %(num2 + num1)) sum() """
214a5b7fb87d1986870cc699f5105c955e2588a6
min0201ji/PythonStudy
/Ch03/function/function_ret_param_ex1.py
422
3.875
4
# 7월2일(금) - 5교시_7월1일 연습문제 풀이 # 사칙 연산 함수 작성 def add(a,b): return a + b def sub(a,b): return a - b def mul(a,b): return a * b def div(a,b): return a / b ## 함수 호출 테스트 ## x = 9 y = 3 print('%d + %d = %d' % (x,y, add(x,y))) print('%d - %d = %d' % (x,y, sub(x,y))) print('%d * %d = %d' % (x,y, mul(x,y))) print('%d / %d = %d' % (x,y, div(x,y)))
07ebec8b82420cd301417d7ebcbbe8b6a004ba8a
meridiani/AoC-2017
/day01/answer.py
909
3.734375
4
### Maria Duffy ### My solution to Day 1 - Advent of Code from numpy import * ### First read in the numbers myFile = open('myList.txt','r') myString = myFile.read() myFile.close() stringLength = len(myString) ### Fix the file so it has no extra character at some point if (myString[0]==myString[-2]): print "Oh no first and last match!" sum = 0 for x in arange(1,stringLength): if (myString[x-1]==myString[x]): sum = sum + int(myString[x]) sum = sum + int(myString[0]) else: print "No circles here thank goodness!" print "First is: ", myString[0], "Last is: ", myString[-1] ### How to make it a circular list? ### maybe break into two strings at a point where they aren't the same then ### rejoin at so first and last def not the same ### loop through list and find repeats ### and these to a list ### sum the numbers ### print to screen print "The answer is: ", sum print "OK to go!"
ad0f8266f9f088212769b638ef2e1fb74ebb1b89
metshein/python
/it19_if_laused.py
668
3.84375
4
tehtemark = input(''' Palun vali õige tehtemärk: + liitmiseks - lahutamiseks * korrutamiseks / jagamiseks ''') number_1 = int(input('Esimene number: ')) number_2 = int(input('Teine number: ')) if tehtemark == '+': print('{} + {} = '.format(number_1, number_2)) print(number_1 + number_2) elif tehtemark == '-': print('{} - {} = '.format(number_1, number_2)) print(number_1 - number_2) elif tehtemark == '*': print('{} * {} = '.format(number_1, number_2)) print(number_1 * number_2) elif tehtemark == '/': print('{} / {} = '.format(number_1, number_2)) print(number_1 / number_2) else: print('Sa ei valinud tehtemärki')
8fdb362aa4fb0de01b740a5a840904bf329b5f22
lzeeorno/Python-practice175
/terminal&py.py
696
4.125
4
#how to use python in terminal def main(): while True: s = input('do you come to learn how to open py doc in terminal?(yes/no):') if s.lower() == 'yes': print('cd use to enter doc, ls to look the all file, python filename.py to open the py document') s1 = input('do you understand?(yes/no):') if s1.lower() == 'yes': print('nice, bye') break else: print('ok, come to ask again') break elif s.lower()== 'no': print('ok, goodbye') break else: print('wrong input, please enter yes/no') continue main()
25d6dd3299b1a2785ce8116da56770237ade4776
lzeeorno/Python-practice175
/175 _labs/lab9_q2.py
2,180
3.65625
4
class Student: def __init__(self, student_id, name, mark): self.ID = student_id self.name = name self.mark = mark def __str__(self): return "\nID:{:10} name:{:20} mark:{}".format(str(self.ID), self.name, str(self.mark)) def __repr__(self): return "\nID:{:10} name:{:20} mark:{}".format(str(self.ID), self.name, str(self.mark)) def compareWith(self, other, compare_by='id'): if compare_by not in ['id', 'name', 'mark']: raise Exception('Compare method ['+compare_by+'] is invalid.') if not isinstance(other, Student): raise Exception('Cannot compare with object that\'s not Student class.') # prepare two datas to compare if compare_by == 'id': data1 = self.ID data2 = other.ID elif compare_by == 'name': data1 = self.name data2 = other.name else: data1 = self.mark data2 = other.mark # compare if data1 < data2: return -1 elif data1 == data2: return 0 else: return 1 def selectionSort(alist, compare_by): for fillslot in range(len(alist)-1,0,-1): positionOfMax=0 for location in range(1,fillslot+1): if alist[location].compareWith(alist[positionOfMax], compare_by) == 1: positionOfMax = location temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp if __name__ == '__main__': ### parse student info f = open('input_lab9_Students.txt','r') students = [] while True: line = f.readline() if len(line) == 0: break # end of file line = line.strip() if len(line) == 0: continue # skip blank lines line_list = line.split(',') for i in range(len(line_list)): line_list[i] = line_list[i].strip() new_student = Student(int(line_list[0]), line_list[1], float(line_list[2])) # print(line_list) students.append(new_student) selectionSort(students, 'mark') print(students)
e27ada4c0d14ba5e57f4b9f1059a70d2e18da209
lzeeorno/Python-practice175
/175 _labs/lab1_q2.py
1,294
3.921875
4
f = open('lab1q2_input_earthquake.txt','r') # open the file string = f.read() # read the file list_of_string = string.splitlines() # split the lines between the string and create a list def output(): # create the dictionary of earthquake data # by spliting up the elements inside the list_of_stiring # return the dict line = [] earthquake = {} for elements in list_of_string: # check for each string inside the list C = elements.split() # split the strings line.append(C) for eachList in line: region = eachList[len(eachList)-1] # set the region earthquake[region] = [] # create the dictionary for region in earthquake: for eachList in line: index = 0 if region == eachList[len(eachList)-1]: # check for the region inside eachList date = eachList[index + 1] # set the date magnitude = float(eachList[index]) # set the magnitude attribute = [date,magnitude] # set the attribute earthquake[region].append(attribute) # append the attribute to the values of the dictionary content = [region,*earthquake[region]] print(content) output()
db27825139d554441b2839d702e7a062650a04a5
lzeeorno/Python-practice175
/175_assignments/assignment3.py
8,939
3.8125
4
#assignment3 #Zheng Fuchen (Leon), 1465251 # step 1 import random # import the random for shuffling the cards suits=["D", "C", "H", "S"] ranks=["2","3","4","5","6","7","8","9","0","A","J","Q","K"] while True: filename = input("please enter the game name(shuffleddeck): ") #prompt player to input the game name try: if filename == 'shuffleddeck': f = open('as3_input_shuffledDeck.txt', "r") break except: print("filename is error,please enter again") #prompt user to enter the correct filename continue content = f.read() f.close() shuffled_cards = content.strip().split('\n') #read the shuffledDeck.txt and get the content #validation if len(shuffled_cards) != 52: #avoid the txt file did not have 52 cards raise EXception("total cards not equal 52") for card in shuffled_cards: if len(card)!= 2: #avoid the txt file did not have both suits and ranks print("card format error!") if card[1] not in suits: # cards did not have valid suits raise Exception("cards format error: invalid suit.") if card[0] not in ranks: #cards did not have valid ranks raise Exception("cards format error: invalid ranks.") if shuffled_cards.count(card) != 1: # the cards either lack a suit or lack a rank raise Exception ("card number error: dupilicate card ") # step 2: distributing cards,use circular queue #first of all, we creat a circular queue in a class class CircularQueue: # Constructor, which creates a new empty queue: def __init__(self, capacity): if type(capacity) != int or capacity<=0: raise Exception ('Capacity Error') self.__items = [] self.__capacity = capacity self.__count=0 self.__head=0 self.__tail=0 # Adds a new item to the back of the queue, and returns nothing: def enqueue(self, item): if self.__count== self.__capacity: raise Exception('Error: Queue is full') if len(self.__items) < self.__capacity: self.__items.append(item) else: self.__items[self.__tail]=item self.__count +=1 self.__tail=(self.__tail +1) % self.__capacity # Removes and returns the front-most item in the queue. # Returns nothing if the queue is empty. def dequeue(self): if self.__count == 0: raise Exception('Error: Queue is empty') item= self.__items[self.__head] self.__items[self.__head]=None self.__count -=1 self.__head=(self.__head+1) % self.__capacity return item # Returns the front-most item in the queue, and DOES NOT change the queue. def peek(self): if self.__count == 0: raise Exception('Error: Queue is empty') return self.__items[self.__head] # Returns True if the queue is empty, and False otherwise: def isEmpty(self): return self.__count == 0 # Returns True if the queue is full, and False otherwise: def isFull(self): return self.__count == self.__capacity # Returns the number of items in the queue: def size(self): return self.__count # Returns the capacity of the queue: def capacity(self): return self.__capacity # Removes all items from the queue, and sets the size to 0 # clear() should not change the capacity def clear(self): self.__items = [] self.__count=0 self.__head=0 self.__tail=0 # Returns a string representation of the queue: def __str__(self): str_exp = "]" i=self.__head for j in range(self.__count): str_exp += str(self.__items[i]) + ", " i=(i+1) % self.__capacity return str_exp + "]" # # Returns a string representation of the object CircularQueue def __repr__(self): return str(self.__items) + " H=" + str(self.__head) + " T="+str(self.__tail) + " ("+str(self.__count)+"/"+str(self.__capacity)+")" capicity = 52 #we should have 52 cards,so the capicity is 52 player1 = CircularQueue(capicity) player2 = CircularQueue(capicity) random_int = random.randint(0,1) choice = ["player1","player2"] first_take = choice[random_int] #randomly pick player 1 or player 2 for card in shuffled_cards: if first_take == "player1": player1.enqueue(card) first_take = "player2" else: player2.enqueue(card) first_take = "player1" #step 3: asking user for data while True: nbWarCards = input(" enter the number of cards face down in the war from 1 to 3: ") #prompt user to play game if nbWarCards in ['1','2','3'] and len(nbWarCards)==1: break else: print("invalid input, the number out of range, please enter again. ") nbWarCards = int(nbWarCards) # step 4: comparing cards def compareCards(card1,card2): #comparing the rank of the card between player1 and player2 rank1 = ranks.index(card1[0]) rank2 = ranks.index(card2[0]) if rank1 > rank2: return 1 elif rank1< rank2: return -1 else: return 0 #step 5: class ontable #creat a class to show the cards in the screen and place them in a suitable position class OnTable: def __init__(self): self.__cards = [] self.__faceUp = [] def place(self, player, card, hidden): if player == 1: self.__cards.insert(0,card) self.__faceUp.insert(0, not hidden) else: self.__cards.append(card) self.__faceUp.append(not hidden) def cleanTable(self): out = self.__cards self.__cards = [] self.__faceUp = [] return out def __str__(self): str_exp = '[' for i in range(len(self.__cards)): if i >0: str_exp +=', ' if self.__faceUp[i]: str_exp += self.__cards[i] else: str_exp += 'XX' str_exp +=']' return str_exp # step 6: the game end_game = False cards_on_table = OnTable() while not end_game: face_up_1 = player1.dequeue() #dequeue one card from circular queue 1 and put it on the table cards_on_table.place(1, face_up_1, False) face_up_2 = player2.dequeue() # dequeue one card from circular queue 2 and put it on the table cards_on_table.place(2, face_up_2, False) print(cards_on_table) #shows the two cards which are on the table print("Player1: ", player1.size()) #shows how many cards did the player1 and player2 own right now print("Player2: ", player2.size()) x = input("press enter to continue or quit to end the game") # prompt player continue the game if x.lower() == 'quit': end_game = True if compareCards(face_up_1, face_up_2) == 1: #compareCards method return 1 means player1 win for cards in cards_on_table.cleanTable(): #player1 collect all the cards on the table right now player1.enqueue(cards) elif compareCards(face_up_1, face_up_2) == -1: #compareCards method return -1 means player2 win for cards in cards_on_table.cleanTable(): #player2 collect all the cards on the table right now player2.enqueue(cards) else: if int(player1.size()) < nbWarCards: #if player did not have enough cards for war, then player2 win for cards in cards_on_table.cleanTable(): #player2 collect all the cards on tables player2.enqueue(cards) for cards in player1:#player2 collect all rest cards of player1, b/c player2 win the whole game player2.enqueue(cards) player1.clear() #player1 become empty queue end_game = True #end the game else: for i in range (nbWarCards): #player1 has enough cards for war war_card = player1.dequeue() cards_on_table.place(1, war_card, True) #put the cars which from player1 on table to do the war if player2.size()< nbWarCards: #player2 did not have enough cards for war, player1 win the whole game for cards in cards_on_table.cleanTable(): player1.enqueue(cards)# player1 collect all the cards ontable right now for cards in player2: player1.enqueue(player2)# player1 get all rest cards from player2, b/c player1 win the whole game player2.clear() #player2 become a empty queue end_game = True #end the game else: #both player1 and player2 have enough cards for war for i in range (nbWarCards): war_card = player2.dequeue() #put the cards which from player2 ontable and do the war cards_on_table.place(2, war_card, True) # show the final result if player1.size()==0: end_game = True print("player 1 win") if player2.size()==0: end_game = True print("player 2 win")
14a84fdbc18ce604fc44ae7faff93686e7622761
Degureshaff/python.itc
/python/day17/def_1.py
447
4.15625
4
def calculator(num1, num2, suff): if suff == '*': print(num1 * sum2) elif suff == '/': print(num1 / num2) elif suff == '**': print(num1 ** num2) elif suff == '+': print(num1 + num2) elif suff == '-': print(num1 - num2) num1 = int(input('Число 1: ')) num2 = int(input('Число 2: ')) a = input('Какое действие предпочитаете: ') calculator(num1, num2, a)
f65b5fba33417f7eea92cbebe8871b50bb12b9c3
Degureshaff/python.itc
/python/day19/main.py
943
3.671875
4
# import module_0 # phone = input('Введите номер телефона: ') # module_0.check_phone_number(phone) # import module_0 # module_0.translate() # fio = module_0.getFullName('Амантур', 'Торогулов') # print(fio) # import mylib.calc.calculator as calculate # import random # rstart = int(input('Введите начала рандома: ')) # rend = int(input('Введите конец рандома: ')) # print('Рандомное число: ', random.randint(rstart, rend)) import random mynum = int(input('Загадайте одно число, я попробую найти это число через функцию ranint: ')) choose_num = random.randint(1, mynum + 10) while choose_num != mynum: choose_num = random.randint(1, mynum + 10) print('Это твое число? ', choose_num) if choose_num == mynum: print('Я нашел твое число ', choose_num)
46f91e84678470fa56e0e2bc0bc333a57c8deed5
Degureshaff/python.itc
/python/day22/try_0.py
566
3.6875
4
try: a = int(input('Введите первое число: ')) b = int(input('Введите разделитель числа: ')) z = a / b print(z) except NameError: print('Ошибка: Неправильные переменные') except IndentationError: print('Ошибка: Отступы в коде') except ValueError: print('Ошибка: Текст не синтаксируется') except ZeroDivisionError: print('Ошибка: делить на 0 нельзя ') except: print('Ой ошибка') print(2 / 0)
1d1edccb227ef9c193756534653eccb0f80db859
Degureshaff/python.itc
/python/day3/calculator.py
319
4
4
number1 = input('Введите первое число: ') number2 = input('Введите второе число: ') number1 = int(number1) number2 = int(number2) print(number1 + number2) print(number1 - number2) print(number1 / number2) print(number1 * number2) print(number1 % number2) print(number1 ** number2)
05e222fc7c01e9875b5dc694892cbdf886681264
Degureshaff/python.itc
/python/day18/def_0.py
654
3.828125
4
# def my_function(name, number): # print('World', name) # print('Country') # print('Great Jobs') # name = name + ' REPUBLIC' # print(name, '\n') # if number < 0: # print('Дай десятое число') # else: # number = number * number # print(number) # my_function(-7) def kvadrat(number): if number < 0: print('Дай десятое число') else: number = number * number print(number) def divide(number1, number2): if number2 == 0: print('Нельзя делить на ноль') else: print(number1 / number2) divide(10, 0)
8cb1a0eb539da592941c6686a949c6947df629a6
Degureshaff/python.itc
/python/day18/def_3.py
221
3.515625
4
def perimetr(p): return p * 4 def aiant(s): return s * s p = int(input('Введите сторону крадрата: ')) x = perimetr(p) s = aiant(p) print('Периметр: ', x) print('Аянты: ', s)
d5e5857bec6f090de9f58ec0e44201544394c256
NehaRapolu3/python-tasks
/task 3.py
248
3.9375
4
function= input("enter names seperated by space") words = function.split(" ") length = 0 word = " " for i in range(len(words)) : if len(words[i]) > length : length = len(words[i]) word = words[i] print(word)