blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ea4eeb35fa630b091fd6300c9e4d6af443480b78
PhysicsGlitch/python-challenge
/PyBank/main.py
3,982
4.21875
4
# Disclaimer: I did this homework very early before we covered much of python. # It was more intuitive for me to simply use csv.reader to compile a list # and then I used for loops to references the indexes of the compiled list I needed. # Instead of re-writing my code iterating with the csv.reader, I thought it was more efficient to direct the extra time # to the challenges and demonstrate that I could use the csv.reader and csv.writer functionality in those assignments. # It also was very helpful to do the task in different ways to conceptually understand the logic # of how python works in different ways. # Overview: The code has three main steps: # Step 1: Use csv.reader to create a Python list of the data # Step 2: Define my variables and then create for loops to increment the values I need to find. # Step 3: Use csv.reader to convert my variables into a text file # Step 1: Import os and csv and then use csv.reader to compile a bank_data list import os import csv budget_data = os.path.join('Resources', 'budget_data.csv') with open(budget_data, newline='') as csv_file: bank_data = list(csv.reader(csv_file, delimiter=',')) # Step 2: Define variables and create for loops to increment the totals. total_profits = 0 total_months = 0 monthly_change = 0 max_increase = 0 max_decrease = 0 # Nested for loop to increment totals. for i in range(1, len(bank_data)): for j in range(1, len(bank_data[i])): total_profits += int(bank_data[i][j]) total_months += 1 # This next for loop increments the total of changes between months to find the total value for monthly_change, # since it is iterating over the same range necessary to find min/max, the # if statements find and store the max increase/decrease with the corresponding month. The range(1, len(bank_data)-1) # ignores the header row and then the number of changes between months will always be one less than the total # number of months. for i in range(1, len(bank_data)-1): for j in range(1, len(bank_data[i])): monthly_change += int(bank_data[i+1][j])-int(bank_data[i][j]) if int(bank_data[i+1][j])-int(bank_data[i][j]) > max_increase: max_increase = int(bank_data[i+1][j]) - int(bank_data[i][j]) max_month = bank_data[i+1][0] if int(bank_data[i+1][j])-int(bank_data[i][j]) < max_decrease: max_decrease = int(bank_data[i+1][j]) - int(bank_data[i][j]) min_month = bank_data[i+1][0] average_change = monthly_change/(len(bank_data) -2) # the -2 from len is to eliminate the header # and the number of changes between months will always be one less than total months so - 2 from len gives the # correct value of monthly changes to divide the total change by to get the average. # Format months: I used the split method and a formatted string to make the month readout look identical # to how it appeared in the readme file. split_min_month = min_month.split('-') split_max_month = max_month.split('-') formatted_min_month = f"{split_min_month[1]}-20{split_min_month[0]}" formatted_max_month = f"{split_max_month[1]}-20{split_max_month[0]}" # Creates a path to the results text file. analysis = os.path.join("results.txt") # I used formatted strings and \n to create new lines to print a basic text file. with open(analysis, "w") as datafile: datafile.write(f"Total Months: {total_months}\n") datafile.write(f"Total: ${total_profits}\n") datafile.write(f"Average Change: ${round(average_change, 2)}\n") datafile.write(f"Greatest Increase in Profits: {formatted_max_month} (${max_increase})\n") datafile.write(f"Greatest Decrease in Profits: {formatted_min_month} (${max_decrease})\n") print(f"Total: {total_months}") print(f"Total Months: {total_profits}") print(f"Average Change: ${round(average_change, 2)}") print(f"Greatest Increase in Profits: {formatted_max_month} (${max_increase})") print(f"Greatest Decrease in Profits: {formatted_min_month} (${max_decrease})")
4da53fb2dcb9377139d9b1a8435887f207aa06a8
ArtWachowski/hometest
/distance.py
1,082
3.828125
4
from math import radians, cos, sin, asin, sqrt #https://github.com/mapado/haversine/blob/master/tests/test_haversine.py class Distance: def __init__(self, earth, office): self.earth = earth self.office = office #Returns distance in KMs def get_km(self,la,lo): # unpack latitude/longitude lat1, lng1 = self.office lat2 = float(la) lng2 = float(lo) #Validating ranges https://docs.mapbox.com/help/glossary/lat-lon/# if not (-90.0 <= lat2 <= 90.0): raise Exception('Latitude out of range') if not (-180.0 <= lng2 <= 180.0): raise Exception('Latitude out of range') # convert all latitudes/longitudes from decimal degrees to radians lat1 = radians(lat1) lng1 = radians(lng1) lat2 = radians(lat2) lng2 = radians(lng2) # calculate haversine lat = lat2 - lat1 lng = lng2 - lng1 d = sin(lat * 0.5) ** 2 + cos(lat1) * cos(lat2) * sin(lng * 0.5) ** 2 return int(2 * self.earth * asin(sqrt(d)))
3b89c75be094b2a8ac8072a843978ea3c893bb41
swynn730/AdventOfCode2019
/day05/day05.py
6,532
3.640625
4
# Part 1 # Answer: 4887191 # Had to "cheat" a bit here. The instructions for this puzzle were wordy and I had trouble understanding them. # Therefore I needed some "inspiration" -> https://pastebin.com/0k9ZTur6 # I still like my code better though. :) class ParameterMode(): POSITION = 0 INTERMEDIATE = 1 def extract_intcode_program(user_input_instruction, integer_list): instruction_pointer = 0 integer_list_len = len(integer_list) while(instruction_pointer < integer_list_len): # Extracting the invidual numbers that make up the instruction code. instruction_code = [x for x in str(integer_list[instruction_pointer])] # Preserving negative numbers. for idx, num in enumerate(instruction_code): if num == "-": instruction_code[idx + 1] = "-" + instruction_code[idx + 1] # Cleaning up undesirable symbols. while "-" in instruction_code: instruction_code.remove("-") # Padding each number so that it has a consistent instruction code length and maps to ABCDE. while(len(instruction_code) < 5): instruction_code.insert(0, "0") opcode = "".join(instruction_code[-2::]) parameter_modes = [] # Keeping track of which mode each instruction parameter needs to be in. for instruction_code_num in instruction_code[:-2]: if int(instruction_code_num) == ParameterMode.POSITION: parameter_modes.insert(0, True) else: parameter_modes.insert(0, False) if opcode == "01": # Add first and second parameter and store in third. Skip 4 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] param_02 = integer_list[instruction_pointer + 3] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 integer_list[param_02] = mode_00 + mode_01 instruction_pointer += 4 elif opcode == "02": # Multiply first and second parameter and store in third. Skip 4 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] param_02 = integer_list[instruction_pointer + 3] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 integer_list[param_02] = mode_00 * mode_01 instruction_pointer += 4 elif opcode == "03": # Set first parameter equal to the user supplied value. Skip 2 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] # Don't need to determine the mode here since the mode by default will always be POSITION. integer_list[param_00] = user_input_instruction instruction_pointer += 2 elif opcode == "04": # Output the value of the only parameter. Skip 2 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 print(mode_00) instruction_pointer += 2 # BEGIN CODE FOR PART 2 ONLY. elif opcode == "05": # If the first parameter is non-zero, set the instruction pointer to the value of the second parameter, otherwise do "nothing"/skip 3 spaces ahead when done. # But if the instruction modifies the instruction pointer there's no need to skip spaces automatically. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 instruction_pointer = mode_01 if mode_00 != 0 else (instruction_pointer + 3) elif opcode == "06": # If the first parameter is zero, set the instruction pointer to the value of the second parameter, otherwise do "nothing"/skip 3 spaces ahead when done. # But if the instruction modifies the instruction pointer there's no need to skip spaces automatically. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 instruction_pointer = mode_01 if mode_00 == 0 else (instruction_pointer + 3) elif opcode == "07": # If the first parameter is less than the second parameter, store 1 in the position given by the third parameter, otherwise store 0. Skip 4 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] param_02 = integer_list[instruction_pointer + 3] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 integer_list[param_02] = 1 if mode_00 < mode_01 else 0 instruction_pointer += 4 elif opcode == "08": # If the first parameter is equal to the second parameter, store 1 in the position given by the third parameter, otherwise store 0. Skip 4 spaces ahead when done. param_00 = integer_list[instruction_pointer + 1] param_01 = integer_list[instruction_pointer + 2] param_02 = integer_list[instruction_pointer + 3] # Determine the mode. mode_00 = integer_list[param_00] if parameter_modes[0] else param_00 mode_01 = integer_list[param_01] if parameter_modes[1] else param_01 integer_list[param_02] = 1 if mode_00 == mode_01 else 0 instruction_pointer += 4 # END CODE FOR PART 2 ONLY. elif opcode == "99": break else: # Unknown opcode. instruction_pointer += 1 return integer_list with open("input.txt") as f_handle: f_content = f_handle.read() integer_list = [int(num) for num in f_content.strip().split(",")] user_input_instruction = 1 # Part 2 # Answer: 3419022 # BEGIN TEST DATA # integer_list = [3, 21 ,1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, # 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, # 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99] # user_input_instruction = 0 # Should output 999 if the input value is below 8. # user_input_instruction = 8 # Should output 1000 if the input value is equal to 8. # user_input_instruction = 9 # Should output 1001 if the input value is greater than 8. # END TEST DATA user_input_instruction = 5 extract_intcode_program(user_input_instruction, integer_list)
2c82b81df1a1c29f2d0a5588928d2ba216ae95fb
OffTheMark/csgames_2017_ai_prep
/pathfinding/dijkstra.py
1,214
3.71875
4
from pathfinding.solver import Solver class DijkstraSolver(Solver): """ Dijkstra solver implementation \n Based on https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode """ def solve(self): start = self.find(self.START) finish = self.find(self.FINISH) visited = set() distances = dict.fromkeys(self.maze_graph.keys(), float("+inf")) predecessors = dict.fromkeys(self.maze_graph.keys(), None) distances[start] = 0 while visited != self.maze_graph.keys(): shortest = min((set(distances.keys()) - visited), key=distances.get) if shortest == finish: break for neighbour in self.maze_graph[shortest]: if neighbour in visited: continue new_cost = distances[shortest] + 1 if new_cost < distances[neighbour]: distances[neighbour] = new_cost predecessors[neighbour] = shortest visited.add(shortest) path = [] node = finish while node is not None: path = [node] + path node = predecessors[node] return path
93d85cfb19c14ecfd75b071b014c57dbf09d79f7
joao-vitorg-zz/PythonBR
/8 - Classes/ex16.py
1,865
3.734375
4
# -*- coding: utf-8 -*- # Crie uma "porta escondida" no programa do programa do bichinho virtual que # mostre os valores exatos dos atributos do objeto. Consiga isto mostrando o objeto quando uma opรงรฃo secreta, # nรฃo listada no menu, for informada na escolha do usuรกrio. Dica: acrescente um mรฉtodo especial str() ร  classe Bichinho. from time import time class Tamagushi(object): def __init__(self, nome): self.nome = nome.title() self._fome = 100 self._saude = 100 self._inicial = time() @staticmethod def _analiza(x): return max(min(x, 100), 0) @property def tempo(self): return time() - self._inicial @property def fome(self): return self._fome - self.tempo // 0.5 @property def saude(self): return self._saude - self.tempo // 1 @property def idade(self): return self.tempo // 1 @property def humor(self): return self._analiza((self.saude + self.fome) / 2) @fome.setter def fome(self, x): self._fome = self._analiza(x) @saude.setter def saude(self, x): self._saude = self._analiza(x) def __str__(self): return """ โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•คโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•คโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•คโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•คโ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ Nome โ”‚ Fome(%) โ”‚ Saรบde(%) โ”‚ Humor(%) โ”‚ Idade โ•‘ โ•Ÿโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ข โ•‘ {:<6.6} โ”‚ {:<7.2f} โ”‚ {:<8.2f} โ”‚ {:<8.2f} โ”‚ {:<5.0f} โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•งโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•งโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•งโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•งโ•โ•โ•โ•โ•โ•โ•โ• """.format(self.nome, self.fome, self.saude, self.humor, self.idade)
82c809aa96a84921e66891878fc151eb48ca3d40
ho2921ho/HomeWork
/Social_HW2.py
222
3.59375
4
import random def lottery(): numbers = [] while len(numbers) != 7: num = random.choice(range(1,45)) if num not in numbers: numbers.append(num) return sorted(numbers)
7f5042d2a6506c0897039374995262ef8fb1b916
kongyitian/coding_interviews
/LeetCode/hzw/greedy/gas_station.py
1,109
3.828125
4
# [Ebay] ''' There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. ''' class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ # gas[i] - cost[i] start = 0 n = len(gas) cur_sum = 0 total_sum = 0 for i in range(n): total_sum += (gas[i]-cost[i]) cur_sum += gas[i] cur_sum -= cost[i] while cur_sum < 0 and start != n-1: cur_sum += cost[start] cur_sum -= gas[start] start += 1 return start if total_sum >= 0 else -1 ''' Find the point from which the following sum will all be larger than 0 '''
447db95f30c6b12aeb2e74070cff5977df6d861c
lb8ovn/CoffeeOOP
/PrimeChecker.py
189
3.96875
4
def prime(number): y = False for x in range(2,number): if number%x == 0: y = True if y == True: print('Not a Prime') else: print('Prime')
fb8fb1208161eea30708c03b6acb5261cc34b55e
anirudhasundaresan/project_euler
/problem1.py
110
3.875
4
print(sum([num for num in range(1000) if num%3==0 or num%5==0])) # start with 'for' and read it like a loop.
e64696ae4a054b469866925cd996deae2baa1faf
MaudW64/pylearn
/py/0817_TestDef3.py
435
3.796875
4
# pythonไธๆ”ฏๆดๅ‡ฝๅผ้‡่ผ‰(overload) ไน‹่งฃๆฑบๆ–นๅผ๏ผš่จญๅฎšๅผ•ๆ•ธ """ # defๆ–นๅผไธ€ def account (name,number,balance=0): # balance=0 ็‚บ ้ ่จญๅผ•ๆ•ธ print(name,number,balance) """ # defๆ–นๅผไบŒ def account (**data): # ๅƒ่€ƒTestDef4 print(data.get('name'),data.get('number'),data.get('balance')) account(name='ๆฑๆฑ',number='0001-0001',balance=100) account(name='่ฅฟ่ฅฟ',number='0001-0001') account(name='ๅ—ๅ—')
19fb4f1fb287cd6d54415a06fc199e5614e7c016
imjoung/hongik_univ
/_WSpython/Pandas01_09_FunEx03_์ตœ์ž„์ •.py
307
3.890625
4
def add_mul(choice,*args): if choice == "add": result = 0 for i in args: result = result +i elif choice == "mul": result = 1 for i in args: result = result *i return result result1 = add_mul('add',2,3) print(result1) print("="*20) result2 = add_mul('mul',2,3) print(result2)
00aebd0d91e307ce5ff477c5e6b89da479d80222
Quessou/quessoutils
/qssfsutils/pathchecks.py
2,217
3.578125
4
import string import errno import os import sys ERROR_INVALID_NAME = 123 def is_pathname_valid(pathname: str) -> bool: ''' `True` if the passed pathname is a valid pathname for the current OS; `False` otherwise. ''' # If this pathname is either not a string or is but is empty, this pathname # is invalid. try: if not isinstance(pathname, str) or not pathname: return False # Specific Windows processing # Removes the Drive letter, which will be stored into "_", and keeps the rest in "pathname". _, pathname = os.path.splitdrive(pathname) # Directory guaranteed to exist. If the current OS is Windows, this is # the drive to which Windows was installed (e.g., the "%HOMEDRIVE%" # environment variable); else, the typical root directory. root_dirname = os.environ.get('HOMEDRIVE', 'C:') if sys.platform == 'win32' else os.path.sep assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law # Append a path separator to this directory if needed. root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep # Test whether each path component split from this pathname is valid or # not, ignoring non-existent and non-readable path components. for pathname_part in pathname.split(os.path.sep): try: os.lstat(root_dirname + pathname_part) except OSError as exc: if hasattr(exc, 'winerror'): if exc.winerror == ERROR_INVALID_NAME: return False elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}: return False # If a "TypeError" exception was raised, it almost certainly has the # error message "embedded NUL character" indicating an invalid pathname. except TypeError as exc: return False else: return True def isValidFilename(filename : str) -> bool: validchars = set(string.ascii_letters + string.digits + string.punctuation.replace("/","")) fn = set(filename) return filename != "." and filename != "/" and fn.issubset(validchars) # TODO(mmiko) : Write tests here
48bbcb855b56572b6826be4ec10fa48546d4ed12
jeong0982/CS206-DataStructure
/์ˆ˜์—… code/stacks/example1.py
202
3.6875
4
from cs206stack import print_stack def first(n): second(n) second(n * n) def second(m): three(m) three(m+1) three(m+2) def three(z): print("In three(%d):" % z) print_stack() first(13)
7ffe153d7bad90560f441099a7407d280b566f2c
itepifanio/calculo-numerico
/task2/bissecao.py
779
3.78125
4
f = lambda x: x**3 - 1.7*(x**2) - 12.78*x - 10.08 intervalo = {'a': -3, 'b': 0} def ponto_medio(x, y): return (x + y)/2 max_iteracoes = 100 # evita loops infinitos n = 0 result = -1 erro = 0.0001 a = intervalo['a']; b = intervalo['b'] # variaveis para o intervalo print(f' I | Intervalo a | Intervalo b | Valor mรฉdio c | f(c) |') while n < max_iteracoes and abs(a - b) > erro: c = ponto_medio(a, b) fc = f(c) # encontrado a raiz if fc == 0: print(f' {n:3d} | {a:11f} | {b:11f} | {c:13f} | {fc:10f} |') result = c break n += 1 # busca binรกria no intervalo if f(a)*fc < 0: b = c else: a = c print(f' {n:3d} | {a:11f} | {b:11f} | {c:13f} | {fc:10f} |') print(f'O valor da raiz รฉ {c}')
93a72bfb694a7ec8b655ba0605b3c6b49139557e
EunsilChoi92/Academy_Python
/Python/repeative.py
14,232
4.3125
4
''' [๋ฐ˜๋ณต๋ฌธ] ์กฐ๊ฑด์— ๋งŒ์กฑํ•˜๋ฉด ์ˆ˜ํ–‰ํ•œ๋‹ค. >๋‹จ, ์กฐ๊ฑด์— ๋งŒ์กฑํ•˜์ง€ ์•Š์„๋•Œ๊นŒ์ง€ 1.while๋ฌธ -์กฐ๊ฑด์‹์ด ์ฐธ์ด๋ฉด ์ˆ˜ํ–‰ -if๋ฌธ๊ณผ ๊ธฐ๋ณธ ๊ตฌ์กฐ๊ฐ€ ๋™์ผ >if๋ฌธ : ์กฐ๊ฑด์ด ์ฐธ์ด๋ฉด ์ˆ˜ํ–‰ ๋ >while๋ฌธ : ์กฐ๊ฑด์ด ์ฐธ์ด๋ฉด ์ˆ˜ํ–‰ํ•˜๊ณ  ๋‹ค์‹œ ์กฐ๊ฑด์‹์„ ๋น„๊ต [while๋ฌธ์˜ ๊ธฐ๋ณธ๊ตฌ์กฐ] while ์กฐ๊ฑด์‹ : ์ˆ˜ํ–‰๋ฌธ ์ˆ˜ํ–‰๋ฌธ [for๋ฌธ์˜ ๊ธฐ๋ณธ๊ตฌ์กฐ] for ๋ณ€์ˆ˜ in ๋ฆฌ์ŠคํŠธ(๋˜๋Š” ๋ฌธ์ž์—ด,ํŠœํ”Œ ๋“ฑ๋“ฑ) : ์ˆ˜ํ–‰๋ฌธ ์ˆ˜ํ–‰๋ฌธ ''' print("[while๋ฌธ]") num = 0 while num < 3 : print("num : {}".format(num)) num+=1#๋ณตํ•ฉ ๋Œ€์ž… ์—ฐ์‚ฐ์ž num = num + 1 #1)num = 0, 0 < 3 ๋งŒ์กฑํ•˜์—ฌ ์ˆ˜ํ–‰(์ถœ๋ ฅ๋ฌธ ๋ฐ num 1 ์ฆ๊ฐ€) #2)num = 1, 1 < 3 ๋งŒ์กฑํ•˜์—ฌ ์ˆ˜ํ–‰ #3)num = 2, 2 < 3 ๋งŒ์กฑํ•˜์—ฌ ์ˆ˜ํ–‰ #4)num = 3, 3 < 3 ๋งŒ์กฑํ•˜์ง€ ์•Š์•„์„œ ์ˆ˜ํ–‰ ๋ #while๋ฌธ ์ˆ˜ํ–‰ ์ˆœ์„œ #์กฐ๊ฑด ๋น„๊ต ->(๋งŒ์กฑ) ์ˆ˜ํ–‰ -> ๋น„๊ต ->....๋ฐ˜๋ณต print("๋") ''' num = 0 while num < 3: print("num = ",num) ''' ''' (1)๋ฌดํ•œ๋ฐ˜๋ณต ์ฒ˜์Œ ๋ฐ˜๋ณต๋ฌธ๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ num์˜ ๊ฐ’์„ ์ˆ˜ํ–‰๋ฌธ์—์„œ ์ฆ๊ฐ€์‹œํ‚ค์ง€ ์•Š์•˜๋‹ค. ์กฐ๊ฑด์‹์—์„œ ๋น„๊ต ๋Œ€์ƒ์ธ num์˜ ๊ฐ’์ด ๊ณ„์† ๋™์ผ ๊ทธ๋Ÿฌ๋ฏ€๋กœ ํ•ญ์ƒ ์กฐ๊ฑด์ด ๋งŒ์กฑํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ ์ข…๋ฃŒ X Ctrl + c : ๊ฐ•์ œ์ข…๋ฃŒ (2)์กฐ๊ฑด๋ณ€์ˆ˜ ์กฐ๊ฑด์‹์˜ ๋น„๊ต์— ์‚ฌ์šฉ๋˜๋Š” ๋ณ€์ˆ˜๋Š” '์กฐ๊ฑด๋ณ€์ˆ˜' ์กฐ๊ฑด๋ณ€์ˆ˜๋ฅผ ์–ด๋–ป๊ฒŒ ๋‹ค๋ฃจ์—ˆ๋Š”์ง€์— ๋”ฐ๋ผ ๋ฐ˜๋ณต ํšŸ์ˆ˜๊ฐ€ ์ •ํ•ด์ง„๋‹ค. ์กฐ๊ฑด๋ณ€์ˆ˜๋Š” ์กฐ๊ฑด์‹์—์„œ ๊ทธ ๊ฐ’์ด '์‚ฌ์šฉ'๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฏธ๋ฆฌ ์ƒ์„ฑ๋œ ๋ณ€์ˆ˜์—ฌ์•ผํ•จ ์ดˆ๊ธฐ๊ฐ’(์กฐ๊ฑด๋ณ€์ˆ˜ ์ƒ์„ฑ) while ์กฐ๊ฑด์‹ : (์กฐ๊ฑด๋ณ€์ˆ˜ ์‚ฌ์šฉ) ์ˆ˜ํ–‰๋ฌธ(๋ฐ˜๋ณตํ•ด์„œ ์ˆ˜ํ–‰ํ•˜๊ณ  ์‹ถ์€ ์ฝ”๋“œ + ์กฐ๊ฑด๋ณ€์ˆ˜์˜ ๋ณ€ํ™”์‹) ์กฐ๊ฑด๋ณ€์ˆ˜์˜ ๋ณ€ํ™”์‹์€ ์–ผ๋งˆ๋“ ์ง€ ์ž์œ ๋กญ๊ฒŒ ์‚ฌ์šฉ๊ฐ€๋Šฅ(์‚ฌ์น™์—ฐ์‚ฐ) ๋‹จ,์กฐ๊ฑด์‹์ด ๋งŒ์กฑํ•˜์ง€ ์•Š๋„๋ก๋งŒ ๊ตฌ์„ฑ(๋งŒ์กฑํ•˜์ง€ ์•Š์•„์•ผ ๋ฐ˜๋ณต๋ฌธ์ข…๋ฃŒ) ''' #๋ฐ˜๋ณต ํšŸ์ˆ˜ ์ง€์ • ''' count = int(input("๋ฐ˜๋ณตํ•  ํšŸ์ˆ˜ ์ž…๋ ฅ :")) while count > 0 : print("count = {}".format(count)) count-=1 ''' ''' 1. 1๋ถ€ํ„ฐ 10๊นŒ์ง€ ํ•ฉ ๊ตฌํ•˜๊ธฐ > 1~10๊นŒ์ง€ ์ฆ๊ฐ€ํ•  ๋ณ€์ˆ˜ > ํ•ฉ๊ณ„๋ฅผ ๋ˆ„์ ํ•  ๋ณ€์ˆ˜ [์ถœ๋ ฅ๊ฒฐ๊ณผ] 1~10๊นŒ์ง€ ํ•ฉ์€ 55์ž…๋‹ˆ๋‹ค. ''' ''' cnt = 1 hab = 0 while cnt < 11 : hab+=cnt cnt+=1 print("1~10๊นŒ์ง€์˜ ํ•ฉ์€ {}์ž…๋‹ˆ๋‹ค.".format(hab)) ''' ''' 2. 1๋ถ€ํ„ฐ ์ž…๋ ฅ ๋ฐ›์€ ์ˆ˜๊นŒ์ง€ ํ•ฉ ๊ตฌํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ์ˆซ์ž ์ž…๋ ฅ : 5 1~5๊นŒ์ง€ ํ•ฉ์€ 15์ž…๋‹ˆ๋‹ค. ''' ''' num = int(input("์ˆซ์ž ์ž…๋ ฅ :")) cnt = 1 hab = 0 while cnt <= num : hab+=cnt cnt+=1 print("1~{}๊นŒ์ง€์˜ ํ•ฉ์€ {}์ž…๋‹ˆ๋‹ค.".format(num,hab)) ''' #ํŠน์ • ์กฐ๊ฑด ๋งŒ์กฑ ''' input_num = 0# ์ดˆ๊ธฐ๊ฐ’์ด 9๋ฉด while๋ฌธ ์ˆ˜ํ–‰ X while input_num != 9 : input_num = int(input("9๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์ข…๋ฃŒ : ")) ''' #break ์‚ฌ์šฉ(๋ฐ˜๋ณต๋ฌธ ์ข…๋ฃŒ) ''' while True :#ํ•ญ์ƒ๋งŒ์กฑ ->๋ฌดํ•œ๋ฐ˜๋ณต input_num = int(input("9๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์ข…๋ฃŒ : ")) if input_num == 9: break#๋ฐ˜๋ณต๋ฌธ ์•ˆ์—์„œ๋งŒ ์‚ฌ์šฉ๊ฐ€๋Šฅ. ๋ฐ˜๋ณต๋ฌธ ์ข…๋ฃŒ ''' #while๋ฌธ์€ ๋ฌดํ•œ๋ฐ˜๋ณต ์กฐ๊ฑด์„ ๊ฑธ์–ด๋‘๊ณ  break๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ ์ข…๋ฃŒ #์กฐ๊ฑด๋ฌธ ๋”ฐ๋ผ ๋งŒ๋“ค์–ด์„œ ํƒˆ์ถœ ์‹œํ‚ค๊ฒ ๋‹ค -> ๋น ์ ธ๋‚˜๊ฐˆ ๊ตฌ๋ฉ #ํƒˆ์ถœ์กฐ๊ฑด์ด ๋ณต์žกํ•  ๋•Œ ์ด๋ ‡๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ํŽธํ•จ #continue ์‚ฌ์šฉ(while ๋ฌธ์˜ ์กฐ๊ฑด์‹์œผ๋กœ ์ ํ”„) num = 1 while num < 10 :#num์˜ ๊ฐ’์ด 10๋ณด๋‹ค ์ž‘์œผ๋ฉด ๋งŒ์กฑ -> ์ˆ˜ํ–‰ if num % 2 == 0 :#num 2๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๊ฐ€ 0๊ฐ€ ๊ฐ™๋ƒ(์ง์ˆ˜) #continue๋ฅผ ํ•œ๋‹ค๋Š” ์ˆ˜ํ–‰๋ฌธ ๋๋‚ด๋Š” ๊ฒƒ์ด๋‹ค. #์ƒˆ๋กญ๊ฒŒ ๋๋‚˜๋Š” ์ง€์  ์ƒ์„ฑ num+=1#์›๋ž˜ ์ˆ˜ํ–‰๋ฌธ์ด ๋๋‚  ๋•Œ ํ•˜๋˜ ์ฝ”๋“œ ์ถ”๊ฐ€ ์ž‘์„ฑ continue#๋งŒ๋‚˜๋Š” ์ˆœ๊ฐ„ ์กฐ๊ฑด์‹์œผ๋กœ ์ ํ”„ print("num = {}".format(num)) num+=1 print("์ด ๋•Œ์˜ num? :",num) #break,continue๋ฌธ์€ '๋ฐ˜๋ณต๋ฌธ' ์•ˆ์—์„œ๋งŒ ์“ฐ์ธ๋‹ค #๋‹จ, if๋ฌธ์ด ํ•„์š”ํ•˜๋‹ค # ์™œ? if๋ฌธ ์—†๋Š” break = ๋ฌด์กฐ๊ฑด ๋ฐ˜๋ณต ์ข…๋ฃŒ = ๋ฐ˜๋ณต๋ฌธ ์˜๋ฏธ ์—†์Œ # if๋ฌธ ์—†๋Š” continue = ๋ฌด์กฐ๊ฑด ์กฐ๊ฑด์‹ ์ด๋™ = # continue ์•„๋ž˜ ์ฝ”๋“œ๋Š” ์˜๋ฏธ ์—†์Œ #๊ตฌ๊ตฌ๋‹จ 5๋‹จ num = 1 while num < 10 : print("{} x {} = {}".format(5,num,5*num)) num += 1 # ๋ฐ˜๋ณต๋ฌธ ''' ๊ตฌ๊ตฌ๋‹จ 7๋‹จ ์ถœ๋ ฅํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] 7 * 1 = 7 ... 7 * 9 = 63 ''' ''' ์ž…๋ ฅ ๋ฐ›์€ ๋‹จ ์ถœ๋ ฅํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ๋‹จ์„ ์ž…๋ ฅํ•˜์„ธ์š” : 5 5 * 1 = 5 ... 5 * 9 = 45 ''' ''' dan = int(input("๋‹จ ์ž…๋ ฅ :")) num = 1 while num < 10 : print("{} x {} = {}".format(dan,num,dan*num)) num += 1 ''' ''' [๋ฌธ์ œ] while ๋ฌธ์„ ์ด์šฉํ•ด์„œ 1๋ถ€ํ„ฐ 100๊นŒ์ง€์˜ ํ™€์ˆ˜๋งŒ ์ถœ๋ ฅํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] 1 3 5 ... 97 99 ''' num = 1 while num <= 100 : print("{}".format(num)) num += 2 ''' [๋ฌธ์ œ] ์ฃผ์ธ๊ณต ์ฒด๋ ฅ ๊ณ„์‚ฐ while๋ฌธ์„ ์ด์šฉํ•˜์—ฌ ์ˆซ์ž๋กœ ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…ํžŒ ํ›„ ์ฒด๋ ฅ์ด 0์ด ๋˜๋ฉด ์ข…๋ฃŒํ•˜๊ฒŒ ๋งŒ๋“ค๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€ 100 ์ž…๋‹ˆ๋‹ค. ์–ผ๋งˆ์˜ ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…ํžˆ๊ฒ ์Šต๋‹ˆ๊นŒ : 50 ์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€ 50 ์ž…๋‹ˆ๋‹ค. ์–ผ๋งˆ์˜ ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…ํžˆ๊ฒ ์Šต๋‹ˆ๊นŒ : 40 ์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€ 10 ์ž…๋‹ˆ๋‹ค. ์–ผ๋งˆ์˜ ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…ํžˆ๊ฒ ์Šต๋‹ˆ๊นŒ : 10 ์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€ 0์ด ๋˜์–ด ์ข…๋ฃŒ๋ฉ๋‹ˆ๋‹ค! ''' ''' hp = 100 while hp > 0 : print("์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€",hp,"์ž…๋‹ˆ๋‹ค.") damage = int(input("์–ผ๋งˆ์˜ ๋ฐ๋ฏธ์ง€๋ฅผ ์ž…ํžˆ๊ฒ ์Šต๋‹ˆ๊นŒ?")) hp -= damage print("์ฃผ์ธ๊ณต์˜ ์ฒด๋ ฅ์€ 0์ด ๋˜์–ด ์ข…๋ฃŒ") ''' ''' [๋ฌธ์ œ] while ๋ฌธ์„ ์ด์šฉ. ๋ฌดํ•œ ๋ฃจํ”„๋ฅผ ์‚ฌ์šฉํ•ด ์ž…๋ ฅํ•œ ๋‘ ์ˆซ์ž์˜ ํ•ฉ๊ณ„๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ ๊ณ„์‚ฐํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ๋”ํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 55 ๋”ํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 22 55 + 22 = 77 ๋”ํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 77 ๋”ํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 120 77 + 120 = 197 ๋”ํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ''' ''' hap = 0 while True : a = int(input("๋”ํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” :")) b = int(input("๋”ํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” :")) hap = a + b print("{} + {} = {}".format(a,b,(a+b))) ''' ''' [๋ฌธ์ œ] ์œ„์˜ ๋ฌธ์ œ์—์„œ ์ฐธ๊ณ . while๋ฌธ ์ด์šฉ. ์œ„์˜ ๋ฌธ์ œ์—์„œ ๋ง์…ˆ ์™ธ์— ๋บ„์…ˆ, ๊ณฑ์…ˆ, ๋‚˜๋ˆ—์…ˆ, ๋‚˜๋จธ์ง€๊นŒ์ง€ ๊ณ„์‚ฐํ•ด๋ณด์ž. ์—ฐ์‚ฐ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒํ•˜๊ฒŒ ํ•˜์ž. [์ถœ๋ ฅ๊ฒฐ๊ณผ] ๊ณ„์‚ฐํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 30 ๊ณ„์‚ฐํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 20 ๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : - 30 - 20 = 10 ๊ณ„์‚ฐํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 30 ๊ณ„์‚ฐํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 20 ๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : * 30 * 20 = 600 ๊ณ„์‚ฐํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 30 ๊ณ„์‚ฐํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 20 ๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : / 30 / 20 = 1.5 ๊ณ„์‚ฐํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 30 ๊ณ„์‚ฐํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 20 ๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : % 30 % 20 = 10 ๊ณ„์‚ฐํ•  ์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 30 ๊ณ„์‚ฐํ•  ๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : 20 ๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” : ! ์—ฐ์‚ฐ์ž๋ฅผ ์ž˜๋ชป ์ž…๋ ฅํ•˜์…จ์Šต๋‹ˆ๋‹ค. ๊ณ„์‚ฐ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค! ''' ''' while True : a = int(input("์ฒซ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” :")) b = int(input("๋‘ ๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” :")) op = input("๊ณ„์‚ฐํ•  ์—ฐ์‚ฐ์ž๋ฅผ ์ž…๋ ฅ : ") if op == '+': print("{} + {} = {}".format(a,b,(a+b))) elif op == '-': print("{} - {} = {}".format(a,b,(a-b))) elif op == '*': print("{} * {} = {}".format(a,b,(a*b))) print(f'{a} * {b} ={a*b}') elif op == '/': print("{} / {} = {}".format(a,b,(a/b))) elif op == '%': print("{} % {} = {}".format(a,b,(a%b))) else: print("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž") print("๊ณ„์‚ฐ ์ข…๋ฃŒ") break ''' ''' 5. * ์ฐ๊ธฐ - ์ž…๋ ฅ๋œ ์ˆซ์ž๋งŒํผ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ชจ์–‘์œผ๋กœ ๋ณ„ ์ฐ๊ธฐ - ์กฐ๊ฑด๋ณ€์ˆ˜๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋ฉฐ ๋ฌธ์ž์—ด ์—ฐ์‚ฐ์„ ํ•˜๋ฉด ๋งค์šฐ ํŽธํ•˜๊ฒŒ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค. [์ถœ๋ ฅ๊ฒฐ๊ณผ] ์ˆซ์ž ์ž…๋ ฅ : 5 * ** *** **** ***** ''' ''' num = int(input("์ˆซ์ž ์ž…๋ ฅ :")) cnt = 0 while True: cnt += 1 if cnt > num : break print("*"*cnt) ''' ''' 6. ์ˆซ์ž ๋งž์ถ”๊ธฐ 1~100๊นŒ์ง€ ๋žœ๋ค์œผ๋กœ ์ •๋‹ต ์ˆซ์ž๋ฅผ ์ƒ์„ฑ while๋ฌธ ์•ˆ์—์„œ ์ˆซ์ž๋ฅผ ์ž…๋ ฅ ๋ฐ›๊ณ , ์ˆซ์ž๊ฐ€ ์ •๋‹ต์ด๋ฉด ํƒˆ์ถœ! [์ถœ๋ ฅ๊ฒฐ๊ณผ] (์ •๋‹ต์ด 70์ด๋ผ๊ณ  ๊ฐ€์ •) ์ˆซ์ž ์ž…๋ ฅ : 50 ๋” ํฐ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด๋ณด์„ธ์š”. ์ˆซ์ž ์ž…๋ ฅ : 80 ๋” ์ž‘์€ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด๋ณด์„ธ์š”. ์ˆซ์ž ์ž…๋ ฅ : 70 ์ •๋‹ต์ž…๋‹ˆ๋‹ค! 3ํšŒ๋งŒ์— ๋งž์ถ”์…จ์Šต๋‹ˆ๋‹ค. * ์‹ฌํ™” : ๋ช‡ ํšŒ ๋งŒ์— ๋งž์ท„๋Š”์ง€ ์ถ”๊ฐ€๋กœ ์ถœ๋ ฅ ''' import random print(random.random())#0.0 1.0 ์‚ฌ์ด๋ฅผ ์‹ค์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ print(random.random()+1.0)#1.0~2.0 ์‚ฌ์ด๋ฅผ ์‹ค์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ print(random.randint(1,10))#1~10 ์‚ฌ์ด์˜ ์ •์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ answer = random.randint(1,100) cnt = 0 ''' while True : num = int(input("์ •๋‹ต ์ž…๋ ฅ : ")) cnt += 1 if num == answer : print("์ •๋‹ต์ž…๋‹ˆ๋‹ค!!") print("{}ํšŒ๋งŒ์— ๋งž์ถ”์…จ์Šต๋‹ˆ๋‹ค.".format(cnt)) break elif num > answer : print("๋” ์ž‘์€ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”~") elif num < answer : print("๋” ํฐ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”~") ''' print() print("[for๋ฌธ]") #in ์˜ ์‚ฌ์šฉ #if: ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์—ฌ true/false #for : ํ•˜๋‚˜์”ฉ ๋Œ€์ž…ํ•œ๋‹ค. #๋ฒ”์œ„ ์ง€์ • ๋ฐ˜๋ณต๋ฌธ for z in [1,2,3]:#์š”์†Œ๋ฅผ ๋ณ€์ˆ˜ '๋Œ€์ž…'ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋•Œ ์ƒ์„ฑ print("z =",z)#for๋ฌธ์ด ๋๋‚˜๋„ z ๋ณ€์ˆ˜๋Š” ์‚ฌ์šฉ ๊ฐ€๋Šฅ print("๋ z =",z) for z in "๋Œ€ํ•œ๋ฏผ๊ตญ": print(z) for a in [1,2,3,4,5] : print("ํ•˜ํ•˜ํ•˜ํ•˜ํ•˜ํ•˜") print("a = ",a) #for๋ฌธ ์‚ฌ์šฉํ•  ๋•Œ - ์ผ๋ฐ˜์ ์ธ ์‚ฌ์šฉ๋ฒ• #range() ํ•จ์ˆ˜ : ์ง€์ •ํ•œ ๋ฒ”์œ„๋งŒํผ์˜ ์ˆซ์ž๋“ค์„ ๋ฐ˜ํ™˜ for i in range(10) : #0~9๊นŒ์ง€ ์ˆœ์„œ๋Œ€๋กœ i print("range(10)์—์„œ์˜ i์˜ ๊ฐ’ :",i) ''' range(10) : 0~9 range(5) : 0~4 >๊ฐ’์„ ํ•˜๋‚˜๋งŒ ๋„ฃ์œผ๋ฉด ์‹œ์ž‘(0) ๋์˜ ๊ฐ’ -1(์Šฌ๋ผ์ด์‹ฑ ๋А๋‚Œ) range(1,10) : 1~9(๋์€ ํฌํ•จ๋˜์ง€ ์•Š์Œ) range(10,45) : 10~44 range(1,10,2) : 1~9 ๊ฐ’์ด 2์”ฉ ์ฆ๊ฐ€ range(10,1,-1):10~1๊นŒ์ง€ 1์”ฉ ๊ฐ์†Œ reversed(range(10)) :0 ~9๊นŒ์ง€๋ฅผ ๋’ค์ง‘๋Š”๋‹ค. ''' #for 1~10๊นŒ์ง€์˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ] sum = 0#ํ•ฉ๊ณ„ ๋ˆ„์ ์šฉ for i in range(1,11) : sum += i print("1~10์˜ ํ•ฉ์€ :",sum) #์ž…๋ ฅํšŸ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต ''' cnt = int(input("๋ฐ˜๋ณต ํšŸ์ˆ˜ ์ž…๋ ฅ : ")) #for i in range(cnt,0,-1): for i in reversed(range(1,cnt+1)): print(i) ''' #for๋ฌธ ํ™œ์šฉ ์˜ˆ์‹œ #์†๋‹˜ ๋ฆฌ์ŠคํŠธ : ์ด๋ฆ„,๋‚˜์ด guest_list=[["ํ™๊ธธ๋™",19],["์ด๋ชฝ๋ฃก",27],["์„ฑ์ถ˜ํ–ฅ",18],["๊น€์ฒ ์ˆ˜",29]] print(guest_list) num = 0 #๋ช‡ ๋ฒˆ์งธ ์†๋‹˜์ธ์ง€ for guest in guest_list : #print(guest)#๋ฆฌ์ŠคํŠธ์—์„œ ์š”์†Œ ํ•˜๋‚˜์”ฉ ๋Œ€์ž…(๋Œ€์ž…๋˜๋Š” ์š”์†Œ๋Š” '๋ฆฌ์ŠคํŠธ') name = guest[0]#๋Œ€์ž…๋œ ๋ฆฌ์ŠคํŠธ์ธ guest์˜ ์ฒซ ์š”์†Œ๋Š” '๋ฌธ์ž์—ด'์ด๋ฆ„ age = guest[1]#๋‘๋ฒˆ์งธ ์š”์†Œ๋Š” '์ •์ˆ˜'๋‚˜์ด num+=1 print("{}๋ฒˆ ์†๋‹˜ ์ž…์žฅํ•˜์‹ค๊ฒŒ์š”~".format(num)) if age > 19 : print("{}๋‹˜์€ ์„ฑ์ธ์ž…๋‹ˆ๋‹ค. ์ž…์žฅํ•˜์„ธ์š”~".format(name)) else: print("{}๋‹˜์€ ๋ฏธ์„ฑ๋…„์ž ์ž…๋‹ˆ๋‹ค. ์ž…์žฅํ•˜์…”์„œ ์šฐ์œ ๋งŒ ๋“œ์„ธ์š”".format(name)) if age < 20: continue print("{}๋ฒˆ์งธ ์†๋‹˜์ธ {} ๋‹˜์€ ์„ฑ์ธ์ž…๋‹ˆ๋‹ค({}์„ธ).".format(num,name,age)) #for๋ฌธ์„ ํ™œ์šฉ ์˜ˆ์‹œ (2) #๊ตฌ๊ตฌ๋‹จ ์ถœ๋ ฅ #i,j ๋Š” ๊ตฌ๊ตฌ๋‹จ์—์„œ ~๋‹จ์„ ์˜๋ฏธํ•˜๋Š” ๋ณ€์ˆ˜์™€ ๋’ค์— ๊ณฑํ•ด์ง€๋Š” ์ˆซ์ž๋กœ ์‚ฌ์šฉ for i in range(2,10):#๋‹จ : 2~9 print("{}๋‹จ".format(i)) #i์— 2๊ฐ€ ๋Œ€์ž…๋œ ์ƒํƒœ๋กœ i์˜ for๋ฌธ ์ด ์ˆ˜ํ–‰ #i์˜ for๋ฌธ์˜ ์ˆ˜ํ–‰๋ฌธ์— ๋˜ ๋‹ค๋ฅธ j์˜ for๋ฌธ ์ˆ˜ํ–‰ #>>>j์˜ for๋ฌธ์ด ์ „์ฒด ์ˆ˜ํ–‰๋˜๊ณ  ๋์ด ๋‚˜์•ผ i๊ฐ€ 2์ผ ๋•Œ ์ˆ˜ํ–‰ 1ํšŒ๊ฐ€ ๋ for j in range(1,10): print("{} x {} = {}".format(i,j,(i*j))) ''' 1. 1๋ถ€ํ„ฐ ์ž…๋ ฅ ๋ฐ›์€ ์ˆ˜๊นŒ์ง€ '์ง์ˆ˜'์˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ์ˆซ์ž ์ž…๋ ฅ : 5 1~5๊นŒ์ง€ ์ง์ˆ˜์˜ ํ•ฉ์€ 6์ž…๋‹ˆ๋‹ค. ''' ''' hab = 0 num = int(input("์ˆซ์ž ์ž…๋ ฅ :")) for i in range(0,num+1,2): hab += i print("1~{}๊นŒ์ง€ ์ง์ˆ˜์˜ ํ•ฉ์€ {} ์ž…๋‹ˆ๋‹ค.".format(num,hab)) ''' ''' 2. 1๋ถ€ํ„ฐ 200๊นŒ์ง€ 3๊ณผ 4์˜ ๊ณต๋ฐฐ์ˆ˜๋ฅผ ํ•˜๋‚˜์˜ ๋ณ€์ˆ˜์— '๋ˆ„์ ' ๋ˆ„์ ๋œ ์ˆ˜๊ฐ€ 1000์„ ์ดˆ๊ณผํ•˜๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ 'ํƒˆ์ถœ' ์ด๋•Œ, ๋ˆ„์ ๋œ ์ˆ˜์™€ ๋งˆ์ง€๋ง‰์— ๋”ํ–ˆ๋˜ ๊ณต๋ฐฐ์ˆ˜๋ฅผ ์ถœ๋ ฅ [์ถœ๋ ฅ๊ฒฐ๊ณผ] ๋ˆ„์ ๋œ ์ˆ˜ : 1092 ๋”ํ•œ ์ˆ˜ : 156 ''' ''' hab = 0 for i in range(1,201,1): if i % 3 == 0 and i % 4 ==0 : hab += i if hab > 1000 : break print("๋ˆ„์ ๋œ ์ˆ˜ :",hab) print("๋”ํ•œ ์ˆ˜ :",i) ''' ''' 3. 1~100 ์‚ฌ์ด ์ •์ˆ˜ ์ค‘, 3์˜ ๋ฐฐ์ˆ˜์™€ 5์˜ ๋ฐฐ์ˆ˜๋ฅผ '์—ญ์ˆœ'์œผ๋กœ ์ถœ๋ ฅ ๋‹จ, 3๊ณผ 5์˜ ๊ณต๋ฐฐ์ˆ˜๋Š” <15> ์ฒ˜๋Ÿผ ์ถœ๋ ฅ [์ถœ๋ ฅ๊ฒฐ๊ณผ] 100 99 96 95 93 <90> 87 ... 5 3 ''' for i in reversed(range(1,101,1)): if i % 3 == 0 or i % 5 ==0 : if i % 3 == 0 and i % 5 == 0: print("<{}>".format(i),end=" ") else: print("{}".format(i),end=" ") ''' ๋‚œ์ด๋„ <์ƒ> 4. 2์ค‘for๋ฌธ ๊ตฌ๊ตฌ๋‹จ ์˜ˆ์ œ๋ฅผ for๋ฌธ 1๊ฐœ๋งŒ ์‚ฌ์šฉํ•ด์„œ ๋งŒ๋“ค์–ด๋ณด๊ธฐ - ์ด ๋ฐ˜๋ณต ํšŸ์ˆ˜ = 72ํšŒ - ์ฒ˜์Œ ๋‹จ์€ 2 - ๊ณฑํ•ด์ง€๋Š” ์ˆซ์ž๋Š” ์ฒ˜์Œ์ด 1 - 9ํšŒ ์ˆ˜ํ–‰๋งˆ๋‹ค, ๋‹จ์ด 1 ์ฆ๊ฐ€, ๊ณฑํ•ด์ง€๋Š” ์ˆซ์ž๋Š” 1๋กœ ๋ณ€๊ฒฝ ''' for i in range(18,90,1): dan = i // 9 gob = i % 9 + 1 print("{} X {} = {}".format(dan,gob,(dan*gob)))
6625d06d25c115fca416aeea270b1a49b3360f13
hanmaslah/andela_bootcamp
/andela_vc_factorial.py
173
4.0625
4
def fact(x): if x<0: return "No fact for negatives" elif x==0: return 1 else: return x*fact(x-1) import math #using the inbuilt factorial method math.factorial (5)
c42ca56ac3941f23346666c422fb1bbcad24eb5b
neetukumari4858/dictionory-in-python
/deepa .py
285
3.546875
4
l=[] def div(a): i=0 while i <len(a): if a[i]%3==0: l.append(a[i]) i=i+1 return(l) k=div([15,60,9,30,35,27,45]) def div1(): p=[] j=0 while j<len(l): if l[j]%5==0: p.append(l[j]) j=j+1 print(p) div1()
f43a58c8189d825aaaa0571f87a639e9c6ddb534
shakul12/leetCode
/LinkedList/swapNodesPair.py
582
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list def swapPairs(self, A): head=A prev=A curr=A.next while curr: temp=prev.val prev.val=curr.val curr.val=temp prev= curr.next if curr.next: curr=curr.next.next else: curr=None return head
775c8cc249a555040f0310ecca31dd7af93e8d2e
gabriellaec/desoft-analise-exercicios
/backup/user_373/ch21_2020_04_12_22_45_50_997340.py
200
3.578125
4
dias= input('Dias: ') horas= input ('Horas: ') minutos= input ('Minutos: ') segundos= input ('Segundos: ') total_segundos= (dias*24*60*60 + horas*60*60 + minutos*60 +segundos) print (total_segundos)
8a9733f3f67ff889b3cf9b164b754f9a5c48c8b0
chrisvle/random_name_generator
/rng.py
2,128
3.59375
4
import tkinter as tk import random import time root = tk.Tk(className = 'Random Name Generator') w = 800 h = 600 ws = root.winfo_screenwidth() hs = root.winfo_screenheight() x = (ws/2) - (w/2) y = (hs/2) - (h/2) root.geometry('%dx%d+%d+%d' % (w, h, x, y)) class Window: def __init__(self, master): self.frame = tk.Frame(master) self.text = tk.StringVar() self.ranNameLabel = tk.Label(self.frame, textvariable = self.text, font=("Helvetica", 40), height = 3, width = 15) self.genButton = tk.Button(self.frame, text = 'Generate Random Name', command = self.genRanName, font = ('Helvertica', 18)) self.ranNameLabel.grid(row = 0) self.genButton.grid(row = 1) self.frame.grid() self.NAMES = ['alfonso', 'cale', 'chris', 'colin', 'derrick', 'jeffrey', 'jessica', 'rohit', 'tammy', 'will', 'yulin', 'albert', 'robert'] self.USED = [] def genRanName(self): i = 0 while i <= 50: root.update() if i > 30: time.sleep(0.4) self.helper() elif i > 40: time.sleep(0.6) self.helper() elif i > 45: time.sleep(1) self.helper() else: time.sleep(0.2) self.helper() if i == 50: name = self.text.get() self.USED.append(name) self.NAMES.remove(name) if not self.NAMES: self.NAMES = self.USED self.USED = [] i += 1 def helper(self): fonts = "#"+("%06x"%random.randint(0,16777215)) backgrounds = "#"+("%06x"%random.randint(0,16777215)) self.frame.configure(background = backgrounds) self.genButton.configure(highlightbackground = backgrounds) self.ranNameLabel.config(foreground = fonts) self.text.set(random.choice(self.NAMES)) def main(): app = Window(root) app.frame.configure(padx=250, pady=225, height=300) root.mainloop() if __name__ == '__main__': main()
f0fbb05df86c1243b9649eb7ca7d5d1eee816aa4
orimamo/check-bot
/exercises middel/targil-3.py
120
3.734375
4
a=input("enter your first name : ") b=input("enter your last name : ") full= (a + " " + b) print(full) print(full[::-1])
cdfffc41e35a60ade6032f9b8522a8751e8e8821
malavikasrinivasan/D06
/HW06_ch09_ex02.py
1,157
4.40625
4
#!/usr/bin/env python3 # HW06_ch09_ex02.py # (1) # Write a function called has_no_e that returns True if the given word doesn't # have the letter "e" in it. # - write has_no_e # (2) # Modify your program from 9.1 to print only the words that have no "e" and # compute the percentage of the words in the list have no "e." # - print each approved word on new line, followed at the end by the % # - name your function print_no_e ############################################################################## # Imports # Body def has_no_e(word): if word.find('e') == -1: return True else: return False def print_no_e(filename): with open(filename, "r") as f: words = f.readlines() total_words = len(words) words_without_e = 0 for word in words: if has_no_e(word.strip()): print(word.strip()) words_without_e += 1 print("{:.2%} of all the words in the file have no e".format(words_without_e/total_words)) ############################################################################## def main(): print_no_e("words.txt") if __name__ == '__main__': main()
653e7187c476e4d16739a8064e4548c0ec4068a8
gbaghdasaryan94/Kapan
/HaykAmirjanyan/classroom/Strings and console output/strhw9.py
251
4.25
4
# Write a Python program that accepts a # comma separated sequence of words as input and prints # the unique words in sorted form (alphanumerically). st = input("Enter the string: ") arr = st.split(',') arr.sort() arr = set(arr) print(",".join(arr))
69a52e611e679feeb0e908136912b929af9ac8e7
paulozava/exerciscm
/python/phone-number/phone_number.py
1,154
3.84375
4
class Phone(object): def __init__(self, phone_number): self._raw_number = phone_number self._cleaned_number = self._parse_number() self.area_code = self._cleaned_number[:3] self.max_region = self._cleaned_number[3:6] self.min_region = self._cleaned_number[6:] def _parse_number(self): number = self._raw_number clean_number = ''.join([digit for digit in number if digit not in '()- .+']) if not clean_number.isdigit(): raise ValueError('Invalid digits') if not self._is_valid_number(clean_number): raise ValueError('It is not a valid number') return clean_number[1:] if len(clean_number) == 11 else clean_number def _is_valid_number(self, number): is_valid_area_exc = lambda x, y: x not in '01' and y not in '01' if len(number) == 11 and number[0] == '1': number = number[1:] return len(number) == 10 and is_valid_area_exc(number[0], number[3]) def number(self): return self._cleaned_number def pretty(self): return f'({self.area_code}) {self.max_region}-{self.min_region}'
b665cb5ee24a233af4e29448ce9ea5f609d9ba2d
Yaphel/py_interview_code
/ๅ‰‘ๆŒ‡OFFER/ๆ ˆๅ’Œ้˜Ÿๅˆ—/ไธคไธชๆ ˆๅฎž็Žฐ้˜Ÿๅˆ—.py
1,187
3.734375
4
class Node(object): def __init__(self,data,next = None): self.data = data self.next = next class Stack(object): def __init__(self, top = None): self.top = top def push(self,data): self.top = Node(data, self.top) def push_arr(self,arr): arr_len=len(arr) for i in range(arr_len): self.push(arr[i]) return self def pop(self): if self.top is None: return None data = self.top.data self.top = self.top.next return data def pop_all(self): arr=[] a=self.pop() while a: arr.append(a) a=self.pop() return arr def isEmpty(self): return self.peek() is None class Quene(object): def __init__(self,s1,s2): #s1ๆ˜ฏmasterๆ ˆ #s2ๆ˜ฏslaveๆ ˆ self.s1=s1 self.s2=s2 def pop(self): self.s2.push_arr(self.s1.pop_all()) print("Quene pop value : " ,self.s2.pop()) s=self.s2 self.s2=self.s1 self.s1=s def push(self,data): self.s1.push(data) import unittest class MyTest(unittest.TestCase): def test_01(self): q=Quene(Stack().push_arr([1,2]),Stack()) q.pop() q.push(3) q.pop() q.pop() if __name__ == '__main__': unittest.main()
d3f0bbe59d9a89519271d574312f2a16721206e5
tiankuncampus/leetcode
/search_in_rotated_sorted_arry.py
1,304
3.671875
4
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': if len(nums)==0: return -1 position = self.find_rotate_pos(nums) result = self.binary_search(nums[0:position], target) if (result != -1): return result result = self.binary_search(nums[position:], target) if (result != -1): return position+result return -1 def binary_search(self, nums, target): if len(nums)==0: return -1 start = 0 end = len(nums) - 1 while (start < end): m = (start + end)//2 if(nums[m] > target): end -= 1 elif (nums[m] < target): start += 1 else: return m if (nums[start] == target): return start else: return -1 def find_rotate_pos(self, nums): start = 0 end = len(nums) - 1 first = nums[0] while(start < end): candidate = (start + end)//2 temp = nums[candidate] if (temp < first): end -= 1 else: start += 1 return start s=Solution() print(s.search([1,1,1,1],2))
843e7864bca54509ae1a3c372b3daa62e635f5df
Sujan242/DAA-Lab
/Lab 5/majority_element.py
962
3.671875
4
# https://practice.geeksforgeeks.org/problems/majority-element/0 def majority(l , low , high): if low==high: return l[low] mid = int((low+high)/2) left = majority(l,low,mid) right = majority(l , mid+1 , high) if left==right: return left left_freq = 0 right_freq = 0 for i in range(low,mid+1): if l[i]==left: left_freq+=1 for i in range(mid+1 , high+1): if l[i]==right: right_freq+=1 if left_freq>right_freq: return left return right def main(): t=int(input()) while t>0: n=int(input()) l=input().split() for i in range(n): l[i]=int(l[i]) a = majority(l,0,n-1) freq=0 for i in range(n): if a==l[i]: freq+=1 if freq>(n/2): print(a) else: print(-1) t-=1 main()
259b66bca99a67da620acb0f71ca61c685ec7049
ataluzz/EpamPython2019
/06-advanced-python/hw/task3.py
555
3.625
4
"""" ะ ะตะฐะปะธะทะพะฒะฐั‚ัŒ ะบะพะฝั‚ะตะบัั‚ะฝั‹ะน ะผะตะฝะตะดะถะตั€, ะบะพั‚ะพั€ั‹ะน ะฟะพะดะฐะฒะปัะตั‚ ะฟะตั€ะตะดะฐะฝะฝั‹ะต ะธัะบะปัŽั‡ะตะฝะธั with Suppressor(ZeroDivisionError): 1/0 print("It's fine") """ class Suppressor: def __init__(self, *error_names): self.error_names = error_names def __enter__(self): pass def __exit__(self, exp_type, exp_value, exp_traceback): return issubclass(exp_type, self.error_names) with Suppressor(ZeroDivisionError): 1/0 print("It's fine")
4da7dd0923beaf3e0bc6ef3932a569d120931919
skyla15/HireMeProject-
/1_DataStructure_Algo/DataStructure(Goodrich)/6_Stack_Queue_Deque/_6_3_3_Deque.py
2,426
3.625
4
class Deque(object): DEFAULT_CAPICITY = 5 def __init__(self): self._size = 0 self._front = 0 self._data = [None]*Deque.DEFAULT_CAPICITY def __len__(self): return self._size def add_first(self, e): if self._size == len(self._data): self.resize(len(self._data)*2) if not self.is_empty(): # if the front index already has an element, advance the front leftward self._front = ( self._front - 1 ) % len(self._data) self._data[self._front] = e self._size += 1 def add_last(self, e): if self._size == len(self._data): self.resize(len(self._data)*2) back = ( self._front + self._size ) % len(self._data) self._data[back] = e self._size += 1 def delete_first(self): assert not self.is_empty(), 'Deque Empty' e = self._data[self._front] self._data[self._front] = None self._front = (self._front + 1) % len(self._data) self._size -= 1 if 0 < self._size < len(self._data)//4: self.resize(len(self._data)//2) return e def delete_last(self): assert not self.is_empty(), 'Deque Empty' back = (self._front + self._size - 1) % len(self._data) e = self._data[back] self._data[back] = None self._size -= 1 if 0 < self._size < len(self._data)//4: self.resize(len(self._data)//2) return e def first(self): assert not self.is_empty(), 'Deque Empty' return self._data[self._front] def last(self): assert not self.is_empty(), 'Deque Empty' back = (self._front + self._size - 1) % len(self._data) return self._data[back] def is_empty(self): return self._size == 0 def resize(self, new_size): old_data = self._data temp_front = self._front self._data = [None]*new_size for i in range(self._size): self._data[i] = old_data[temp_front] temp_front = (temp_front + 1) % len(old_data) self._front = 0 def display(self): print(self._data) def main(): print('main') D = Deque() D.add_first(1) D.display() D.add_first(2) D.display() D.add_first(3) D.display() D.add_first(4) D.display() D.add_first(5) D.display() D.add_last(6) D.display() D.add_last(7) D.display() D.add_last(8) D.display() print(len(D)) print(D.delete_first()) D.display() print(D.delete_first()) D.display() print(D.delete_first()) D.display() print(D.delete_last()) D.display() print(D.delete_last()) D.display() print(D.delete_last()) D.display() print(D.delete_last()) D.display() print(D.delete_last()) D.display() main()
e2ab0a6b5f834da36da9c43a403a5cbf2d0cdc65
disha2sinha/Data-Structures-and-Algorithms
/DATA-STRUCTURES/Stack/PostfixEvaluation.py
835
4.21875
4
def operation(op1, op2, operator): if operator == "+": return op1+op2 if operator == "-": return op1-op2 if operator == "*": return op1*op2 if operator == "/": return op1/op2 if operator == "^": return op1^op2 def evaluate(exp_list): stack = [] for i in range(len(exp_list)): if exp_list[i] == '+' or exp_list[i] == '-' or exp_list[i] == '/' or exp_list[i] == '*' or exp_list == '^': operand1 = int(stack.pop()) operand2 = int(stack.pop()) stack.append(operation(operand2, operand1, exp_list[i])) else: stack.append(exp_list[i]) return stack[-1] expression = input("Enter Postfix Expression: ") exp_list = list(expression) e = evaluate(exp_list) print("Result :",e)
63833c86823fc876255ad87cdd42149ab39de90c
erija952/project-euler
/python/p14/p14.py
493
3.59375
4
#!/usr/bin/python def collatz(startNum): seql = 1 while startNum > 1: if startNum % 2==0 : startNum = startNum / 2 else : startNum = 3 * startNum + 1 seql +=1 return seql startNum = 1000000 gseql = 0 gNum = 0; while startNum > 1 : seql = collatz(startNum) if seql > gseql: gNum = startNum gseql = seql; print "New greatest: Seq length " + str(gseql) + " of nr: " + str(gNum) startNum -= 1
1206fcf2ce376d7e2857236af3d7735fafdac791
jb240707/Google_IT_Automation_Python
/Crash Course on Python/crashcourse_notes_script.py
31,085
4.40625
4
""" Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km". """ def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format(miles, km) return result print(convert_distance(12)) # Should be: 12 miles equals 19.2 km print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km print(convert_distance(11)) # Should be: 11 miles equals 17.6 km """ The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made). """ def replace_ending(sentence, old, new): # Check if the old string is at the end of the sentence if sentence.endswith(old): # Using i as the slicing index, combine the part # of the sentence up to the matched string at the # end with the new string i = len(sentence) - len(old) new_sentence = sentence[:i] + new return new_sentence # Return the original sentence if there is no match return sentence print(replace_ending("It's raining cats and cats", "cats", "dogs")) # Should display "It's raining cats and dogs" print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) # Should display "She sells seashells by the seashore" print(replace_ending("The weather is nice in May", "may", "april")) # Should display "The weather is nice in May" print(replace_ending("The weather is nice in May", "May", "April")) # Should display "The weather is nice in April" """ Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position. """ def skip_elements(elements): # code goes here a = len(elements) return elements[0:a:2] # Should be ['a', 'c', 'e', 'g'] print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) """ The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1. """ def odd_numbers(n): return [x for x in range(1, n + 1) if x % 2 != 0] print(odd_numbers(5)) # Should print [1, 3, 5] print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9] print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11] print(odd_numbers(1)) # Should print [1] print(odd_numbers(-1)) # Should print [] """ Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods youโ€™ve learned thus far, like a for loop or a list comprehension. """ filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] # Generate newfilenames as a list containing the new filenames newfilenames = [] # using as many lines of code as your chosen method requires. for x in range(len(filenames)): if x <= len(filenames): if filenames[x].endswith("hpp"): result = filenames[x].replace('hpp', 'h') newfilenames.append(result) else: newfilenames.append(filenames[x]) print(newfilenames) # Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"] """ Let's create a function that turns text into pig latin: a simple text transformation that modifies each word moving the first character to the end and appending "ay" to the end. For example, python ends up as ythonpay. """ def pig_latin(text): say = "" # Separate the text into words q = [] words = text.split() for word in words: # Create the pig latin word and add it to the list q.append(word[1:] + word[0] + "ay") # Turn the list back into a phrase say = " ".join(q) return say print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" # Should be "rogrammingpay niay ythonpay siay unfay" print(pig_latin("programming in python is fun")) """ The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or - when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: "rw-r-----" 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: "rwxr-xr-x" Fill in the blanks to make the code convert a permission in octal format into a string format. """ def octal_to_string(octal): result = "" value_letters = [(4, "r"), (2, "w"), (1, "x")] # Iterate over each of the digits in octal for x in [int(n) for n in str(octal)]: # Check for each of the permissions values for value, letter in value_letters: if x >= value: result += letter x -= value else: result += "-" return result print(octal_to_string(755)) # Should be rwxr-xr-x print(octal_to_string(644)) # Should be rw-r--r-- print(octal_to_string(750)) # Should be rwxr-x--- print(octal_to_string(600)) # Should be rw------- """ The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, โ€ฆ For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that. """ def group_list(group, users): members = ", ".join(users) return "{}: {}".format(group, members) # Should be "Marketing: Mike, Karen, Jake, Tasha" print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Engineering: Kim, Jay, Tom" print(group_list("Engineering", ["Kim", "Jay", "Tom"])) print(group_list("Users", "")) # Should be "Users:" """ The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that. """ def guest_list(guests): for name, age, prof in guests: print("{} is {} years old and works as {}".format(name, age, prof)) guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) """ Output should match: Ken is 30 years old and works as Chef Pat is 35 years old and works as Lawyer Amanda is 25 years old and works as Engineer """ """ The "toc" dictionary represents the table of contents for a book. Fill in the blanks to do the following: 1) Add an entry for Epilogue on page 39. 2) Change the page number for Chapter 3 to 24. 3) Display the new dictionary contents. 4) Display True if there is Chapter 5, False if there isn't. """ toc = {"Introduction": 1, "Chapter 1": 4, "Chapter 2": 11, "Chapter 3": 25, "Chapter 4": 30} toc["Epilogue"] = 39 # Epilogue starts on page 39 toc["Chapter 3"] = 24 # Chapter 3 now starts on page 24 print(toc) # What are the current contents of the dictionary? print("Chapter 5" in toc) # Is there a Chapter 5? """ Now, it's your turn! Have a go at iterating over a dictionary! Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary. """ cool_beasts = {"octopuses": "tentacles", "dolphins": "fins", "rhinos": "horns"} for beasts, parts in cool_beasts.items(): print("{} have {}".format(beasts, parts)) """ In Python, a dictionary can only hold a single value for a given key. To workaround this, our single value can be a list containing multiple values. Here we have a dictionary called "wardrobe" with items of clothing and their colors. Fill in the blanks to print a line for each item of clothing with each color, for example: "red shirt", "blue shirt", and so on. """ wardrobe = {"shirt": ["red", "blue", "white"], "jeans": ["blue", "black"]} for item in wardrobe: for key in wardrobe[item]: print("{} {}".format(key, item)) """ The email_list function receives a dictionary, which contains domain names as keys, and a list of users as values. Fill in the blanks to generate a list that contains complete email addresses (e.g. diana.prince@gmail.com). """ def email_list(domains): emails = [] for domain, users in domains.items(): for user in users: emails.append("{}@{}".format(user, domain)) return(emails) print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": [ "barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]})) """ The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values. """ def groups_per_user(group_dictionary): user_groups = {} for group, users in group_dictionary.items(): for user in users: user_groups.setdefault(user, []).append(group) return(user_groups) print(groups_per_user({"local": ["admin", "userA"], "public": ["admin", "userB"], "administrator": ["admin"]})) """ The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function. """ def add_prices(basket): # Initialize the variable that will be used for the calculation total = 0 # Iterate through the dictionary items for value in basket.values(): # Add each price to the total calculation # Hint: how do you access the values of # dictionary items? total += value # Limit the return value to 2 decimal places return round(total, 2) groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59, "coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44} print(add_prices(groceries)) # Should print 28.44 """ The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function. """ def format_address(address_string): # Declare variables address = address_string.split(" ") # Determine if the address part is the # house number or part of the street name house_number = address[0] street_name = address[1:] # Does anything else need to be done # before returning the result? street_name = " ".join(street_name) # Return the formatted string return "house number {} on street named {}".format(house_number, street_name) print(format_address("123 Main Street")) # Should print: "house number 123 on street named Main Street" print(format_address("1001 1st Ave")) # Should print: "house number 1001 on street named 1st Ave" print(format_address("55 North Center Drive")) # Should print "house number 55 on street named North Center Drive" """ The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word("Have a nice day", "nice") returns "Have a NICE day". Can you write this function in just one line? """ def highlight_word(sentence, word): return sentence.replace(word, word.upper()) print(highlight_word("Have a nice day", "nice")) print(highlight_word("Shhh, don't be so loud!", "laoud")) print(highlight_word("Automating with Python is fun", "fun")) """ A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student's arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew's list, followed by Jamie's list in reverse order, to get an accurate list of the students as they arrived. """ def combine_lists(list1, list2): # Generate a new list containing the elements of list2 # Followed by the elements of list1 in reverse order return list2 + list1[::-1] Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"] Drews_list = ["Mike", "Carol", "Greg", "Marcia"] print(combine_lists(Jamies_list, Drews_list)) """ Use a list comprehension to create a list of squared numbers (n*n). The function receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4, 9]. """ def squares(start, end): return [n * n for n in range(start, end + 1)] print(squares(2, 3)) # Should be [4, 9] print(squares(1, 5)) # Should be [1, 4, 9, 16, 25] print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] """ Complete the code to iterate through the keys and values of the car_prices dictionary, printing out some information about each one. """ def car_listing(car_prices): result = "" for car, price in car_prices.items(): result += "{} costs {} dollars".format(car, price) + "\n" return result print(car_listing({"Kia Soul": 19000, "Lamborghini Diablo": 55000, "Ford Fiesta": 13000, "Toyota Prius": 24000})) """ Taylor and Rory are hosting a party. They sent out invitations, and each one collected responses into dictionaries, with names of their friends and how many guests each friend is bringing. Each dictionary is a partial list, but Rory's list has more current information about the number of guests. Fill in the blanks to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rory's dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary. """ def combine_guests(guests1, guests2): # Combine both dictionaries into one, with each key listed # only once, and the value from guests1 taking precedence consolidated = {} consolidated.update(guests2) consolidated.update(guests1) return consolidated Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4} Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5} print(combine_guests(Rorys_guests, Taylors_guests)) """ Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}""" def count_letters(text): result = {} text = ''.join(c for c in text.lower() if c.isalpha()) # Go through each letter in the text for letter in text: # Check if the letter needs to be counted or not # Add or increment the value in the dictionary if letter not in result: result[letter] = 1 else: result[letter] += 1 return result print(count_letters("AaBbCc")) # Should be {'a': 2, 'b': 2, 'c': 2} print(count_letters("Math is fun! 2+2=4")) # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1} print(count_letters("This is a sentence.")) # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1} colors = ["red", "white", "blue"] colors.insert(2, "yellow") print(colors) animal = "Hippopotamus" print(animal[3:6]) print(animal[-5]) print(animal[10:]) host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"} print(host_addresses.keys()) """ Want to give this a go? Fill in the blanks in the code to make it print a poem. """ class Flower: color = 'unknown' rose = Flower() rose.color = "red" violet = Flower() violet.color = "blue" this_pun_is_for_you = "Dude!" print("Roses are {},".format(rose.color)) print("violets are {},".format(violet.color)) print(this_pun_is_for_you) """ Creating new instances of class objects can be a great way to keep track of values using attributes associated with the object. The values of these attributes can be easily changed at the object level. The following code illustrates a famous quote by George Bernard Shaw, using objects to represent people. Fill in the blanks to make the code satisfy the behavior described in the quote. """ # โ€œIf you have an apple and I have an apple and we exchange these apples then # you and I will still each have one apple. But if you have an idea and I have # an idea and we exchange these ideas, then each of us will have two ideas.โ€ # George Bernard Shaw class Person: apples = 0 ideas = 0 johanna = Person() johanna.apples = 1 johanna.ideas = 1 martin = Person() martin.apples = 2 martin.ideas = 1 def exchange_apples(you, me): # Here, despite G.B. Shaw's quote, our characters have started with # different amounts of apples so we can better observe the results. # We're going to have Martin and Johanna exchange ALL their apples with #one another. # Hint: how would you switch values of variables, # so that "you" and "me" will exchange ALL their apples with one another? # Do you need a temporary variable to store one of the values? # You may need more than one line of code to do that, which is OK. temp = you.apples you.apples = me.apples me.apples = temp return you.apples, me.apples def exchange_ideas(you, me): # "you" and "me" will share our ideas with one another. # What operations need to be performed, so that each object receives # the shared number of ideas? # Hint: how would you assign the total number of ideas to # each idea attribute? Do you need a temporary variable to store # the sum of ideas, or can you find another way? # Use as many lines of code as you need here. temp = you.ideas you.ideas += me.ideas me.ideas += temp return you.ideas, me.ideas exchange_apples(johanna, martin) print("Johanna has {} apples and Martin has {} apples".format( johanna.apples, martin.apples)) exchange_ideas(johanna, martin) print("Johanna has {} ideas and Martin has {} ideas".format( johanna.ideas, martin.ideas)) """ The City class has the following attributes: name, country (where the city is located), elevation (measured in meters), and population (approximate, according to recent statistics). Fill in the blanks of the max_elevation_city function to return the name of the city and its country (separated by a comma), when comparing the 3 defined instances for a specified minimal population. For example, calling the function for a minimum population of 1 million: max_elevation_city(1000000) should return "Sofia, Bulgaria". """ # define a basic city class class City: name = "" country = "" elevation = 0 population = 0 # create a new instance of the City class and # define each attribute city1 = City() city1.name = "Cusco" city1.country = "Peru" city1.elevation = 3399 city1.population = 358052 # create a new instance of the City class and # define each attribute city2 = City() city2.name = "Sofia" city2.country = "Bulgaria" city2.elevation = 2290 city2.population = 1241675 # create a new instance of the City class and # define each attribute city3 = City() city3.name = "Seoul" city3.country = "South Korea" city3.elevation = 38 city3.population = 9733509 def max_elevation_city(min_population): # Initialize the variable that will hold # the information of the city with # the highest elevation return_city = City() # Evaluate the 1st instance to meet the requirements: # does city #1 have at least min_population and # is its elevation the highest evaluated so far? if city1.population >= min_population and city1.elevation > return_city.elevation: return_city = city1 # Evaluate the 2nd instance to meet the requirements: # does city #2 have at least min_population and # is its elevation the highest evaluated so far? if city2.population >= min_population and city2.elevation > return_city.elevation: return_city = city2 # Evaluate the 3rd instance to meet the requirements: # does city #3 have at least min_population and # is its elevation the highest evaluated so far? if city3.population >= min_population and city3.elevation > return_city.elevation: return_city = city3 # Format the return string if return_city.name: return ("{}, {}".format(return_city.name, return_city.country)) else: return "" print(max_elevation_city(100000)) # Should print "Cusco, Peru" print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria" print(max_elevation_city(10000000)) # Should print "" """ We have two pieces of furniture: a brown wood table and a red leather couch. Fill in the blanks following the creation of each Furniture class instance, so that the describe_furniture function can format a sentence that describes these pieces as follows: "This piece of furniture is made of {color} {material}" """ class Furniture: color = "" material = "" table = Furniture() table.color = "brown" table.material = "wood" couch = Furniture() couch.color = "red" couch.material = "leather" def describe_furniture(piece): return ("This piece of furniture is made of {} {}".format(piece.color, piece.material)) print(describe_furniture(table)) # Should be "This piece of furniture is made of brown wood" print(describe_furniture(couch)) # Should be "This piece of furniture is made of red leather" """ Letโ€™s test your knowledge of using dot notation to access methods and attributes in an object. Letโ€™s say we have a class called Birds. Birds has two attributes: color and number. Birds also has a method called count() that counts the number of birds (adds a value to number). Which of the following lines of code will correctly print the number of birds? Keep in mind, the number of birds is 0 until they are counted! """ class Birds: color = "" number = 0 bluejay = Birds() bluejay.color = "blue" bluejay.number = 1 print(bluejay.number) """ OK, now itโ€™s your turn! Have a go at writing methods for a class. Create a Dog class with dog_years based on the Piglet class shown before (one human year is about 7 dog years). """ class Dog: years = 0 def dog_years(self): return self.years * 7 fido = Dog() fido.years = 3 print(fido.dog_years()) """ Want to see this in action? In this code, there's a Person class that has an attribute name, which gets set when constructing the object. Fill in the blanks so that 1) when an instance of the class is created, the attribute gets set correctly, and 2) when the greeting() method is called, the greeting states the assigned name. """ class Person: def __init__(self, name): self.name = name def greeting(self): # Should return "hi, my name is " followed by the name of the Person. return "hi, my name is {}".format(self.name) # Create a new instance with a name of your choice some_person = Person("steph") # Call the greeting method print(some_person.greeting()) """ Remember our Person class from the last video? Letโ€™s add a docstring to the greeting method. How about, โ€œOutputs a message with the name of the personโ€. """ class Person: def __init__(self, name): self.name = name def greeting(self): "Outputs a message with the name of the person" print("Hello! My name is {name}.".format(name=self.name)) help(Person) """ The code below defines an Elevator class. The elevator has a current floor, it also has a top and a bottom floor that are the minimum and maximum floors it can go to. Fill in the blanks to make the elevator go through the floors requested. """ class Elevator: def __init__(self, bottom, top, current): """Initializes the Elevator instance.""" self.bottom = 0 self.top = 10 self.current = 0 def up(self): """Makes the elevator go up one floor.""" if self.current == 10: self.current += 0 else: self.current += 1 def down(self): """I'm assuming the lowest floor the elevator can go is -1""" """Makes the elevator go down one floor.""" if self.current <= -1: self.current -= 0 else: self.current -= 1 def go_to(self, floor): """Makes the elevator go to the specific floor.""" self.current = floor def __str__(self): return "Current floor: {}".format(self.current) elevator = Elevator(-1, 10, 0) elevator.up() print(elevator.current) # should output 1 elevator.down() print(elevator.current) # should output 0 elevator.go_to(10) print(elevator.current) # should output 10 # Go to the top floor. Try to go up, it should stay. Then go down. elevator.go_to(10) elevator.up() elevator.down() print(elevator.current) # should be 9 # Go to the bottom floor. Try to go down, it should stay. Then go up. elevator.go_to(-1) elevator.down() elevator.down() elevator.up() elevator.up() print(elevator.current) # should be 1 elevator.go_to(5) print(elevator) """ Letโ€™s create a new class together and inherit from it. Below we have a base class called Clothing. Together, letโ€™s create a second class, called Shirt, that inherits methods from the Clothing class. Fill in the blanks to make it work properly. """ class Clothing: material = "" def __init__(self, name): self.name = name def checkmaterial(self): print("This {} is made of {}".format(self.name, self.material)) class Shirt(Clothing): material = "Cotton" polo = Shirt("Polo") polo.checkmaterial() """ Letโ€™s expand a bit on our Clothing classes from the previous in-video question. Your mission: Finish the "Stock_by_Material" method and iterate over the amount of each item of a given material that is in stock. When youโ€™re finished, the script should add up to 10 cotton Polo shirts. """ class Clothing: stock = {'name': [], 'material': [], 'amount': []} def __init__(self, name): material = "" self.name = name def add_item(self, name, material, amount): Clothing.stock['name'].append(self.name) Clothing.stock['material'].append(self.material) Clothing.stock['amount'].append(amount) def Stock_by_Material(self, material): count = 0 n = 0 for item in Clothing.stock['material']: if item == material: count += Clothing.stock['amount'][n] n += 1 return count class shirt(Clothing): material = "Cotton" class pants(Clothing): material = "Cotton" polo = shirt("Polo") sweatpants = pants("Sweatpants") polo.add_item(polo.name, polo.material, 4) sweatpants.add_item(sweatpants.name, sweatpants.material, 6) current_stock = polo.Stock_by_Material("Cotton") print(current_stock) """ Animals at the Zoo Jupyter notebook """ class Animal: name = "" category = "" def __init__(self, name): self.name = name def set_category(self, category): self.category = category class Turtle: name = "" category = "reptile" def __init__(self, name): self.name = name def set_category(self, category): self.category = category print(Turtle.category) class Snake: name = "" category = "reptile" def __init__(self, name): self.name = name def set_category(self, category): self.category = category print(Snake.category) class Zoo: def __init__(self): self.current_animals = {} def add_animal(self, animal): self.current_animals[animal.name] = animal.category def total_of_category(self, category): result = 0 for animal in self.current_animals.values(): if animal == category: result += 1 return result zoo = Zoo() turtle = Turtle("Turtle") # create an instance of the Turtle class snake = Snake("Snake") # create an instance of the Snake class zoo.add_animal(turtle) zoo.add_animal(snake) # how many zoo animal types in the reptile category print(zoo.total_of_category("reptile"))
a04d653f0c22bcc3de9fb24e0a7cc9fa05faf565
sailusm/LuminarPython
/flowcotrol/looping/reverse.py
125
3.734375
4
num=int(input("Enter a number:")) # temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 print(rev)
5143f27f3756017024b2a9df1d0b475ef7f69dba
YXMforfun/_checkio-solution
/home/pearls-box.py
2,447
4.40625
4
""" While Stephen is running cargo, Nicola and Sophia invented a game using the boxes. To start the game, they put several black and white pearls in one of the boxes. Each robots have Nth moves, then initial set are restored for a next player. For each move, the robot take a pearl out of the box and put one of the opposite color back. The winner is the one who pulls the white pearl on the Nth step (or +1 point if they play many parties). Our robots don't like indeterminacy and want to know the probability of a white pearl on the Nth step. The probability is a value between 0 (0% chance or will not happen) and 1 (100% chance or will happen). The result is a float from 0 to 1 with two digits precision (ยฑ0.01). You are given a start set of pearls as a string that contains "b" (black) and "w" (white) and the number of the step (N). The order of the pearls does not matter. Input: The start sequence of the pearls as a string and the step number as an integer. Output: The probability for a white pearl as a float. Precondition: 0 < N โ‰ค 20 0 < |pearls| โ‰ค 20 """ # Consider the process as a decision tree. Focus on the probability from itertools import product def checkio(marbles, step): def calculate(pearls): length = len(marbles) white = marbles.count('w') ratio = 1 for i in pearls: if i == 'w': ratio *= (white/length) white -= 1 else : ratio *= 1- (white/length) white += 1 if white < 0 or white > length: return 0 return ratio * (white/length) return round(sum(calculate(l) for l in product(['w','b'], repeat=step-1)), 2) #recursion def checio1(marbles, step): white_rate = marbles.count('w') / len(marbles) black_rate = 1 - white_rate if step == 1: return white_rate else : return sum([ white_rate * checkio1(marbles.replace('w', 'b', 1), step-1), black_rate * checkio1(marbles.replace('b', 'w', 1), step-1) ]) if __name__ == '__main__': assert checkio('bbw', 3) == 0.48, "1st example" assert checkio('wwb', 3) == 0.52, "2nd example" assert checkio('www', 3) == 0.56, "3rd example" assert checkio('bbbb', 1) == 0, "4th example" assert checkio('wwbb', 4) == 0.5, "5th example" assert checkio('bwbwbwb', 5) == 0.48, "6th example"
414a958b620f84055cb5702e8cddd6c79210e3ec
nsshayan/DataStructuresAndAlgorithms
/HackerRank/PythonPractice/lists.py
341
3.828125
4
if __name__ == '__main__': N = int(input()) elements = [] for _ in range(N): command = input().strip().split(' ') if command[0] == 'insert': elements.insert(int(command[1]), int(command[2])) elif command[0]=='print': print(elements) elif command[0]=='remove':
a4fe48cd352fc0c23b8ddbae5b454bc912cf9aac
markzcheng/SudokuSolver
/Solver.py
2,675
4.03125
4
board = [ [8, 0, 0, 9, 3, 0, 0, 0, 2], [0, 0, 9, 0, 0, 0, 0, 4, 0], [7, 0, 2, 1, 0, 0, 9, 6, 0], [2, 0, 0, 0, 0, 0, 0, 9, 0], [0, 6, 0, 0, 0, 0, 0, 7, 0], [0, 7, 0, 0, 0, 6, 0, 0, 5], [0, 2, 7, 0, 0, 8, 4, 0, 6], [0, 3, 0, 0, 0, 0, 5, 0, 0], [5, 0, 0, 0, 6, 2, 0, 0, 8], ] # function to print the sudoku board def print_board(board): row = len(board) col = len(board[0]) sep_length = 29 for i in range(row): if i % 3 == 0 and i != 0: print(sep_length * "-") for j in range(col): if j % 3 == 0 and j != 0: print('|', end=' ') print(board[i][j], end=' ') print() # Find and return the row, col values of the first zero found # Otherwise return None if there are no zeroes def find_zero(board): # hello row = len(board) col = len(board[0]) for i in range(row): for j in range(col): if board[i][j] == 0: return i, j return None # Checks if the row, col, and square for a number is valid # i refers to the row num and j refers to the col num def valid_number(i, j, board): return valid_row(i, j, board) and valid_col(i, j, board) and valid_square(i, j, board) def valid_row(i, j, board): val = board[i][j] for colNum in range(len(board[0])): if board[i][colNum] == val and (colNum != j): return False return True def valid_col(i, j, board): val = board[i][j] for rowNum in range(len(board)): if board[rowNum][j] == val and (rowNum != i): return False return True def valid_square(i, j, board): rowStart = (i // 3) * 3 colStart = (j // 3) * 3 val = board[i][j] for row in range(rowStart, rowStart + 3): for col in range(colStart, colStart + 3): if board[row][col] == val and (row != i or col != j): return False return True def solve(board): coordinates = find_zero(board) if not coordinates: return True else: (row, col) = coordinates for i in range(1, 10): board[row][col] = i if valid_number(row, col, board): solved = solve(board) if solved: return True board[row][col] = 0 return False def run_program(board): print() print("The starting board looks like:\n") print_board(board) print() solved = solve(board) if solved: print("Solving...\n") print("The ending board looks like:\n") print_board(board) else: print("Invalid board. No solution exists.") print() run_program(board)
632f4d7c927c014e9102723afd7c9c43ac9bd1ca
GabrielVicente-GT/UVG_CC2003_Proyecto-2_Fase2
/menu.py
8,488
3.84375
4
#Christopher Garcรญa 20541 #Isabel Solano 20504 #Gabriel Vicente 20498 #Jessica Ortiz 20192 #Algoritmos y estructura de datos CC2003 #Secciรณn 10 def Vacio(campo): while campo == None or campo == "" or campo.isspace(): campo = input('No se puede dejar un campo vacรญo: ') return campo def no_option(Verificacion): print ('La opciรณn que ingresรณ no existe') Verificacion = False print('______________________-----------------------------------______________________') print('______________________----------Sistema ChrIGaJ----------______________________') print('______________________-----------------------------------______________________') Verificador = False Palabra_clave = '' while Verificador != True: try: print ('Elija la accion que desea hacer con la base de datos creada') print (' Elegir juego ...') print ('1) Por Tipo / Genero') print ('2) Por Compania') print ('3) Por Tipo / Genero') print ('4) Online') print ('5) Offline') print ('6) Ser Multiplayer') print ('7) Ser Singleplayer') print (' Otras opciones ...') print ('8) Agregar relacion') print ('9) Quitar relacion') print ('10) Salir') print () Menu = int(input('Ingrese una opciรณn: ')) if Menu == 1: try: print ('Que genero desea?') print ('1) FPS') print ('2) ARPG') print ('3) MOBA') print ('4) Mundo abierto') print ('5) Carreras') print ('6) Party') print ('7) Estrategia') print ('8) Deportes') print ('9) Accion') print ('10) Aventura') print ('11) Peleas') genero = int(input('Ingrese una opciรณn: ')) if genero == 1: Palabra_clave = 'FPS' elif genero == 2: Palabra_clave = 'ARPG' elif genero == 3: Palabra_clave = 'MOBA' elif genero == 4: Palabra_clave = 'Mundo abierto' elif genero == 5: Palabra_clave = 'Carreras' elif genero == 6: Palabra_clave = 'Party' elif genero == 7: Palabra_clave = 'Estrategia' elif genero == 8: Palabra_clave = 'Deportes' elif genero == 9: Palabra_clave = 'Accion' elif genero == 10: Palabra_clave = 'Aventura' elif genero == 11: Palabra_clave = 'Peleas' else: print () print ('Genero no encontrado') print () no_option(Verificador) Palabra_clave = '' #aqui va el metodo if Palabra_clave != '': print(Palabra_clave) else: print('esto no esta en la base') except: print ('La opciรณn que ingresรณ no existe') print () Verificador = False elif Menu == 2: try: print ('Que compania desea?') print ('1) Riot Games') print ('2) Supercell') print ('3) Epic Games') print ('4) Nintendo') print ('5) miHoyo') print ('6) InnerSloth') print ('7) Activision') print ('8) Mediatonic') print ('9) Mojang Studios') print ('10) Rockstar Games') print ('11) Psyonix') print ('12) Electronics Arts') ceo = int(input('Ingrese una opciรณn: ')) if ceo == 1: Palabra_clave = 'Riot Games' elif ceo == 2: Palabra_clave = 'Supercell' elif ceo == 3: Palabra_clave = 'Epic Games' elif ceo == 4: Palabra_clave = 'Nintendo' elif ceo == 5: Palabra_clave = 'miHoyo' elif ceo == 6: Palabra_clave = 'InnerSloth' elif ceo == 7: Palabra_clave = 'Activision' elif ceo == 8: Palabra_clave = 'Mediatonic' elif ceo == 9: Palabra_clave = 'Mojang Studios' elif ceo == 10: Palabra_clave = 'Rockstar Games' elif ceo == 11: Palabra_clave = 'Psyonix' elif ceo == 12: Palabra_clave = 'Electronics Arts' else: print () print ('Compania no encontrado') print () no_option(Verificador) Palabra_clave = '' #aqui va el metodo if Palabra_clave != '': print(Palabra_clave) else: print('esto no esta en la base') except: print ('La opciรณn que ingresรณ no existe') print () Verificador = False elif Menu == 3: try: print ('En que dispositivo?') print ('1) Playstation 4-5') print ('2) Xbox One S-Series X') print ('3) Android/IOS') print ('4) PC') print ('5) Nintendo Switch') disp = int(input('Ingrese una opciรณn: ')) if disp == 1: Palabra_clave = 'Playstation 4-5' elif disp == 2: Palabra_clave = 'Xbox One S-Series X' elif disp == 3: Palabra_clave = 'Android/IOS' elif disp == 4: Palabra_clave = 'PC' elif disp == 5: Palabra_clave = 'Nintendo Switch' else: print () print ('Dispositivo no encontrado') print () no_option(Verificador) Palabra_clave = '' #aqui va el metodo if Palabra_clave != '': print(Palabra_clave) else: print('esto no esta en la base') except: print ('La opciรณn que ingresรณ no existe') print () Verificador = False Verificador = False elif Menu == 4: Palabra_clave = 'Online' #metodo aqui print(Palabra_clave) Verificador = False elif Menu == 5: Palabra_clave = 'Offline' #metodo aqui print(Palabra_clave) Verificador = False elif Menu == 6: Palabra_clave = 'Multiplayer' #metodo aqui print(Palabra_clave) Verificador = False elif Menu == 7: Palabra_clave = 'Singleplayer' #metodo aqui print(Palabra_clave) Verificador = False elif Menu == 8: print('esta es la opcion de crear relacion') Verificador = False elif Menu == 9: print('esta es la opcion de eliminar') Verificador = False elif Menu == 10: print ('Adios!') Verificador = True else: print () print ('La opciรณn que ingresรณ no existe') print () no_option(Verificador) except: print ('La opciรณn que ingresรณ no existe') print () Verificador = False
2a7337d0f428c519ab27cc63059036783eb91b9a
MiracleWong/aming_python
/python_basic/9.py
198
3.53125
4
#!/usr/bin/python #-*- coding:utf-8 -*- # for i in [i**2 for i in range(1,11)]: # print i, with open('tmp.txt') as fd: while True: line = fd.readline() if not line: break print line,
6c8e36b4c91de2af3bc017b49bd8751405f13e55
Mudasirrr/Courses-
/Rice-Python-Data-Visualization/week2- Creating Line Plots of GDP Data/examples_pygal.py
763
3.796875
4
""" Example of drawing line plots with Pygal. """ import pygal def draw_line(title, xvals, yvals): """ Draw line plot with given x and y values. """ lineplot = pygal.Line(height=400) lineplot.title = title lineplot.x_labels = xvals lineplot.add("Data", yvals) lineplot.render_in_browser() xvals = [0, 1, 3, 5, 6, 7, 9, 11, 12, 15] yvals = [4, 3, 1, 2, 2, 4, 5, 2, 1, 4] draw_line("My Line Plot", xvals, yvals) def draw_xy(title, xvals, yvals): """ Draw xy plot with given x and y values. """ coords = [(xval, yval) for xval, yval in zip(xvals, yvals)] xyplot = pygal.XY(height=400) xyplot.title = title xyplot.add("Data", coords) xyplot.render_in_browser() draw_xy("My XY Plot", xvals, yvals)
b8a4056a7791bdf7597999b1ad7c0d4b0ede2d53
omedalus/IntrospectivePlanner
/python/ipl/nnplanner/lookahead.py
1,213
3.84375
4
class Lookahead: def __init__(self, sensors, best_actuators, utility, recursion_depth): self.sensors = sensors self.best_actuators = best_actuators self.utility = utility self.recursion_depth = recursion_depth # NOTE: recursion_depth is actually how much depth this path was explored to! # Higher means it was explored deeper. def key(self): return Lookahead.sensors_key(self.sensors) @staticmethod def sensors_key(sensors): retval = str(['{:.02f}'.format(x) for x in sensors]) return retval class LookaheadCache: def __init__(self): self.cache = {} def __len__(self): return len(self.cache) def clear(self): self.cache = {} def get(self, sensors, recursion_depth): lhkey = Lookahead.sensors_key(sensors) lh = self.cache.get(lhkey) if lh is None or recursion_depth > lh.recursion_depth: # If we're going to explore this path to a depth deeper than what we already did, # then let's go ahead and do so. return None return lh def put(self, sensors, actuators, utility, recursion_depth): lh = Lookahead(sensors, actuators, utility, recursion_depth) lhkey = lh.key() self.cache[lhkey] = lh
f61a3fcc0a352b6c1d3da405d540d9814c510a59
RivkaSchuss/TileGameAI
/Astar.py
2,413
3.859375
4
from heapq import heappush, heappop class Astar(object): def __init__(self, state, logic): self.state = state self.logic = logic """ runs the a* search algorithm """ def run_search(self): open_list = [] closed_list = set() # initializing the first state initial_state = self.logic.get_initial_state() initial_state.depth = 0 initial_state.heuristic = self.calculate_trip_cost(initial_state) # adding the first state to the heap, with the condition being the f of the state heappush(open_list, (initial_state.get_f, initial_state)) while open_list: current_node = heappop(open_list)[1] # check if we've arrived at the goal state if self.logic.goal_state_check(current_node): path = "".join(self.logic.construct_path(current_node)) return path, str(len(closed_list) + 1), len(path) # if we've already checked this state, move on. if hash(str(current_node.board)) in closed_list: continue # get the successors of the current state children = self.logic.get_next_moves(current_node) # iterate over the successors and calculate their f's, enter them into the heap for child in children: child.depth = current_node.depth + 1 child.heuristic = self.calculate_trip_cost(child) heappush(open_list, (child.get_f, child)) # add the node that has been checked to the closed list closed_list.add(hash(str(current_node.board))) raise Exception("Puzzle can not be solved.") """ runs the manhattan distance heuristic function """ def calculate_trip_cost(self, state): cost = 0 board = state.board # iterating over the game board for r, row in enumerate(board): for c, num in enumerate(row): num = int(num) if num != 0: # calculating the correct index for the current tile correct_r, correct_c = int((num - 1) / self.logic.board_size), (num - 1) % self.logic.board_size # calculating the cost to place the correct tile in its place cost += abs(correct_r - r) + abs(correct_c - c) return cost
c8bfb7de654bf73e4df2ea332ee962c6d671334f
ASam-sparta/data14pythonasam
/Hangman/hangman_word.py
1,116
3.84375
4
from hangman_words import word_list from random import choice class Word: def __init__(self, difficulty): self.difficulty = difficulty self.easy = [10, 11] self.medium = [12, 13] self.hard = [14, 15] self.dict = {1: self.easy, 2: self.medium, 3: self.hard} self.word = self.generate_word() self.length = len(self.word) ## Getter for word def get_word(self): return self.word # Returns a list of indexes where all instances of a letter is found in the word def get_index_of_letter(self, letter_to_find): indexes = [] letter_to_find = letter_to_find.upper() for index_search in range(self.length): if letter_to_find == self.word[index_search]: indexes.append(index_search) return indexes # This keeps picking a word randomly, until one of the correct length is chosen def generate_word(self): picked_word = choice(word_list) while len(picked_word) not in self.dict[self.difficulty]: picked_word = choice(word_list) return picked_word
2834050573db40f828573a3a5e88137c4851382e
P-RASHMI/Python-programs
/Functional pgms/QuadraticRoots.py
979
4.3125
4
''' @Author: Rashmi @Date: 2021-09-17 19:10:01 @Last Modified by: Rashmi @Last Modified time: 2021-09-17 19:36:03 @Title : A program that takes a,d,c from quadratic equation and print the rootsโ€ ''' import math def deriveroots(a,b,c): """to calculate roots of quadratic equation parameter : a,b,c return value : roots""" #To find determinent detrimt = b * b - 4 * a * c sqrt_val = math.sqrt(abs(detrimt)) if detrimt > 0: print("real and different") root1 = (-b + sqrt_val)/(2*a) root2 = (-b - sqrt_val)/(2*a) print("roots are: ", root1 , root2 ) elif detrimt == 0: print("roots are real and same") print("root is", -b /(2*a)) else: print("roots are complex") a = int(input("enter the x* x coefficient")) b = int(input("enter the x coefficient")) c = int(input("enter the constant")) if (a == 0): print("give the corect quadratic equation") else: deriveroots(a,b,c)
47ef2d46be4fe56c7e41e428d85d8bd0de35bb10
TomasNiessner/Mi_primer_programa
/Tabla_multiplicaciรณn.py
272
4.0625
4
#Obtener la tabla de multiplicaciรณn de un nรบmero dado por el usuario. numero_tabla = int(input("Ingrese un nรบmero para obtener su tabla de multiplicaciรณn: ")) for numero in range(1,11): print("{} * {} = {}".format(numero_tabla, numero, numero_tabla * numero))
abc9cfec70a5c2aa02da16f91d12814de10d77d6
PaulSayantan/problem-solving
/HACKEREARTH/Algorithms/Sorting/Bubble Sort/easyGoing.py
434
3.5
4
from typing import List def arr_sort(n: int, arr: List[int]) -> List[int]: for i in range(n): for j in range(len(arr)-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr for _ in range(int(input())): n, m = (int(x) for x in input().split()) arr = [int(x) for x in input().split()] arr = arr_sort(n, arr) print(sum(arr[m: n]) - sum(arr[: n-m]))
8daaa1f9b7cd439d14845f8b3b829de56109c077
kingofthenorth871/info319Prosjekt
/src.py
614
3.609375
4
import json import codecs from collections import Counter #reads the file with open("tweets.json", encoding='utf-8') as file: data = json.load(file) #saves all the tweets in a list tweet = [] for x in data: tweet.append(x['tweets']) #creates a string to hold all the tweets for word count tweet_string = ''.join(tweet) #Counts word frequency for each tweet word_freq = [] tokens = tweet_string.split(" ") cnt = Counter(tokens) freq = cnt.most_common() word_freq.append(freq) #Writes to file file_out = codecs.open("word_frq.txt", "w", "utf-8") file_out.write(str(word_freq)) file_out.close()
dd7d025e39e63e0d8ba5389003483f46e8def2e8
moreirafelipe/univesp-alg-progamacao
/S7/exemplo1-prat.py
310
3.53125
4
from tkinter import Tk, Label, PhotoImage, TOP, BOTTOM root = Tk() photo = PhotoImage(file='computer.gif')#.subsample(5) image = Label(master=root, image=photo) text = Label(master=root, font=("Arial", 36), text='Este รฉ um TESTE!') image.pack(side=TOP, fill='x',) text.pack(side=BOTTOM) root.mainloop()
f598bb4f1697aa17a2e1312df69740bbcb2f4f5d
arch1904/Python_Programs
/largest_sum_subarray.py
1,331
4.25
4
# Largest Sum Subarray # # Write a function that given an array of integers will return the continuous subarrray with the largest # sum in the entire array # # # Example(s) # ---------- # Example 1: # Input: [-8,-6,1,-4,3,4,6] # Output: [3,4,6] # # Example 2: # Input: [2,-8,7,-3,4,-20] # Output: [7,-3,4] # # Example 3: # Input: [-1,-2,-3,-4] # Output: [-1] # # Parameters # ---------- # arr : List[int] # A variable length array of integers # # Returns # ------- # List[int] # Largest sum continous sub array # def largest_sum_subarray(arr): ''' returns the largest sum continous sub array ''' if len(arr) == 0: #If Arr is Empty Return None return None sum = max_sum = arr[0] #initialising sum and max sum to first element of the array i = 0 first = last = 0 for j in range(1, len(arr)): #Iterate through list starting at the second element if arr[j] > (sum + arr[j]): #if current element is greater than sum + current element sum = arr[j] i = j else: sum += arr[j] #keep adding consecutive elements if sum > max_sum: max_sum = sum #get maximum sum first = i #index where largest sum subarray starts last = j #index where largest sum subarray ends return arr[first:last+1]
ec0711a000fe152d80e234769047290bc7ac411d
Hellofafar/Leetcode
/Medium/623.py
2,944
4.21875
4
# ------------------------------ # 623. Add One Row to Tree # # Description: # Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. # The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree. # # Example 1: # Input: # A binary tree as following: # 4 # / \ # 2 6 # / \ / # 3 1 5 # # v = 1 # d = 2 # # Output: # 4 # / \ # 1 1 # / \ # 2 6 # / \ / # 3 1 5 # Example 2: # Input: # A binary tree as following: # 4 # / # 2 # / \ # 3 1 # # v = 1 # d = 3 # # Output: # 4 # / # 2 # / \ # 1 1 # / \ # 3 1 # # Note: # The given d is in range [1, maximum depth of the given tree + 1]. # The given binary tree has at least one tree node. # # Version: 1.0 # 12/22/18 by Jianfa # ------------------------------ class Solution: def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ if d == 1: newroot = TreeNode(v) newroot.left = root return newroot depth = 1 # Current depth of the tree nodes = [root] while nodes and depth < d - 1: # Loop to depth d - 1 temp = [] for i in range(len(nodes)): node = nodes[i] if node.left: temp.append(node.left) if node.right: temp.append(node.right) nodes = temp depth += 1 for node in nodes: # Insert left node newLeftNode = TreeNode(v) # The new left node to insert if node.left: newLeftNode.left = node.left node.left = newLeftNode # Insert right node newRightNode = TreeNode(v) # The new right node to insert if node.right: newRightNode.right = node.right node.right = newRightNode return root # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # Traverse until the depth d - 1 to get all nodes at the row. # Insert left and right node to each of the node at the row.
48fc359b78111a4496dd4eaafea0d747b04930c4
jpchato/pdx_code
/programming_102/unit_3/lecture.py
2,234
4.375
4
employee_availabilities = {} # dictionaries use curly brackets # print(type(employee_availabilities)) # add key:value pairs availabilities = { 'Keegan': 'Mon', 'Sarah':'Tues', } # keys are passed to dictionaries using square brackets # dictionary_name[key] # get the value at the key 'Keegan' keegan_availability = availabilities['Keegan'] print(keegan_availability) # Mon sarah_availability = availabilities['Sarah'] print(sarah_availability) # Tues # Dictionary keys can be strings or integers only # this is not a list # dictionary with integers # using integers as keys can be confusing when referencing values, because the syntax looks like a list numbers = { 0: 'zero', 1: 'one', 2: 'two' } print(numbers[0]) # dictionary values can be any data type, even other dictionaries availabilities = { # key:value, 'Keegan': ['Mon', 'Tues', 'Wed', 'Thu', 'Fri'], # list as a value 'Anthony': ['Mon', 'Wed', 'Fri'], 'Sarah': 'Thu' } # since keegan's availability is a list, each item can be referenced with its index keegan = availabilities['Keegan'] print(keegan[2]) sarah = availabilities['Sarah'] # add a new key:value pair availabilities['Al'] = 'Fri' print(availabilities) # code will break if a non-existent key is referenced # remove key:value pairs with keyword 'del' # del dictionary_name['key_to_delete'] del availabilities['Anthony'] print(availabilities) # Dictionary methods # dictionary_name.get(key, default_return_value) # .get() will return the value at the key if it exists # otherwise, return the default_value anthony = availabilities.get('Anthony', 'That key doesn\'t exist') print(anthony) keegan = availabilities.get('Keegan', 'That key doesn\'t exist') print(keegan) # .pop(key) - remove the key:value pair at the key and return the value removed_value = availabilities.pop('Keegan') print(removed_value) print(availabilities) new_employees = { 'John': 'Mon', 'George': 'Tue', 'Ringo': 'Fri' } availabilities.update(new_employees) print(availabilities) for name in availabilities: print(name) # line 81 and 86 have the same output # print(availabilities.keys()) for key in availabilities.keys(): print(key) print(availabilities.items())
8e2b03927b23db137ea8c06865e0dc62b633cbe8
yerimO/python_codeup__finish
/6082.py
143
3.6875
4
a=int(input()) for i in range(1,a+1,1): if (i%10)!=0 and (i%10)%3==0 : print("X",end=' ') else : print(i,end=' ')
c200b49bdcf1b0b32375b0fb622dacae634a62a8
Wilson0406/Python-exercises
/unicode_module.py
2,509
3.65625
4
# Defines the unicode characters and print (UTF - 8, UTF - 16, UTF - 32) # Go to start --> type character map to know the unicode symbols of every character # https://www.pythonsheets.com/notes/python-unicode.html # J --> U + 004A, Utf - 8 Dec : 74 # ร– --> Utf - 8 : 0xc3 0x96(Dec : 195 150), UTF -16 : 0x00D6 (Dec :214) # S --> U + 0053, Utf - 8 Dec : 83 # รฏ --> Utf - 8 : 0xc3 0xAF(Dec : 195 175), UTF -16 : 0x00EF (Dec :239) # G --> U + 0047, Utf - 8 Dec : 71 # A --> U + 0041, Utf - 8 Dec : 65 # ASCII - 7 bits , UTF-8 --> 8bits, UTF-16 --> 16 bits, UTF-32 --> 32 bits # ord() --> function to print the unicode for the given character # chr() --> function to print the character for the given unicode print(ord("J")) print(chr(74)) print(ord("ร–")) print(chr(214)) print(ord("S")) print(chr(83)) print(ord("รฏ")) print(chr(239)) print(ord("G")) print(chr(71)) print(ord("A")) print(chr(65)) print("Define the Unicode - 16 as strings and print \n") s = "Jร–SรฏGA" print(type(s)) print([ord(c) for c in s]) print([_c for _c in s]) b = s.encode('utf-16') print([_c for _c in b]) print(b) print([_c for _c in b]) c = b.decode('utf-16') print(c) print([_c for _c in c]) print("Define the Unicode - 8 as strings and print \n") s = "Jร–SรฏGA" # J --> U + 004A, Utf - 8 Dec : 74 # ร– --> Utf - 8 : 0xc3 0x96(Dec : 195 150), UTF -16 : 0x00D6 (Dec :214) # S --> U + 0053, Utf - 8 Dec : 83 # รฏ --> Utf - 8 : 0xc3 0xAF(Dec : 195 175), UTF -16 : 0x00EF (Dec :239) # G --> U + 0047, Utf - 8 Dec : 71 # A --> U + 0041, Utf - 8 Dec : 65 print(type(s)) print([_c for _c in s]) b = s.encode('utf-8') print([_c for _c in b]) print(b) print([_c for _c in b]) c = b.decode('utf-8') print(c) print([_c for _c in c]) # Printing the unicode characters by name (UTF-16) print(u"\N{DAGGER}") print(u"\N{SECTION SIGN}") print(u"\N{CENT SIGN}") print(u"\N{Latin Capital Letter J}") print(u"\N{Latin Capital Letter O with Diaeresis}") print(u"\N{Latin Capital Letter S}") print(u"\N{Latin Capital Letter I with Diaeresis}") print(u"\N{Latin Capital Letter G}") print(u"\N{Latin Capital Letter A}") # Printing the unicode characters by value (UTF-16) print(u"\u004A") print(u"\u00D6") print(u"\u0053") print(u"\u00EF") print(u"\u0047") print(u"\u0041") # Printing the unicode characters by value (UTF-32) print(u"\U0000004A") print(u"\U000000D6") print(u"\U00000053") print(u"\U000000EF") print(u"\U00000047") print(u"\U00000041")
58b4fa1b8fcb8fea45f20f7b1df4c19e53d78c6b
NishaUSK/pythontraining
/ex35.py
294
4.09375
4
#nested_if statement statement1 = 'true' nested_statement = '' if statement1: #outer if statement print("true") if nested_statement: #nested if statement print("yes") else: #nested else statement print("no") else: #outer else statement print("false")
acd3860637f06cb1160a802935cdd46957322604
franklin-antony/Mongo-WS
/Week-1/basic-python/for_loops.py
222
4
4
fruit = ["apple","orange","grape"] new_fruit = [] print(fruit) for item in fruit: print(item) new_fruit.append(item) print(new_fruit) sum = 0 numbers = [1, 2, 3, 5, 8] for i in numbers: sum = sum + i print sum
3d9273d3c6611141fd4776bee2b68b208c38189f
Shopzilla-Ops/python-coding-challenge
/pig-latin/gmendiola/translate.py
1,557
3.734375
4
#!/usr/bin/python2.7 import argparse class Translation(object): '''This object provides various translations for a given phrase''' def __init__(self, phrase, native='en'): self.phrase = phrase @property def pig_latin(self): VOWELS = tuple(list('aeiou')) for token in self.phrase.split(): print token if not token: continue elif not token.isalpha: yield token elif token.lower().startswith(VOWELS): yield ''.join([token, 'way']) elif not token.lower().startswith(VOWELS): vowel_pos_list = [token.lower().find(v) for v in VOWELS if token.find(v) != -1] if not vowel_pos_list: yield token else: first_vowel_pos = min(vowel_pos_list) yield ''.join([ token[first_vowel_pos:], token[:first_vowel_pos], 'ay' ]) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('language', help='language to translate into', choices=['platin']) parser.add_argument('phrase', help='phrase to translate') args = parser.parse_args() phrase = Translation(args.phrase) handlers = { 'platin': phrase.pig_latin, } print '\n', ' '.join(list(handlers.get(args.language)))
9fa1c09b9b00caaa8db0d663207412be7b0ff046
Kf4btg/SkyModMan
/skymodman/types/color.py
3,646
3.890625
4
from collections import namedtuple def _bound(value, lower, upper): if value < lower: return lower if value > upper: return upper return value class Color(namedtuple("Color", "R G B")): """" Just a very simple RGB color representation with ability to convert to/from hex-notation. Thanks to its generic nature, it can easily be extended to accomodate more components and all the methods should still work without having to override them to add the new component """ __slots__ = () # Restrict the values between 0 and 255 def __new__(cls, *args): return super().__new__(cls, *(_bound(a, 0, 255) for a in args)) @classmethod def from_hexstr(cls, hexstr): """ :param str hexstr: must be a string of 6 or 3 characters (7 or 4 if prepended with '#'), each a valid hex digit. The string 'ABC' is interpreted as shorthand for 'AABBCC'. Case is unimportant, and need not even be consistent: 'aaBBcc' == 'AabBCc' :return: a new Color initialized from the converted values of `hexstr` """ hexstr = hexstr.strip().lstrip("#") len_str = len(hexstr) num_fld = len(cls._fields) if len_str == num_fld: # ABC step, rpt = 1, 2 else: # AABBCC step, rpt = 2, 1 flds = tuple(int(hexstr[step*i:step*i+step]*rpt, 16) for i in range(num_fld)) return cls._make(flds) def to_hexstr(self, case='X'): """ Returns a hexadecimal-representation of the color, using uppercase letters by default. Pass 'x' for the `case` argument to use lowercase letters: >>> Color(255,255,0).to_hexstr() 'FFFF00' >>> Color(255,255,0).to_hexstr('x') 'ffff00' This is NOT the same as hex(Color(...)), though the only difference is that hex() prepends '0x' to the hex string (and is usually lowercase): >>> hex(Color(255,255,0) '0xffff00' .. note:: ``Color.__str__()`` is an alias for ``Color.to_hexstr('X')`` (the default uppercase representation). ``Color.__repr___()`` still returns the default namedtuple __repr__: >>> str(Color(255,255,0)) 'FFFF00' >>> repr(Color(255,255,0)) 'Color(R=255, G=255, B=0)' .. """ if case not in 'Xx': case='X' return "".join("{0.%s:02%s}" % (f, case) for f in self._fields).format(self) def __str__(self): return self.to_hexstr() def __hex__(self): return '0x'+str(self) def __int__(self): return int(str(self), 16) def __eq__(self, other): if not hasattr(other, "__int__"): return NotImplemented return int(self) == int(other) def __lt__(self, other): if not hasattr(other, "__int__"): return NotImplemented return int(self) < int(other) if __name__ == '__main__': c = Color(55,66,77) print(c.to_hexstr('x')) assert c.to_hexstr() == '37424D' c2 = Color.from_hexstr('37424d') c3 = Color.from_hexstr('#37424D') print(c2) print(c3) assert c2.R == c3.R == c.R == 55 assert c2.G == c3.G == c.G == 66 assert c2.B == c3.B == c.B == 77 print(str(c)) print(repr(c)) print (Color(2001, 256, -1)) assert Color(-1, -1, -1) == Color(0, 0, 0) assert Color(256, 256, 256) == Color(255, 255, 255) assert Color.from_hexstr("#ABC") == Color.from_hexstr("#AABBCC") print (repr(Color.from_hexstr('ABC'))) print (repr(Color.from_hexstr('012')))
75d63573aeee007eaeb8578b49a2e666fea4ebac
KeiraJCoder/week1
/Day4/loops.py
1,954
4.21875
4
favourite_drinks = ["Coke", "Pepsi", "Monster"] for x in favourite_drinks: print (x) for i in range (2, 12, 1): print (i) for i in reversed(range (2, 12, 1)): print (i) name = "" while len(name) == 0: #while the length of name is equal to zero name = input("Enter your name: ") #ask the user to enter their name print ("Hello " +name + " you filthy swine!") films = [ "Deadpool", "Donnie Darko", "Moana"] for films in films: print(films) def film_check(): if films[2] == "Ghostbusters": print ("Yay, its Ghostbusters!!!") else: print ("Booooo, we want ghostbusters") film_check() import time for seconds in range (9,0,-1): print (seconds) time.sleep(1) print ("KEIRA IS F***ING AMAZING!!!!!!!!") name = "" while len(name) == 0: #while the length of name is equal to zero name = input("Enter your name: ") #ask the user to enter their name print ("Hello " +name) num = 0 while num <10: #while number is less than 10, keep printing num+= 1 print (num) import random rand_num = random.randint(0,50) my_num = 50 while rand_num != my_num: print (rand_num) rand_num = random.randint(0,50) print ("You've found {}".format(my_num)) for x in range(13): print("Hello World ") print() for x in reversed(range(13)): print("x") print() x = 1 while x <= 13: print ("Hello World") x += 1 # Python program to shuffle a deck of card current_card = [ ] random.randint (1,len(current_card)) current_card = "" cards = ["Diamond", "Spade", "Club", "Hearts"] pick_card = random.choice(cards) print("Your card is", pick_card) while pick_card != current_card: current_card = random.choice(cards) print(current_card) num = 100 for i in range (100) : print ("*") while num < 9: num += 1 print (* num) if num <= 5: num -= 1 else: num -= 1 print(* num)
af4ab7a4384285ea1f27dc5fb3249e5c1c391058
Bhawana3/Data-Structures
/queue_using_python_list.py
1,171
4.3125
4
class Queue: """ initializing empty list named queue""" def __init__(self): self.queue = [] """ append new node into queue(list)""" def enqueue(self,new_node): self.queue.append(new_node) """ pop first element from the queue""" def dequeue(self): if self.queue != []: return self.queue.pop(0) else: return "Empty queue - underflow" """ return first element from the queue""" def peek(self): if self.queue != []: return self.queue[0] else: return "Empty queue" def printQueue(self): for node in self.queue: print node,'-->', print None if __name__ == "__main__": queue = Queue() print "Menu : " print "1 - appending new element in the queue" print "2 - dequeuing queue" print "3 - show first element in the queue" print "4 - print queue" n = raw_input("Enter any number 1/2/3/4 : ") while True: if n == '1': value = input("Enter value of new element : ") queue.enqueue(value) elif n == '2': print queue.dequeue() elif n == '3': print queue.peek() elif n == '4': queue.printQueue() else: print "Invalid option choosen.Exiting..." break n = raw_input("Enter any number 1/2/3/4 : ")
f21731869100cc6023eb5f704323d03afd272b8c
wolf-coder/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
847
4.09375
4
#!/usr/bin/python3 """ function that divides all elements of a matrix. """ def matrix_divided(matrix, div): """ function that divides all elements of a matrix. """ if not([len(row) for row in matrix].count(len(matrix[0])) == len(matrix)): raise TypeError('Each row of the matrix must have the same size') if type(div) not in [int, float]: raise TypeError('div must be a number') elif div == 0: raise ZeroDivisionError('division by zero') """ funtion to return error in case inappropriate matrix input """ def TypeError_exec(): exec( 'raise(TypeError(\'matrix must be a matrix (list of lists)' ' of integers/floats\'))') return [[round(x / div, 2) if type(x) in [int, float] else TypeError_exec() for x in row] for row in matrix]
e8d6fc925cc8ccb5a84aa8c94f077ef6ccb7c6b4
liyuanyuan11/Python
/While/While6.py
116
3.765625
4
animals=["Tiger","Lion","Panda","Bear","Welf"] for animals in animals: print("This zoo contains a "+animals+".")
32e4ba571b5e2d24278ad8e5867b290a9b03f06c
nosy0411/dynamic_plot_practice
/dynamic_using_animation.py
1,463
3.546875
4
# ๋™์  ๊ทธ๋ž˜ํ”„๋ฅผ ๊ทธ๋ฆฌ๋Š” ๋ฒ•์€ ํฌ๊ฒŒ 2๊ฐ€์ง€๊ฐ€ ์žˆ๋Š”๋ฐ # (1) plt.ion() ์„ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• # (2) import matplotlib.animation as animation ์ฆ‰ animation์„ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation x = [] y = [] figure, ax = plt.subplots(figsize=(4, 3)) line, = ax.plot(x, y) plt.axis([0, 4*np.pi, -1, 1]) def func_animate(i): x = np.linspace(0, 4*np.pi, 1000) y = np.sin(2 * (x - 0.1 * i)) line.set_data(x, y) return line, range(10) ani = FuncAnimation(figure, func_animate, frames=10, interval=50) # ani.save(r'animation.gif', fps=10) plt.show() # ani = FuncAnimation(figure, # func_animate, # frames=10, # interval=50) # figure๋Š” ํ”Œ๋กฏ์ด ์—…๋ฐ์ดํŠธ ๋  Figure ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค. # func_animate๋Š” ๊ฐ ํ”„๋ ˆ์ž„์—์„œ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ฒซ ๋ฒˆ์งธ ๋…ผ๊ฑฐ๋Š” ๋‹ค์Œ ๊ฐ’frames์—์„œ ๋‚˜์˜ต๋‹ˆ๋‹ค. # frames = 10์€range(10)๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. 0์—์„œ 9๊นŒ์ง€์˜ ๊ฐ’์€ ๊ฐ ํ”„๋ ˆ์ž„์—์„œfunc_animate๋กœ ์ „๋‹ฌ๋ฉ๋‹ˆ๋‹ค. # ๋˜ํ•œ๋ฆฌ์ŠคํŠธ [0, 1, 3, 7, 12]์™€ ๊ฐ™์ด ์ธํ„ฐ๋ฒŒ์„ โ€˜ํ”„๋ ˆ์ž„โ€™์— ํ• ๋‹น ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. # interval์€ ms๋‹จ์œ„์˜ ํ”„๋ ˆ์ž„ ๊ฐ„ ์ง€์—ฐ ์‹œ๊ฐ„์ž…๋‹ˆ๋‹ค. # fps ๋ฐdpi์™€ ๊ฐ™์€ ๋งค๊ฐœ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์• ๋‹ˆ๋ฉ”์ด์…˜์„gif ๋˜๋Š”mp4์— ์ €์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
fb09a484c60b319796fb26c824852bffbc0e6390
unitware/advent-of-code
/2018/9/assignment_9.py
8,083
3.75
4
''' --- Day 9: Marble Mania --- You talk to the Elves while you wait for your navigation system to initialize. To pass the time, they introduce you to their favorite marble game. The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number. First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble. Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble. However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble. For example, suppose there are 9 players. After the marble with value 0 is placed in the middle, each player (shown in square brackets) takes a turn. The result of each of those turns would produce circles of marbles like this, where clockwise is to the right and the resulting current marble is in parentheses: [-] (0) [1] 0 (1) [2] 0 (2) 1 [3] 0 2 1 (3) [4] 0 (4) 2 1 3 [5] 0 4 2 (5) 1 3 [6] 0 4 2 5 1 (6) 3 [7] 0 4 2 5 1 6 3 (7) [8] 0 (8) 4 2 5 1 6 3 7 [9] 0 8 4 (9) 2 5 1 6 3 7 [1] 0 8 4 9 2(10) 5 1 6 3 7 [2] 0 8 4 9 2 10 5(11) 1 6 3 7 [3] 0 8 4 9 2 10 5 11 1(12) 6 3 7 [4] 0 8 4 9 2 10 5 11 1 12 6(13) 3 7 [5] 0 8 4 9 2 10 5 11 1 12 6 13 3(14) 7 [6] 0 8 4 9 2 10 5 11 1 12 6 13 3 14 7(15) [7] 0(16) 8 4 9 2 10 5 11 1 12 6 13 3 14 7 15 [8] 0 16 8(17) 4 9 2 10 5 11 1 12 6 13 3 14 7 15 [9] 0 16 8 17 4(18) 9 2 10 5 11 1 12 6 13 3 14 7 15 [1] 0 16 8 17 4 18 9(19) 2 10 5 11 1 12 6 13 3 14 7 15 [2] 0 16 8 17 4 18 9 19 2(20)10 5 11 1 12 6 13 3 14 7 15 [3] 0 16 8 17 4 18 9 19 2 20 10(21) 5 11 1 12 6 13 3 14 7 15 [4] 0 16 8 17 4 18 9 19 2 20 10 21 5(22)11 1 12 6 13 3 14 7 15 [5] 0 16 8 17 4 18(19) 2 20 10 21 5 22 11 1 12 6 13 3 14 7 15 [6] 0 16 8 17 4 18 19 2(24)20 10 21 5 22 11 1 12 6 13 3 14 7 15 [7] 0 16 8 17 4 18 19 2 24 20(25)10 21 5 22 11 1 12 6 13 3 14 7 15 The goal is to be the player with the highest score after the last marble is used up. Assuming the example above ends after the marble numbered 25, the winning score is 23+9=32 (because player 5 kept marble 23 and removed marble 9, while no other player got any points in this very short example game). Here are a few more examples: 10 players; last marble is worth 1618 points: high score is 8317 13 players; last marble is worth 7999 points: high score is 146373 17 players; last marble is worth 1104 points: high score is 2764 21 players; last marble is worth 6111 points: high score is 54718 30 players; last marble is worth 5807 points: high score is 37305 What is the winning Elf's score? ''' import blist class MarbleMania(): ''' >>> MarbleMania(9).play_game_and_print(25) [0] (0) [1] 0 (1) [2] 0 (2) 1 [3] 0 2 1 (3) [4] 0 (4) 2 1 3 [5] 0 4 2 (5) 1 3 [6] 0 4 2 5 1 (6) 3 [7] 0 4 2 5 1 6 3 (7) [8] 0 (8) 4 2 5 1 6 3 7 [9] 0 8 4 (9) 2 5 1 6 3 7 [1] 0 8 4 9 2 (10) 5 1 6 3 7 [2] 0 8 4 9 2 10 5 (11) 1 6 3 7 [3] 0 8 4 9 2 10 5 11 1 (12) 6 3 7 [4] 0 8 4 9 2 10 5 11 1 12 6 (13) 3 7 [5] 0 8 4 9 2 10 5 11 1 12 6 13 3 (14) 7 [6] 0 8 4 9 2 10 5 11 1 12 6 13 3 14 7 (15) [7] 0 (16) 8 4 9 2 10 5 11 1 12 6 13 3 14 7 15 [8] 0 16 8 (17) 4 9 2 10 5 11 1 12 6 13 3 14 7 15 [9] 0 16 8 17 4 (18) 9 2 10 5 11 1 12 6 13 3 14 7 15 [1] 0 16 8 17 4 18 9 (19) 2 10 5 11 1 12 6 13 3 14 7 15 [2] 0 16 8 17 4 18 9 19 2 (20) 10 5 11 1 12 6 13 3 14 7 15 [3] 0 16 8 17 4 18 9 19 2 20 10 (21) 5 11 1 12 6 13 3 14 7 15 [4] 0 16 8 17 4 18 9 19 2 20 10 21 5 (22) 11 1 12 6 13 3 14 7 15 [5] 0 16 8 17 4 18 (19) 2 20 10 21 5 22 11 1 12 6 13 3 14 7 15 [6] 0 16 8 17 4 18 19 2 (24) 20 10 21 5 22 11 1 12 6 13 3 14 7 15 [7] 0 16 8 17 4 18 19 2 24 20 (25) 10 21 5 22 11 1 12 6 13 3 14 7 15 32 #10 players; last marble is worth 1618 points: high score is 8317 >>> MarbleMania(10).play_game(1618) 8317 #13 players; last marble is worth 7999 points: high score is 146373 >>> MarbleMania(13).play_game(7999) 146373 #17 players; last marble is worth 1104 points: high score is 2764 >>> MarbleMania(17).play_game(1104) 2764 #21 players; last marble is worth 6111 points: high score is 54718 >>> MarbleMania(21).play_game(6111) 54718 #30 players; last marble is worth 5807 points: high score is 37305 >>> MarbleMania(30).play_game(5807) 37305 #PART_A = '405 players; last marble is worth 71700 points' >>> MarbleMania(405).play_game(71700) 428690 #PART_B = '405 players; last marble is worth 7170000 points' >>> MarbleMania(405).play_game(7170000) 3628143500 ''' def __init__(self, num_players): self.num_players = num_players self.player = 0 self.current = 0 self.current_pos = 0 self.marbles = blist.blist([0]) self.players = [0 for _ in range(num_players)] def next_round(self): self.increment_player() self.current += 1 if not MarbleMania.is_multiple_of_23(self.current): self.add_marble() else: player_index = self.player - 1 remove_index = (self.current_pos - 7) % len(self.marbles) extra = self.marbles.pop(remove_index) self.players[player_index] += self.current + extra self.current_pos = remove_index % len(self.marbles) def add_marble(self): self.current_pos = self.current_pos + 2 while self.current_pos > len(self.marbles): self.current_pos -= len(self.marbles) self.marbles.insert(self.current_pos, self.current) def increment_player(self): if self.player < self.num_players: self.player += 1 else: self.player = 1 def print(self): s = f'[{self.player}] ' for m in self.marbles: if m == self.marbles[self.current_pos]: s += f'({m})' else: s += f' {m} ' print(s.strip()) return self def play_game(self, num_rounds): for i in range(num_rounds): self.next_round() return self.winner_score() def play_game_and_print(self, num_rounds): for i in range(num_rounds): self.print() self.next_round() self.print() return self.winner_score() def winner_score(self): return max(self.players) @staticmethod def is_multiple_of_23(num): ''' >>> MarbleMania.is_multiple_of_23(23) True >>> MarbleMania.is_multiple_of_23(46) True >>> MarbleMania.is_multiple_of_23(24) False >>> MarbleMania.is_multiple_of_23(21) False ''' return not (num%23)
f9200573cbde6232a8720efd1d47a2779efda178
taisei-s/nlp100
/swings/swing04.py
1,042
3.78125
4
# coding:utf-8 """ 04. ๅ…ƒ็ด ่จ˜ๅท "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."ใจใ„ใ†ๆ–‡ใ‚’ๅ˜่ชžใซๅˆ†่งฃใ—๏ผŒ1, 5, 6, 7, 8, 9, 15, 16, 19็•ช็›ฎใฎๅ˜่ชžใฏๅ…ˆ้ ญใฎ1ๆ–‡ๅญ—๏ผŒใใ‚Œไปฅๅค–ใฎๅ˜่ชžใฏๅ…ˆ้ ญใซ2ๆ–‡ๅญ—ใ‚’ๅ–ใ‚Šๅ‡บใ—๏ผŒๅ–ใ‚Šๅ‡บใ—ใŸๆ–‡ๅญ—ๅˆ—ใ‹ใ‚‰ๅ˜่ชžใฎไฝ็ฝฎ๏ผˆๅ…ˆ้ ญใ‹ใ‚‰ไฝ•็•ช็›ฎใฎๅ˜่ชžใ‹๏ผ‰ใธใฎ้€ฃๆƒณ้…ๅˆ—๏ผˆ่พžๆ›ธๅž‹ใ‚‚ใ—ใใฏใƒžใƒƒใƒ—ๅž‹๏ผ‰ใ‚’ไฝœๆˆใ›ใ‚ˆ๏ผŽ """ def swing04(str): word_list = [c.strip(',.') for c in str.split()] single = [0, 4, 5, 6, 7, 8, 14, 15, 18] element_dict ={} for i in range(len(word_list)): p = 1 if i in single else 2 element_dict[word_list[i][:p]] = i + 1 return element_dict if __name__ == "__main__": str = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." element_dict = swing04(str) for k, v in sorted(element_dict.items(), key=lambda x: x[1]): print(k, v)
2efbec51725707704632810f68a7727357d7a478
sakar123/Python-Assignments
/Question9.py
143
3.984375
4
given_string = input('Enter a string') first_char = given_string[0] last_char = given_string[-1] print(last_char+given_string[1:-1]+first_char)
42afb2335f845bdb5b6e36869200fbc02df71fc8
starxskiez/building-game
/console.py
2,476
4.0625
4
import os, time from grid import gc # Colors teal = '\033[96m' reset = '\033[0m' bold = '\033[1m' black = '\33[30m' red = '\33[31m' green = '\33[32m' orange = '\33[33m' blue = '\33[34m' violet = '\33[35m' cyan = '\33[36m' pink= '\033[95m' yellow = '\033[93m' blue = '\033[34m' white = '\33[37m' # Main Function for the Console def main(): os.system("clear") print(bold + cyan + "The Building Game: An M & L project...\n" + reset) howto() cmd() # How to Play Function def howto(): print(bold + cyan + "How To Play:\n") print(bold + cyan + "Press the arrow keys or wasd to move the black square or cursor on the screen. To change the color you want to draw with, press numbers 0-9 on your keyboard. You can look at the color list to see all the colors and their corresponding number. Finally, if you want to place a block or a brick, press space. Your brick should appear as the color you chose." + reset) print(bold + "\nColors:\n" + reset + "0. White (Eraser)\n" + pink + "1. Pink\n" + red + "2. Firebrick (Red)\n" + orange + "3. Orange\n" + yellow + "4. Gold (Yellow)\n" + green + "5. Forest Green (Green)\n" + blue + "6. Steel Blue (Blue)\n" + violet + "7. Dark Slate Blue (Purple)\n" + red + "8. Brown\n" + white + "9. Black\n" + reset) # Commands def cmd(): print("Commands (type cmdlist for a full list of commands and dont use yet its broken):") cmd = input("> ") if cmd == "cmdlist": cmdlist() elif cmd == "gc": gc() else: print # cmdlist command def cmdlist(): os.system("clear") print(bold + "Commands:" + reset) print("1. cmdlist - Returns full list of commands. Gets updated frequently.") print("2. gc - Allows you to change the color of the grid.") print() cmd = input("Commands:\n[1] back\n> ") if cmd == "back" or cmd == "1": main() def gc(): global gc while True: os.system("clear") color = input("What color would you like the grid to be (adding more options)?\n1. white\n2. black\n3. light blue\n4. back\n> ") if color == "white" or color == "1": gc = "white" break elif color == "black" or color == "2": gc = "black" break elif color == "light blue" or color == "3": gc = "lightblue" break elif color == "back": main() else: print(red + "Invalid Option. " + reset) yn = input(green + "Do you want to go back (y/n)? ") if yn == "y": main() break else: pass
225bf910c279af058d485ce213ebbb5bb0464cd2
fawazn/ABCs
/grabbag.py
1,941
3.5625
4
from random import sample from queue import deque #Traversal -- i'm not sure why dict instead of set for P def walk (G, s): P, Q = dict(), set() P[s] = None Q.add(s) while Q: u = Q.pop() for v in G[u].difference(P): Q.add(v) P[v] = u return P #Depth first search def dfs(G,s, S=None,target = None): if S is None: S = set() S.add(s) for u in G[s]: if u in S: continue dfs(G,u,S,s) return S #BFS traversal, pretty much same as before def bfs(G,s): P, Q = set(), deque(s) while Q: u = Q.popleft() for v in G[u]: if v in P: continue Q.append(v) P.add(v) return P #Quicksort using list comprehensions def qsort(list): if list == []: return [] else: pivot = list[0] lesser = qsort([x for x in list[1:] if x < pivot]) greater = qsort([x for x in list[1:] if x >= pivot]) return lesser + [pivot] + greater def iddfs(G, s): yielded = set() # Visited for the first time def recurse(G, s, d, S=None): # Depth-limited DFS if s not in yielded: yield s yielded.add(s) if d == 0: return # Max depth zero: Backtrack if S is None: S = set() S.add(s) for u in G[s]: if u in S: continue for v in recurse(G, u, d-1, S): # Recurse with depth-1 yield v n = len(G) for d in range(n): # Try all depths 0..V-1 if len(yielded) == n: break # All nodes seen? for u in recurse(G, s, d): yield u bratislav = {'a' : {'b','c','d' }, 'b' : {'a', 'c','x' }, 'c' : {'a', 'b'} ,'d' : {'a'}, 'x' : {'b', 'y'}, 'y' : {'x', 'z'}, 'z': {'x'} } vr = bfs (bratislav,'a') print(vr) unsrtd = sample(range(100),12) sorted = qsort(unsrtd) var = walk(bratislav,'a') var2 = dfs (bratislav,'z') print (var)
6d9b340f4969226dabce29a7160ba96d63ad2e62
crawfordl1/ArtIntel
/LocalizationIntro/4-FinalLocalizationFunction/4-2.py
5,654
3.859375
4
''' Created on Jan 28, 2015 @author: Wastedyu6 TOPIC: In a 2D World, Sense Multiple Colors via Sense() Function and Move() Accordingly ''' '''### GLOBALLY DEFINED VARIABLES ### world - Same length as List p. World specifies the color of the Grid-cell (i.e. Element) that the Robot "Senses" p_Move - Probability Move() function is executed correctly sensor_right - Probability Sense() measurement is correct ''' p_move = 0.8 sensor_right = 0.7 world = [['red', 'green', 'green', 'red', 'red'], ['red', 'red', 'green', 'red', 'red'], ['red', 'red', 'green', 'green', 'red'], ['red', 'red', 'red', 'red', 'red']] class MyClass(object): '''### CLASS VARIABLES ### Motions - How many times and which direction the Robot is defined to Move Measurements - Order of Which the Robot senses the Colors ''' motions = [[0,0],[0,1],[1,0],[1,0],[0,1]] measurements = ['green', 'green', 'green' ,'green', 'green'] '''### SHOW() FUNCTION ### -Purpose: Iterate through 2 Dimensional List in order to print Final Result -Input: -List (p) -Output: -List (p) ''' def show(p): for i in range(len(p)): print p[i] #Initialize Probability Table by Counting how many Grid-cells are in the World total = 0.0 for i in range(len(world)): total = total + len(world[i]) print("Total number of Grid-Cells in the Robot World:") print(total) print("") #Create initial Uniform Distribution - Calculates probabilities based on TOTAL Grid-cells existing in World matrix #In this Example, before the Robot has moved, each Grid-cell has a (1/20) be the the location the Robot it Thinks it is on p = [[total for row in range(len(world[0]))] for col in range(len(world))] '''### SENSE() FUNCTION ### -Purpose: Measurement Update of Robot "sensing" colors of grid-cells -*Note: Functions allow for the calculation of any arbitrary, non-specified Input -Input: -List (p) - Uniform Probability Distribution -Global Variable (Z) - Desired Robot Measurement -Output: -List (q) - NON-NORMALIZED Distribution (i.e. for all elements based on Senese Measurement: p * pHit or pMiss) ''' def sense(p, world, measurement): #Construct empty Posterior Distribution Matrix (Same size as p) q = [[0.0 for row in range(len(p[0]))] for col in range(len(p))] s = 0.0 #Iterate all Rows for rows in range(len(p)): #Iterate all Columns for columns in range(len(p[rows])): hit = (measurement == world[rows][columns]) #Does Measurement Match the Color the Robot is Sensing? #Calculate Non-Normalized Posterior Distributions q[rows][columns] = p[rows][columns] * (hit * sensor_right + (1-hit) * (1.0 - sensor_right)) s = s + q[rows][columns] #Sum of non-Normalized Distribution after the Robot has Sensed ''' If Hit is False (0) Then we can calculate the Probability of the Sensor's INACCURACY --> (0 * sensor_right + (1-0) * (1 - sensor_right)) --> (0 + (1 - 0.3)) If Hit is True (1) Then we can calculate the Probability of the Sensor's ACCURACY --> (1 * sensor_right + (1-1) * (1 - sensor_right)) --> (1 * 0.7 + 0) ''' #Normalize by dividing by Sum of Non-Normalized Posterior Distributions for rows in range(len(q)): for columns in range(len(p[rows])): q[rows][columns] = q[rows][columns] / s return q '''### MOVE() FUNCTION ### -Purpose: Measurement Update of Robot "moving" RIGHT between grid-cells -Input: -List (p) - Probability Distribution -Motion Number (U) - Number of Grid-cells the Robot is moving. Motion Direction examples below: -[0,0] - No Movement -[0,1] - Move Right -[0,-1] - Move Left -[1,0] - Move Down -[-1,0] - Move Up -Output: -List (q) - New Probability Distribution of Robot AFTER the Move has occurred i.e. What is the new Probability of finding desired colors based on where the Robot THINKS it is now? ''' def move(p, motion): #Construct empty Posterior Distribution Matrix (Same size as p) q = [[0.0 for row in range(len(p[0]))] for col in range(len(p))] for rows in range(len(p)): for columns in range(len(p[rows])): #Determine Cells that the Robot previously moved from q[rows][columns] = (p_move * p[(rows - motion[0]) % len(p)][(columns - motion[1]) % len(p[rows])]) + ((1.0-p_move) * p[rows][columns]) ''' Explanation for Addition of line: ((1.0-p_move) * p[rows][columns]) -->Provides the Probability of if the Robot did not move. Thus Multiply current position by Probability of Staying in Position ''' return q #Determine new Probability Distributions (Where the Robot Thinks it is) based on measurements from Move & Sense functions for k in range(len(measurements)): p = move(p, motions[k]) p = sense(p, world, measurements[k]) #Print Final Probability Calculation of where the Robot Thinks it is! show(p)
acf5e26a8a833938992cff5aaf5d3590b8f5a4b5
liangliang1120/NLP2
/improve_agent.py
9,763
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 22:45:49 2019 (Optional) Improve your agent to make it able to find a path based on different strategies a. Find the shortest path between two stations. b. Find the path that requires minimum transfers between two stations. c. Combine the previous two ideas, find a more suitable path. @author: us """ import sh_subway_con import math import subway_location def geo_distance(origin, destination): """ Calculate the Haversine distance. ้€š่ฟ‡็ป็บฌๅบฆ่ฎก็ฎ—ๅŸŽๅธ‚้—ด่ท็ฆป๏ผˆๆ‹ท่ด๏ผ‰ Parameters ---------- origin : tuple of float (lat, long) destination : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> origin = (48.1372, 11.5756) # Munich >>> destination = (52.5186, 13.4083) # Berlin >>> round(distance(origin, destination), 1) 504.2 """ lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2 - lat1) # ๅฐ†่ง’ๅบฆ่ฝฌๆขไธบๅผงๅบฆ dlon = math.radians(lon2 - lon1) a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) #่ฟ”ๅ›ž็ป™ๅฎš็š„ X ๅŠ Y ๅๆ ‡ๅ€ผ็š„ๅๆญฃๅˆ‡ๅ€ผ d = radius * c return d def sort_by_distance(pathes): def get_distance_of_path(path): distance = 0 for i,_ in enumerate(path[:-1]): distance += get_stat_distance(path[i],path[i+1]) #print(path, distance) return distance #print(sorted(pathes,key=get_distance_of_path)) return sorted(pathes,key=get_distance_of_path) def get_distance_of_path(path): distance = 0 for i,_ in enumerate(path[:-1]): distance += get_stat_distance(path[i],path[i+1]) return distance def bfs_lenth(graph,start,destination,search_strategy): # Find the shortest path between two stations. pathes = [[start]] #็ปดๆŠค็š„list while pathes: path = pathes.pop(0)#ๆŠŠ็ฌฌไธ€ไธช่ทฏๅพ„ๆ‹ฟๅ‡บๆฅ froniter = path[-1]#็œ‹่ฟ™ๆก่ทฏๅพ„ไธญๆœ€ๅŽ็š„็‚นๆ˜ฏๅฆ่ฟžๆŽฅๅ…ถไป–็š„็‚น successsors = graph[froniter]#ๆŠŠ่ฟžๆŽฅ็š„็‚นๆ”พๅ…ฅsuccessors for city in successsors: if city in path: continue # check loop new_path = path+[city] pathes.append(new_path) #bfs pathes = search_strategy(pathes) if pathes and (destination == pathes[0][-1]): return pathes[0] def sort_by_transfers(pathes,dict_line): def get_transfers_of_path(path,dict_line): # ่ฎก็ฎ—่ทฏ็บฟๆขไน˜ๆฌกๆ•ฐ stat_dict = {} for stat in path: stat_dict[stat] = [] for stat in path: #print(stat) for line in dict_line.keys(): for statt in dict_line[line]: if stat in statt: stat_dict[stat].append(line) transfer_line = [] for stat in stat_dict: try: a except: a = [] for line in stat_dict[stat]: #print(line) if line in a: b = line #print('ไธๆขไน˜',line) transfer_line.append(b) #print('transfer_line ',transfer_line) a = stat_dict[stat] #print('a',a,stat) transfer_num = len(set(transfer_line)) #print('transfer_num',transfer_num) return transfer_num path_transfer_num = {} for path in pathes: path_transfer_num[str(path)] = get_transfers_of_path(path,dict_line) #print(path_transfer_num) sorted_way_dict = sorted(path_transfer_num.items(), key=lambda item: item[1], reverse=False) sorted_way = [] for key in sorted_way_dict: sorted_way.append(eval(key[0])) #print('sorted_way',sorted_way) return sorted_way def bfs_transfer(graph,start,destination,dict_line,search_strategy): # Find the minium transfers between two stations. pathes = [[start]] #็ปดๆŠค็š„list while pathes: path = pathes.pop(0)#ๆŠŠ็ฌฌไธ€ไธช่ทฏๅพ„ๆ‹ฟๅ‡บๆฅ froniter = path[-1]#็œ‹่ฟ™ๆก่ทฏๅพ„ไธญๆœ€ๅŽ็š„็‚นๆ˜ฏๅฆ่ฟžๆŽฅๅ…ถไป–็š„็‚น successsors = graph[froniter]#ๆŠŠ่ฟžๆŽฅ็š„็‚นๆ”พๅ…ฅsuccessors for city in successsors: if city in path: continue # check loop #print(city) new_path = path+[city] #print(new_path) pathes.append(new_path) #bfs #print(pathes) pathes = search_strategy(pathes,dict_line) #print('kkk',pathes) if pathes and (destination == pathes[0][-1]): return pathes[0] if __name__=='__main__': url = "http://sh.bendibao.com/ditie/" dict_line = sh_subway_con.get_line_station(url) station_con = sh_subway_con.build_connection(dict_line) locat_dict = subway_location.locat_dict def get_stat_distance(stat1,stat2): return geo_distance(locat_dict[stat1],locat_dict[stat2]) #ไปฅไธ‹10ๅท็บฟๅ’Œ11ๅท็บฟ๏ผŒ้‡ๅˆ็ซ™็‚นๆ”ฏ็บฟๅŽป้‡,ไปฅๅ…ๆขไน˜ๆฌกๆ•ฐๅขžๅŠ  line10_stat = ['ๆ–ฐๆฑŸๆนพๅŸŽ','ๆฎท้ซ˜ไธœ่ทฏ','ไธ‰้—จ่ทฏ','ๆฑŸๆนพไฝ“่‚ฒๅœบ','ไบ”่ง’ๅœบ','ๅ›ฝๆƒ่ทฏ', 'ๅŒๆตŽๅคงๅญฆ','ๅ››ๅนณ่ทฏ','้‚ฎ็”ตๆ–ฐๆ‘','ๆตทไผฆ่ทฏ','ๅ››ๅทๅŒ—่ทฏ','ๅคฉๆฝผ่ทฏ','ๅ—ไบฌไธœ่ทฏ', '่ฑซๅ›ญ','่€่ฅฟ้—จ','ๆ–ฐๅคฉๅœฐ','้™•่ฅฟๅ—่ทฏ','ไธŠๆตทๅ›พไนฆ้ฆ†','ไบค้€šๅคงๅญฆ', '่™นๆกฅ่ทฏ','ๅฎ‹ๅ›ญ่ทฏ','ไผŠ็Ё่ทฏ','ๆฐดๅŸŽ่ทฏ','้พ™ๆบช่ทฏ'] line11_stat = ['็ฝ—ๅฑฑ่ทฏ','ๅพกๆกฅ','ๆตฆไธ‰่ทฏ','ไธ‰ๆž—ไธœ','ไธ‰ๆž—','ไธœๆ–นไฝ“่‚ฒไธญๅฟƒ','้พ™่€€่ทฏ', 'ไบ‘้”ฆ่ทฏ','้พ™ๅŽ','ไธŠๆตทๆธธๆณณ้ฆ†','ๅพๅฎถๆฑ‡','ไบค้€šๅคงๅญฆ','ๆฑŸ่‹่ทฏ','้š†ๅพท่ทฏ', 'ๆ›นๆจ่ทฏ','ๆžซๆกฅ่ทฏ','็œŸๅฆ‚','ไธŠๆตท่ฅฟ็ซ™','ๆŽๅญๅ›ญ','็ฅ่ฟžๅฑฑ่ทฏ','ๆญฆๅจ่ทฏ', 'ๆกƒๆตฆๆ–ฐๆ‘','ๅ—็ฟ”','้ฉฌ้™†','ๅ˜‰ๅฎšๆ–ฐๅŸŽ'] temp = dict_line['ไธŠๆตทๅœฐ้“10ๅท็บฟๆ”ฏ็บฟ'].copy() for stat in dict_line['ไธŠๆตทๅœฐ้“10ๅท็บฟๆ”ฏ็บฟ']: if stat[0] in line10_stat: temp.remove(stat) dict_line['ไธŠๆตทๅœฐ้“10ๅท็บฟๆ”ฏ็บฟ'] = temp temp = dict_line['ไธŠๆตทๅœฐ้“11ๅท็บฟๆ”ฏ็บฟ'].copy() for stat in dict_line['ไธŠๆตทๅœฐ้“11ๅท็บฟๆ”ฏ็บฟ']: if stat[0] in line11_stat: temp.remove(stat) dict_line['ไธŠๆตทๅœฐ้“11ๅท็บฟๆ”ฏ็บฟ'] = temp #็”ฑไบŽ3ๅท็บฟ4ๅท็บฟๆœ‰้‡ๅˆ๏ผŒๆŠŠ็ฝ‘็ปœๅŽป้‡ for stat in station_con.keys(): station_con[stat] = list(set(station_con[stat])) #c=get_stat_distance('ไธดๅนณ่ทฏ','ๆก‚ๆž—่ทฏ') #c = get_distance_of_path(['ไธดๅนณ่ทฏ', 'ๆตทไผฆ่ทฏ', 'ๅฎๅฑฑ่ทฏ', 'ไธŠๆตท็ซ่ฝฆ็ซ™', 'ๆฑ‰ไธญ่ทฏ', 'ๅ—ไบฌ่ฅฟ่ทฏ', '้™ๅฎ‰ๅฏบ', 'ๆฑŸ่‹่ทฏ', 'ๅพๅฎถๆฑ‡', 'ๅฎœๅฑฑ่ทฏ', 'ๆก‚ๆž—่ทฏ']) #===========================ๆŒ‰็…งๆœ€็Ÿญ่ท็ฆป้€‰ๆ‹ฉ่ทฏ็บฟ=============================== c = bfs_lenth(station_con,"ไธญๅฑฑๅŒ—่ทฏ","ๅ››ๅทๅŒ—่ทฏ",search_strategy=sort_by_distance) print("ไธดๅนณ่ทฏ=>ๆก‚ๆž—่ทฏ dfs่ท็ฆปๆœ€็Ÿญ่ทฏ็บฟ:",str(c)) # ็”จbfs่ฎก็ฎ—ๆœ€็Ÿญ่ทฏ็จ‹็š„็บฟ่ทฏ๏ผŒ็”ฑไบŽ่Š‚็‚น่พƒๅคš๏ผˆ344ไธช๏ผ‰๏ผŒๅฑ‚ๆฌก่พƒๆทฑ๏ผŒๆ‰€ไปฅ่ฟ่กŒ่ตทๆฅ็‰นๅˆซๆ…ข๏ผŒ # ๅๅ‡ ็ซ™็š„่ทฏ็บฟ็ซ™่ท‘ไบ†24ๅฐๆ—ถ่ฟ˜ๆฒกๅ‡บ็ป“ๆžœ๏ผŒๆต‹่ฏ•็”จ่พƒ็Ÿญ่ทฏ็บฟ่ฟ›่กŒ # ็ป“ๆžœ: ไธดๅนณ่ทฏ=>ๆก‚ๆž—่ทฏ dfs่ท็ฆปๆœ€็Ÿญ่ทฏ็บฟ: ['ไธญๅฑฑๅŒ—่ทฏ', 'ไธŠๆตท็ซ่ฝฆ็ซ™', 'ๆฑ‰ไธญ่ทฏ', 'ๆ›ฒ้˜œ่ทฏ', 'ๅคฉๆฝผ่ทฏ', 'ๅ››ๅทๅŒ—่ทฏ'] #===========================ๆŒ‰็…งๆœ€ๅฐ‘ๆขไน˜้€‰ๆ‹ฉ่ทฏ็บฟ=============================== #c = get_transfers_of_path(['ไธญๅฑฑๅŒ—่ทฏ','ไธŠๆตท็ซ่ฝฆ็ซ™','ๆฑ‰ไธญ่ทฏ','ๆ›ฒ้˜œ่ทฏ','ๅคฉๆฝผ่ทฏ','ๅ››ๅทๅŒ—่ทฏ'],dict_line) c = bfs_transfer(station_con,"ไธญๅฑฑๅŒ—่ทฏ","ๅ››ๅทๅŒ—่ทฏ",dict_line,search_strategy=sort_by_transfers) print("ไธญๅฑฑๅŒ—่ทฏ=>ๅ››ๅทๅŒ—่ทฏ dfsๆœ€ๅฐ‘ๆขไน˜่ทฏ็บฟ:",str(c)) ''' # ๅคงๆฆ‚้œ€่ฆ2-3ๅˆ†้’Ÿ ไธญๅฑฑๅŒ—่ทฏ=>ๅ››ๅทๅŒ—่ทฏ dfsๆœ€ๅฐ‘ๆขไน˜่ทฏ็บฟ: ['ไธญๅฑฑๅŒ—่ทฏ', 'ไธŠๆตท็ซ่ฝฆ็ซ™', 'ๆฑ‰ไธญ่ทฏ', 'ๆ–ฐ้—ธ่ทฏ', 'ไบบๆฐ‘ๅนฟๅœบ', '้ป„้™‚ๅ—่ทฏ', '้™•่ฅฟๅ—่ทฏ', 'ๆ–ฐๅคฉๅœฐ', '่€่ฅฟ้—จ', '่ฑซๅ›ญ', 'ๅ—ไบฌไธœ่ทฏ', 'ๅคฉๆฝผ่ทฏ', 'ๅ››ๅทๅŒ—่ทฏ'] ''' #Combine the previous two ideas, find a more suitable path. #็›ธๆฏ”่พƒ่€Œ่จ€๏ผŒๆˆ‘ๆ›ดๅ€พๅ‘ไบŽ้€‰ๆ‹ฉ ่ท็ฆปๆ›ด็Ÿญ็š„็บฟ่ทฏ๏ผŒ #ๆต‹่ฏ•ไธญๅฆ‚ๆžœ้€‰ๆ‹ฉๆขไน˜ๆ•ฐ่พƒๅฐ‘็š„่ทฏ็บฟ๏ผŒๅพˆๅฏ่ƒฝ่ตฐๅพˆ้•ฟ่ท็ฆป๏ผŒ่€—ๆ—ถๆ›ด้•ฟ #ๆต‹่ฏ•ๆ—ถ๏ผšๆขไน˜3ๆฌกๅช่ฆๅ5็ซ™๏ผŒๅฆ‚ๆžœๆขไน˜2ๆฌก้œ€่ฆๅ11็ซ™๏ผŒๆขไน˜ๆฌกๆ•ฐๆœ€ๅฐ‘ๅฏ่ƒฝๅฐฑไธๆ˜ฏๆœ€ไผ˜้€‰ๆ‹ฉ #ๅฏไปฅๆƒณๅˆฐ็š„ๅ…ถไป–่ทฏๅพ„้€‰ๆ‹ฉๆ–นๅผ๏ผš1ๆŒ‰็…งไผฐ็ฎ—ๆ—ถ้—ดๅฏปๆ‰พๆ—ถ้—ดๆœ€็Ÿญ่ทฏ็บฟ๏ผŒ2็›ดๆŽฅๆŒ‰็…ง็ป่ฟ‡็š„็ซ™็‚นๆœ€ๅฐ‘้€‰ๆ‹ฉ่ทฏ็บฟ ''' Compare your results with results obtained by using some apps such as Baidu map, A map, Google map or Apple map. If there is difference, try to explanate it. ่ท็ฆป็š„ไผฐ่ฎกๅ’Œ็™พๅบฆๅœฐๅ›พไธŠ่ฟ˜ๆ˜ฏๆœ‰ไบ›่ฎธๅŒบๅˆซ๏ผŒ ไพ‹ๅฆ‚ ไธดๅนณ่ทฏ=>ๆก‚ๆž—่ทฏ๏ผŒpython่„šๆœฌไธญ็”จๅ…ฌๅผ็ฎ—10.444km,appไธญ13.7km ๅทฎ่ท็š„ๅœฐๆ–น๏ผš 1.็ป็บฌๅบฆไธๅ‡†็กฎ๏ผ› 2.appไธญ่ฎก็ฎ—็š„ๆ˜ฏๅฏ่กŒ้“่ทฏ็š„้•ฟๅบฆ๏ผŒไธๆ˜ฏๅ…ฌๅผไธญ็š„็›ด็บฟ่ท็ฆป 3.appไธญ่€ƒ่™‘ๆ›ดๅคš็š„ๅ› ็ด ๏ผŒๅฏไปฅ้€‰ๆ‹ฉ๏ผˆๆ—ถ้—ด็Ÿญใ€ๅฐ‘ๆขไน˜ใ€ๅฐ‘ๆญฅ่กŒ๏ผ‰็ญ‰ 4.appไธญ่ฟ˜ไผš่€ƒ่™‘ๆ—ถ้—ดๅ› ็ด  ๅฆๅค–appไธญไผšๅฎžๆ—ถๆŒ‰็…ง่ทฏๅ†ตๆ›ดๆ–ฐ๏ผŒไพ‹ๅฆ‚ๆœ‰ๆŒ‰้“่ทฏๆ‹ฅๅ ต็จ‹ๅบฆใ€ๆ™š้—ดๅœ่ฟ็ญ‰ไฟกๆฏๆ›ดๆ–ฐ '''
19d6d05867f9540c140c59bdf4423ef2cc486e5e
marcusaj0114/web-dev
/examples/ex4.py
1,313
4.3125
4
# Sets the number of cars to 100 cars = 100 # Sets the space in the car to 4.0 space_in_car = 4.0 # Sets the number of drivers to 30 drivers = 30 # Sets the number of passengers to 90 passengers = 90 # Calculates the number of cars that are not driven by subtracting the number of drivers from the total number of cars cars_not_driven = cars - drivers # Sets the number of cars driven to the number of cars cars_driven = drivers # Calculates the carpool capacity by multiplying the space in each car by the number of cars carpool_capacity = cars_driven * space_in_car # Calculates the average number of passengers per car by dividing the number of passengers by the cars that are driven average_passengers_per_car = passengers / cars_driven # Outputs the number of cars print("There are", cars, "cars available.") # Outputs the number of files print("There are only", drivers, "drivers available.") # Outputs the number of cars that won't be driven print("There will be", cars_not_driven, "empty cars today.") # Outputs the carpool capacity print("We can transport", carpool_capacity, "people today.") # Outputs the number of passengers print("We have", passengers, "to carpool today.") # Outputs the average number of passengers per car print("We need to put about", average_passengers_per_car, "in each car.")
43e653bb992f3142f07ee002dc3e3f6d5511bb58
aplascencia-ns/ssh_forwarding
/merge_two_files.py
3,167
3.875
4
# Python Program - Merge Two Files import shutil # https://docs.python.org/3/library/shutil.html import os # https://docs.python.org/3/library/os.html?highlight=os#module-os # Input account name account = input("Enter account name: ") # Exec bash for getting info from AWS and generate the files cmd = 'sh ssh_config.sh ' + account os.system(cmd) # Init variables file_current_name = "config_current" file_account_name = "config_" + account file_config_output = "config" # Creating lists list_file_current = [] list_file_account = [] block = [] ########################################### # Open config's current file and init loop ########################################### file_current = open(file_current_name, "r") # It reads the individual lines file_current_rl = file_current.readlines() # Iterate over a list for line in file_current_rl: line_text = line # print(len(line_text)) # print(line_text) # End of block if (len(line_text.strip()) == 0): # add last line before to restart list_file_current.append(block) # restart block block = [] continue else: # create a list of lists block.append(line_text) # print(block) # print("############### list_file_current ###############") # print(list_file_current) # restart block block = [] ########################################### # Open config's account file and init loop ########################################### file_account = open(file_account_name, "r") # It reads the individual lines file_account_rl = file_account.readlines() # Iterate over a list for line in file_account_rl: line_text = line #.strip() # End of block if (len(line_text.strip()) == 0): # add last line before to restart list_file_account.append(block) # restart block block = [] continue else: # create a list of lists # line_text += "\n" block.append(line_text) # print("############### list_file_account ###############") # print(list_file_account) # getting length of list current lenght = len(list_file_current) equal = False # Loop over list inside another list for item_account in list_file_account: # print(item) for item_current in range(lenght): # Validate if the items have the same info in order to skip it if (item_account == list_file_current[item_current]): # Change flag equal = True # print("EQUAL") # print(list_file_current[item_current]) # Adding new items to the current file config if (not equal): list_file_current.append(item_account) # Change flag equal = False # print("##############################") # print(list_file_current) # Concatenate item in list to strings joined = [''.join(row) for row in list_file_current] # Final result output = '\n'.join(joined) + "\n" # print(output) # Generating config file file_config = open(file_config_output, "w+") file_config.write(output) file_config.close() print("\nContent merged successfully.!") # Overwrite config file os.system('cat ./config > ~/.ssh/config')
ff66619c13712959bcfc1739e0002afbd3263dc9
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/chnjul005/question3.py
449
3.734375
4
m = input("Enter the message:\n") mr = eval(input("Enter the message repeat count:\n")) ft = eval(input("Enter the frame thickness:\n")) linet = 0 dashn = len(m) +(ft*2) for i in range(ft): print("|"*linet,"+","-"*dashn,"+","|"*linet,sep="") linet+=1 dashn-=2 for i in range(mr): print("|"*ft,m,"|"*ft) linet-=1 dashn+=2 for i in range(ft): print("|"*linet,"+","-"*dashn,"+","|"*linet,sep="") linet-=1 dashn+=2
6b92f27a747adc87191b1a11ad6189436cac4627
umberahmed/python-practice
/meal_cost.py
760
4
4
def solve(meal_cost, tip_percent, tax_percent): # function defined as solve and takes 3 parameters, meal cost, tip percent and tax percent """Calculates a meal cost, including tip and tax""" # tip = float(tip_percent) / 100 # tip variable created to calculate tip percent total_tip = meal_cost * tip # total tip variable created to calculate meal with tip tax = float(tax_percent) / 100 # tax variable created to calculate tax percentage total_tax = meal_cost * tax # total tax variable created to calculate meal with tax total_meal_cost = meal_cost + total_tip + total_tax # final cost of meal, including tip and tax return "The total meal cost is {} dollars.".format(int(total_meal_cost)) print solve(15.50, 15, 10)
e218be99053c9ce81235173fa89c87bcc89ce7fc
Paecklar/Web_Dev
/Lesson_12/hello.py
191
3.65625
4
from functions import print_hello #print_hello("Hallo", 5) print(print_hello(name="tom")) from functions import numbers_sum for numb in range(1, 5): print(numbers_sum(numb, numb+1))
417dc8e317304023ce8d615234b6b3d0449b0a18
CongoCash/Rocket
/Updated/intro-algorithms/solutions/solution-mergesort.py
602
4.15625
4
def merge_sort(toSort): if len(toSort) <= 1: return toSort mIndex = len(toSort) / 2 left = merge_sort(toSort[:mIndex]) right = merge_sort(toSort[mIndex:]) result = [] while len(left) > 0 and len(right) > 0: if left[0] > right[0]: result.append(right.pop(0)) else: result.append(left.pop(0)) if len(left) > 0: result.extend(merge_sort(left)) else: result.extend(merge_sort(right)) return result items = [3,89,14,1,6,334,9,0,44,101] print 'Before: ', items merge_sort(items) print 'After: ', items
ceeadf564da0d6fc5e2c64af83647581f8da3b0c
10JQ/spider
/LiaoXueFeng.py
5,010
3.96875
4
#################################################### # ๅ‡ฝๆ•ฐ #################################################### # ้ป˜่ฎคๅ‚ๆ•ฐ็š„ๅ€ผๆ˜ฏๅœจๅ‡ฝๆ•ฐๅฎšไน‰็š„ๆ—ถๅ€™่ฎก็ฎ—ๅ‡บๆฅ็š„ # ๆ‰€ไปฅ๏ผŒ้ป˜่ฎคๅ‚ๆ•ฐๅฟ…้กปๆŒ‡ๅ‘ไธๅ˜ๅฏน่ฑก def add_end(L=None): if L is None: L = [] L.append('END') return L # ๅฏๅ˜ๅ‚ๆ•ฐ # ๅœจๅฝขๅ‚ๅ‰ๅŠ *๏ผŒไผ ้€’็ป™ๅ‡ฝๆ•ฐ็š„ๅคšไธชๅฎžๅ‚ไผš่ขซ็ป„ๅˆไธบไธ€ไธชTuple def func(*arguments): pass # ๅฆ‚ๆžœไผ ้€’็ป™ๅ‡ฝๆ•ฐไธ€ไธชListๆˆ–่€…Tuple๏ผŒๅฏไปฅๅœจๅ‰้ขๅŠ *ๅท num = [1, 2, 3] func(*num) # ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) # ๅฏไปฅๅชไผ ๅ…ฅๅฟ…้€‰ๅ‚ๆ•ฐ๏ผš >>> person('Michael', 30) name: Michael age: 30 other: {} # ไนŸๅฏไปฅไผ ๅ…ฅไปปๆ„ไธชๆ•ฐ็š„ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ๏ผš >>> person('Bob', 35, city='Beijing') name: Bob age: 35 other: {'city': 'Beijing'} >>> person('Adam', 45, gender='M', job='Engineer') name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'} # ็”จ**ไผ ้€’ไธ€ไธชdict็ป™ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ๏ผš >>> extra = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, **extra) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'} # ๆณจๆ„kw่Žทๅพ—็š„dictๆ˜ฏextra็š„ไธ€ไปฝๆ‹ท่ด๏ผŒๅฏนkw็š„ๆ”นๅŠจไธไผšๅฝฑๅ“ๅˆฐๅ‡ฝๆ•ฐๅค–็š„extra # ๅ…ถไป–ๆ–นๅผไผ ้€’็š„้ƒฝๆ˜ฏๅฏน่ฑก็š„ๅผ•็”จ # ๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ # ็”จไธ€ไธชๅˆ†้š”็ฌฆ*๏ผŒ*ๅ‰ไธบไฝ็ฝฎๅ‚ๆ•ฐ๏ผŒ*ๅŽ็š„ๅ‚ๆ•ฐๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ def person(name, age, *, city, job): print(name, age, city, job) # ่ฐƒ็”จๆ–นๅผๅฆ‚ไธ‹๏ผš person('Jack', 24, city='Beijing', job='Engineer') Jack 24 Beijing Engineer # ๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐๅฏไปฅๆœ‰็ผบ็œๅ€ผ # ๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ่ฐƒ็”จๆ—ถๅฟ…้กปไผ ๅ…ฅๅ‚ๆ•ฐๅ๏ผŒๅฆๅˆ™่ฐƒ็”จๅฐ†ๆŠฅ้”™ # ไธๆไพ›ๅ‚ๆ•ฐๅ็š„ๅ‚ๆ•ฐๅฐ†่ขซ่ง†ไธบไฝ็ฝฎๅ‚ๆ•ฐ # ๅฆ‚ๆžœๅ‡ฝๆ•ฐๅฎšไน‰ไธญๅทฒ็ปๆœ‰ไบ†ไธ€ไธชๅฏๅ˜ๅ‚ๆ•ฐ๏ผŒๅŽ้ข็š„ๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐๅฐฑไธๅ†้œ€่ฆๅˆ†้š”็ฌฆ*ไบ†๏ผš def person(name, age, *args, city, job): print(name, age, args, city, job) # ๅคš็งๅ‚ๆ•ฐ็ป„ๅˆไฝฟ็”จๆ—ถ๏ผŒๅ‚ๆ•ฐๅฎšไน‰็š„้กบๅบๅฟ…้กปๆ˜ฏ๏ผšๅฟ…้€‰ๅ‚ๆ•ฐใ€้ป˜่ฎคๅ‚ๆ•ฐใ€ๅฏๅ˜ๅ‚ๆ•ฐใ€ๅ‘ฝๅๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐๅ’Œๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ # ๅฏนไบŽไปปๆ„ๅ‡ฝๆ•ฐ๏ผŒ้ƒฝๅฏไปฅ้€š่ฟ‡็ฑปไผผfunc(*args, **kw)็š„ๅฝขๅผ่ฐƒ็”จๅฎƒ๏ผŒๆ— ่ฎบๅฎƒ็š„ๅ‚ๆ•ฐๆ˜ฏๅฆ‚ไฝ•ๅฎšไน‰็š„ใ€‚ #################################################### # ้ซ˜็บง็‰นๆ€ง #################################################### # ๅˆ‡็‰‡๏ผŒไปŽstart่ตท๏ผŒๅˆฐendไธบๆญข๏ผˆไธๅŒ…ๆ‹ฌend๏ผ‰๏ผŒๆญฅ้•ฟstep # list_or_tuple_or_str[start:end:step] # ่ตทๅง‹ไฝ็ฝฎ้ป˜่ฎคๆ˜ฏ0๏ผŒ็ป“ๆŸไฝ็ฝฎ้ป˜่ฎคๆœ€ๅŽไธ€ไธชๅ…ƒ็ด +1๏ผŒๆญฅ้•ฟ้ป˜่ฎค1 # ๅชๅ†™[:]ๅฏไปฅๅŽŸๆ ทๆ‹ท่ดไธ€ไธชlist๏ผš L2 = L[:] # ่ฟญไปฃ # dict่ฟญไปฃ # ่ฟญไปฃkey๏ผš for key in d # ่ฟญไปฃvalue๏ผš for value in d.values() # ๅŒๆ—ถ่ฟญไปฃ๏ผš for k, v in d.items() # ๅˆคๆ–ญไธ€ไธชๅฏน่ฑกๆ˜ฏๅฆๅฏ่ฟญไปฃ๏ผš from collections import Iterable isinstance('abc', Iterable) True # ๅ†…็ฝฎ็š„enumerateๅ‡ฝๆ•ฐๅฏไปฅๆŠŠไธ€ไธชlistๅ˜ๆˆ็ดขๅผ•-ๅ…ƒ็ด ๅฏน: for i, value in enumerate(['A', 'B', 'C']): print(i, value) 0 A 1 B 2 C # ๅˆ—่กจ็”Ÿๆˆๅผ # ็”จrangeๅ‡ฝๆ•ฐ๏ผš list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # ็”จforๅพช็Žฏ๏ผš [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # ็”จๅธฆๆกไปถ็š„forๅพช็Žฏ๏ผš [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] # ไธคๅฑ‚ๅพช็Žฏ๏ผš [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] # ไนŸๅฏไปฅไฝฟ็”จไธคไธชๅ˜้‡ๆฅ็”Ÿๆˆlist๏ผš d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + '=' + v for k, v in d.items()] ['y=B', 'x=A', 'z=C'] # ็”Ÿๆˆๅผ # ๅฆ‚ๆžœไธ€ไธชๅ‡ฝๆ•ฐๅฎšไน‰ไธญๅŒ…ๅซyieldๅ…ณ้”ฎๅญ—๏ผŒ้‚ฃไนˆ่ฟ™ไธชๅ‡ฝๆ•ฐๅฐฑไธๅ†ๆ˜ฏไธ€ไธชๆ™ฎ้€šๅ‡ฝๆ•ฐ๏ผŒ่€Œๆ˜ฏไธ€ไธชgenerator # ่ฐƒ็”จgenerator่ฟ”ๅ›žไธ€ไธชgeneratorๅฏน่ฑก # ๅœจๆฏๆฌก่ฐƒ็”จnext()็š„ๆ—ถๅ€™ๆ‰ง่กŒ๏ผŒ้‡ๅˆฐyield่ฏญๅฅ่ฟ”ๅ›ž๏ผŒๅ†ๆฌกๆ‰ง่กŒๆ—ถไปŽไธŠๆฌก่ฟ”ๅ›ž็š„yield่ฏญๅฅๅค„็ปง็ปญๆ‰ง่กŒใ€‚ def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) o = odd() next(o) step 1 1 next(o) step 2 3 next(o) step 3 5 next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration # ๅŸบๆœฌไธŠไปŽๆฅไธไผš็”จnext()ๆฅ่Žทๅ–ไธ‹ไธ€ไธช่ฟ”ๅ›žๅ€ผ๏ผŒ่€Œๆ˜ฏ็›ดๆŽฅไฝฟ็”จforๅพช็Žฏๆฅ่ฟญไปฃ๏ผš for n in odd(): print(n) # ๆƒณ่ฆgenerator็š„่ฟ”ๅ›žๅ€ผ๏ผŒๅฟ…้กปๆ•่ŽทStopIteration้”™่ฏฏ๏ผŒ่ฟ”ๅ›žๅ€ผๅŒ…ๅซๅœจStopIteration็š„valueไธญ try: x = next(g) except StopIteration as e: print('Generator return value:', e.value) break # ๅฏไปฅ่ขซnext()่ฐƒ็”จๅนถไธๆ–ญ่ฟ”ๅ›žไธ‹ไธ€ไธชๅ€ผ็š„ๅฏน่ฑก็งฐไธบ่ฟญไปฃๅ™จ๏ผšIterator # ๅฏไปฅ็”จisinstance()ๅˆคๆ–ญไธ€ไธชๅฏน่ฑกๆ˜ฏๅฆๆ˜ฏIteratorๅฏน่ฑก๏ผš from collections import Iterator isinstance((x for x in range(10)), Iterator) True isinstance([], Iterator) False # ๅฏไปฅ้€š่ฟ‡iter()ๅ‡ฝๆ•ฐ่Žทๅพ—ไธ€ไธชIteratorๅฏน่ฑก๏ผš isinstance(iter([]), Iterator) True # Iterator็š„่ฎก็ฎ—ๆ˜ฏๆƒฐๆ€ง็š„๏ผŒๅชๆœ‰ๅœจ้œ€่ฆ่ฟ”ๅ›žไธ‹ไธ€ไธชๆ•ฐๆฎๆ—ถๅฎƒๆ‰ไผš่ฎก็ฎ—ใ€‚
55f695fa67f7da45d366a1050d43605e840fb902
Neanra/EPAM-Python-hometasks
/xhlhdehh-python_online_task_10_exercise_2/task_10_ex_2.py
910
4.375
4
"""Implement a function `most_common_words(file_path: str, top_words: int) -> list` which returns most common words in the file. <file_path> - system path to the text file <top_words> - number of most common words to be returned Example: print(most_common_words(file_path, 3)) >>> ['donec', 'etiam', 'aliquam'] > NOTE: Remember about dots, commas, capital letters etc. """ import re def most_common_words(text, top_words): if not isinstance(text, str): raise TypeError if type(top_words) is not int: raise TypeError top_count = dict() with open(text, 'r') as file_handle: for line in file_handle: for word in re.findall('\w+', line): top_count[word] = top_count.get(word, 0) + 1 result = [] for k, v in sorted(top_count.items(), key = lambda x: x[1], reverse=True)[:top_words]: result.append(k) return result
76810fb466e16423dfc6b51dfcbc0af936cc0445
kantel/pygamezero
/noc/simplemover/motion101_mouseacc.py
1,827
3.84375
4
# Example 1.10: Motion 101 (Acceleration towards Mouse) # aus ยปThe Nature of Codeยซ portiert nach Pygame Zero # 14. Juni 2020 by Jรถrg Kantel import pgzrun import pygame from pvector import PVector import sys WIDTH = 400 HEIGHT = 400 TITLE = "Motion 101: Acceleration Towards Mouse" RADIUS = 16 class Mover(object): def __init__(self, x, y, r): self.location = PVector(x, y) self.velocity = PVector(0, 0) self.radius = r self.topspeed = 10 def display(self): screen.draw.filled_circle((self.location.x, self.location.y), self.radius, (255, 0, 0)) screen.draw.circle((self.location.x, self.location.y), self.radius, (0, 0, 0)) def update(self): mouse_x, mouse_y = pygame.mouse.get_pos() mouse = PVector(mouse_x, mouse_y) dir = mouse - self.location dir.normalize() dir.mult(0.5) self.acceleration = dir self.velocity.add(self.acceleration) self.velocity.limit(self.topspeed) self.location.add(self.velocity) def check_edges(self): if (self.location.x > WIDTH - RADIUS): self.location.x = WIDTH - RADIUS self.velocity.x *= -1 elif (self.location.x < RADIUS): self.location.x = RADIUS self.velocity.x *= -1 if (self.location.y > HEIGHT - RADIUS): self.location.y = HEIGHT - RADIUS self.velocity.y *= -1 elif (self.location.y < RADIUS): self.location.y = RADIUS self.velocity.y *= -1 mover = Mover(200, 200, RADIUS) def draw(): screen.fill((149, 224, 245)) mover.display() def update(): mover.update() mover.check_edges() def on_key_down(): ## Spielende mit ESC if keyboard.escape: sys.exit() pgzrun.go()
cb1e63b6692d07874fac623c3ae037d473297be8
Canadasunyan/codes
/031-ๅˆ†่›‹็ณ•้—ฎ้ข˜.py
849
3.71875
4
# ๅˆ†่›‹็ณ•้—ฎ้ข˜ # ็ป™ๅฎšไธ€ไธชList่กจ็คบๆฏไธชไบบ็š„้œ€ๆฑ‚้‡้‡, ๅฆไธ€ไธชList่กจ็คบๆฏไธช่›‹็ณ•็š„้‡้‡, ๆฏไบบๆœ€ๅคšๅพ—ๅˆฐไธ€ไธช่›‹็ณ•, ่›‹็ณ•ไธ่ƒฝๅˆ‡ๅผ€, ่ฟ”ๅ›žๆปก่ถณ้œ€ๆฑ‚็š„ไบบๆ•ฐ # ๅ…ˆๆŽ’ๅบ, ่ฎพ็ฝฎไธคไธชๆŒ‡้’ˆไพๆฌกๆ‰ซๆๅˆ—่กจ def allocate(demand, supply): # ไผ˜ๅ…ˆๆปก่ถณ้œ€ๆฑ‚่พƒๅฐ็š„ไบบ demand, supply = sorted(demand), sorted(supply) i, j, count = 0, 0, 0 while i< len(demand) and j < len(supply): # ๆปก่ถณ้œ€ๆฑ‚, ๅˆ™่›‹็ณ•่ขซๆถˆ่€—(j++), ไธ€ไบบ็ฆปๅผ€(i++), ๆปก่ถณ็š„ไบบๆ•ฐๅŠ 1(count++) if demand[i] <= supply[j]: i += 1 j += 1 count += 1 else: # ๅฆ‚ๆžœๅฝ“ๅ‰็š„่›‹็ณ•ไธ่ƒฝๆปก่ถณ้œ€ๆฑ‚, ๅˆ™ๆ˜พ็„ถไธ่ƒฝๆปก่ถณๆ›ด้ซ˜็š„้œ€ๆฑ‚, ๅ› ๆญคๆ‰”ๆމๆญค่›‹็ณ• j += 1 return count print(allocate([1, 2, 3, 4, 5, 6], [3, 3, 3, 4, 5, 5]))
82f00760019a48bd84a303bc98303165a23199ec
glatif1/Practice-Programs-in-Python
/MiniPrograms/numberguessinggame.py
851
4.0625
4
import random actualguessesTaken = 0 print("This is the number guessing game!!!") number = random.randint(1, 20) print(' the number is between 1 and 20.') continuegame='y' while actualguessesTaken < 6: while continuegame =='y': Playerguess = int(input("Enter your guess:")) actualguessesTaken = actualguessesTaken + 1 if Playerguess < number: print('Your guess is too low.') if Playerguess > number: print('Your guess is too high.') if Playerguess == number: print("That is correct! You got it in", actualguessesTaken,"guesses!") exit() continuegame = input("Would you like to continue?'y' or 'n':").lower() if Playerguess != number: print('Too many guesses. The number was ', number) print("You took",actualguessesTaken,"guesses")
655d31517f2bd37590ed357f4bbde52a47132b86
clairerousell/Spotify-Top-50-2019-COSI-10A-Final-Project
/.ipynb_checkpoints/chatbot-checkpoint.py
3,636
4.125
4
from random import choice import spotify_info computerResponses = [] # list of all computer's questions humanResponses = [] # list of all the person's responses def spotify_helper(): """ gives a list of songs to the user based on their music taste this function asks the user questions to narrow down the list """ userComment = input("Computer >> Hello! I am a chatbot that will recommend you songs based on your music taste. Why don't you tell me what kinds of songs you're looking for? (e.g. genre, danceability, song length)\nThe User >> ") while userComment not in ["goodbye","bye","quit","exit"]: humanResponses.append(userComment) response = respond(userComment) if response in computerResponses: response = "Once again, "+response computerResponses.append(response) print("Computer >> "+response) userComment = input("The User >> ") print("bye") def respond(comment): """ generate a computer response to the user's comment""" if contains(comment,popWords): return choice(popResponses) if contains(comment,trapWords): return choice(trapResponses) if contains(comment,rapWords): return choice(rapResponses) if contains(comment,hiphopWords): return choice(hiphopResponses) if contains(comment,latinWords): return choice(latinResponses) if contains(comment,edmWords): return choice(edmResponses) if contains(comment,danceWords): return choice(danceResponses) if contains(comment,lengthWords): return choice(lengthResponses) if contains(comment,energyWords): return choice(energyResponses) return choice(otherResponses) def contains(sentence,words): """ true if one of the words is in the sentence where sentence is a string and words is a list of strings """ wordsInSentence = [word for word in words if word in sentence] return len(wordsInSentence) >= 1 def contains2(sentence,words): """ a more efficient test to see if a word in the list words is also in the string sentence. Note, this will return True for contains2("lovely day",["el"]) which might not be what you wanted. We could first split sentence into words, which might be better! """ for w in words: if w in sentence: return True return False # Here are the sad keywords and responses to sad comments popWords = "pop".split() popResponses=[ "Here are some pop songs:"+spotify_info.printSongList(spotify_info.pop) ] rapWords = "rap".split() sadResponses=[ "Here are some rap songs:"+(spotify_info.printSongList(spotify_info.rap)) ] hiphopWords = "hip hop hiphop".split() hiphopResponses=[ "Here are some hip hop songs:"+(spotify_info.printSongList(spotify_info.hip_hop)) ] edmWords = "edm".split() edResponses=[ "Here are some edm songs:"+(spotify_info.printSongList(spotify_info.edm)) ] trapWords = "trap".split() trapResponses=[ "Here are some trap songs:"+(spotify_info.printSongList(spotify_info.trap)) ] latinWords = "latin".split() latinResponses=[ "Here are some latin songs:"+(spotify_info.printSongList(spotify_info.latin)) ] # We give these responses if there is nothing else to say! generalResponses = [ "What genre of music is your favorite?.", "Do you mainly listen to short songs or long songs?", "Do you like your music to be high ir low energy?", "What genre of music would you like to listen to?" ] if __name__=="__main__": spotify_helper() # call spotify_helper when run as a script # but not when imported
a31cbfae58ed2eac0194c38ac979a8bdadc4cf65
dictator-x/practise_as
/algorithm/leetCode/1192_critical_connections_in_a_network.py
1,005
3.5625
4
""" 1192. Critical Connections in a Network """ from typing import List class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph = collections.defaultdict(set) for e1, e2 in connections: graph[e1].add(e2) graph[e2].add(e1) visited = [-1] * n ret = [] self.dfs(0, -1, 0, visited, ret, graph) return ret def dfs(self, cur, parent, level, visited, ret, graph): # give visited intial value visited[cur] = level + 1 for n in graph[cur]: if n == parent: continue elif visited[n] == -1: # dfs visited[cur] = min(self.dfs(n, cur, level+1, visited, ret, graph), visited[cur]) else: visited[cur] = min(visited[cur], visited[n]) if visited[cur] == level + 1 and cur != 0: ret.append([parent, cur]) return visited[cur]
7a9c209c8260c5134d92ae9930d24d06acfa6336
sumitgupta7132/Coursera_Python_Assignment
/Coursera_Using Python to Access Web Data/Week4/Assignment_week4.1.py
1,060
3.515625
4
#Sumit Gupta # We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. # # Sample data: http://py4e-data.dr-chuck.net/comments_42.html (Sum=2553) # Actual data: http://py4e-data.dr-chuck.net/comments_257178.html (Sum ends with 7) # # You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis. from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") l=[] tags = soup('span') for tag in tags: l.append(int(tag.contents[0])) print(sum(l)) # Enter - http://py4e-data.dr-chuck.net/comments_257178.html # 2407
52176e71fd521a186a17528d35480a00b7ec17c2
ares5221/Data-Structures-and-Algorithms
/03ๅญ—็ฌฆไธฒ็›ธๅ…ณ/04ๆœ€้•ฟๅ…ฌๅ…ฑๅญๅบๅˆ—LCS/LCS.py
1,461
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ๆœ€้•ฟๅ…ฌๅ…ฑๅญๅบๅˆ— """ def GetLCSLength(aString, bString, aLength, bLength): cMat = [[0 for i in range(bLength+1)] for j in range(aLength+1)] fMat = [[0 for i in range(bLength+1)] for j in range(aLength+1)] for i in range(aLength): for j in range(bLength): if aString[i] == bString[j]: cMat[i + 1][j + 1] = cMat[i][j] +1 fMat[i + 1][j + 1] = 'OK' elif cMat[i + 1][j] > cMat[i][j + 1]: cMat[i + 1][j + 1] = cMat[i + 1][j] fMat[i + 1][j + 1] = 'Left' else: cMat[i + 1][j + 1] = cMat[i][j + 1] fMat[i + 1][j + 1] = 'Up' for i in cMat: print(i) print('') for j in fMat: print(j) print('') return cMat, fMat def GetLCSString(aString, fMat, i, j): if i == 0 or j == 0: return if fMat[i][j] == 'OK': GetLCSString(aString, fMat, i-1, j-1) print(aString[i-1],end='') elif fMat[i][j] == 'Left': GetLCSString(aString,fMat,i,j-1) else: GetLCSString(aString,fMat,i-1,j) if __name__ == '__main__': # aString = 'ABCBDAB' # bString = 'BDCABA' aString = "a1b2c3" bString = "1a1wbz2c123a1b2c123"; aLength = len(aString) bLength = len(bString) cMat,fMat = GetLCSLength(aString, bString,aLength,bLength) GetLCSString(aString, fMat, aLength, bLength)
d5bef25b34b121f6462d4f3556dfc9dd79f732d7
hemanthsavasere/Data_Structures
/Linked_List.py
366
3.8125
4
class Node(object): def __init__(self, val): self.value = val self.next = None def add_beginning(self,node): node.next = self if __name__ == "__main__": head = Node(1) b = Node(2) c = Node(5) head.next = b b.next = c temp = head while temp is not None: print temp.value temp = temp.next
3b1fba0a122b061e73789f222c18ae04da809f14
tenzin12345678910/cssi-labs
/python/labs/functions-cardio/myfunctions.py
422
3.5625
4
print("Welcome to my calcutor") def count_vowels(s): numA = s.count("a") numE = s.count("e") numI = s.count("i") numO = s.count("o") numU = s.count("u") numY = s.count("y") sumVowels = numA + numE + numI + numO + numU + numY return sumVowels def count_total(s): return print(count_vowels("Hello there, you exist")) countNum = count_vowels("Hello there, you exist") print(countNum)
9f1a4349a27a691037a94b6c06602bcc3a503ebb
athola/PythonTheHardWay
/RegexStrip.py
891
4.1875
4
import re, sys def stripString(string, char=""): newStr = "" if (char==""): frontStrippedStr = "" stripFrontSpaceRegex = re.compile(r'^\s+') frontStrippedStr = stripFrontSpaceRegex.sub('', string) stripEndSpaceRegex = re.compile(r'\s+$') newStr = stripEndSpaceRegex.sub('', frontStrippedStr) else: stripCharRegex = re.compile(char) newStr = stripCharRegex.sub('', string) return newStr def main(): useCommandLine = False if (len(sys.argv) > 1): useCommandLine = True if (useCommandLine): string = sys.argv[1] char = sys.argv[2] else: string = input("Please enter a string: ") char = input("Please enter a character to strip from the string: ") newString = stripString(string, char) print(newString) main()
c205c9bc8346eb013e3c7131b9edd4ed60678ee6
Neckmus/itea_python_basics_3
/_medviediev_oleksandr/02/04_list_comprehensions.py
149
3.71875
4
my_list = [i for i in range(10) if not i % 2] ''' my_list = [] for i in range(10): if not i % 2: my_list.append(i) ''' print(my_list)
4e068ded725c5f580d84afef8d99c7626db57085
EmanuelYano/python3
/URI - Lista 6/1168.py
615
3.6875
4
#!/usr/bin/env python3 #-*- coding:utf-8 -*- # 1 -> 2 # 4 -> 4 # 7 -> 3 # 8 -> 7 # 2,3,5 -> 5 # 6,9,0 -> 6 n = int(input()) valor = [] for i in range(n): valor.append(input()) for i in valor: somaLed = 0 for num in i: if int(num) == 1: somaLed += 2 elif int(num) == 4: somaLed += 4 elif int(num) == 7: somaLed += 3 elif int(num) == 8: somaLed += 7 elif (int(num) == 2) or (int(num) == 3) or (int(num) == 5): somaLed += 5 else: somaLed += 6 print("%d leds"%somaLed) exit(0)
00b0c3dd323d18ba84b7c14c95bc4038eba7e6b2
Slendercoder/Caballos
/main.py
1,304
3.90625
4
# -*- coding: utf-8 -*- # Resolucion del problema de tres caballos en un tablero 3x3 import Caballos as C import sys sys.setrecursionlimit(10000) # Para incrementar el limite de la recursion import visualizacion as V # Solicita condicion inicial print(u'Introduzca el nรบmero de la casilla (1,...,9) en la que') print(u'desea un caballo como condiciรณn inicial.') print(u'Deje vacรญo si no desea condiciรณn inicial.') cInicial = input(u'Condiciรณn inicial? (1,...,9):') if len(cInicial) > 0: assert(int(cInicial)>0 and int(cInicial)<10) print(u'Resolviendo el problema con condiciรณn inicial', cInicial) cInicial = chr(int(cInicial) + 96) # print(cInicial) else: print(u"El problema se resolverรก sin condiciones iniciales.") print("Creando reglas...") reglas = C.crear_reglas() if len(cInicial) > 0: reglas += cInicial + "Y" A = C.String2Tree(reglas) print('Encontrando soluciones (paciencia, por favor!)...') listaSoluciones = C.Encuentra_Interpretaciones(A) print('Hay', str(len(listaSoluciones)), ' interpretaciones que resuelven el problema.') # print('Las interpretaciones son:\n', listaSoluciones) for x in range(len(listaSoluciones)): f = listaSoluciones[x] V.dibujar_tablero(f,x + 1) print('Visualizaciones guardadas en /Soluciones') print('Terminado!')
ac776e7c7f1124ab8b4971180f7bf677198bbbf7
edwardmasih/Python-School-Level
/Class 11/11-Programs/Armstrong Numbers upto a given Number.py
276
3.625
4
import math d=int(input("Enter the range (>100)- ")) for i in range (2,d): v=i c=0 while 1: a=v%10 c=c+a**3 v=math.floor(v/10) if v==0: break if i==c: print("The Armstrong number is",c)
c6be7b4763fcaa19789b854dc48c5e3a6484d2a4
RayshineRen/Classcial-Search
/UCS/UCSGraph.py
1,068
3.71875
4
from DataStructure import * from queue import PriorityQueue A = Node('A') B = Node('B') C = Node('C') D = Node('D') E = Node('E') G = Node('G') A.add_child(B, 1) A.add_child(C, 2) B.add_child(A, 1) B.add_child(D, 3) C.add_child(A, 2) C.add_child(E, 1) D.add_child(B, 3) D.add_child(G, 2) E.add_child(C, 1) E.add_child(G, 4) G.add_child(D, 2) G.add_child(E, 4) def UCS(root:Node, Goal:str): frontier = PriorityQueue() explored = set() frontier.put((0, [root])) while True: if(frontier.qsize() <= 0): return False accu_cost, path = frontier.get() cur = path[-1] if cur.label == Goal: return (accu_cost, path) for child in cur.children: cur_cost = accu_cost+child.cost cur_path = path+[child.dest] if not cur_path[-1] in explored: frontier.put((cur_cost, cur_path)) explored.add(cur) cost, path = UCS(A, 'G') if path!=False: for node in path: print(node.label+"->",end="") print("Gooooal! with cost is ",cost)
dc4700272c4061452989e650f90ddf1e4de1dce9
kevincleppe/Python-Crash-Course
/Chapter_10/rememberv2.py
334
3.625
4
import json filename='usernamev2.json' try: with open(filename) as f: username=json.load(f) except FileNotFoundError: username=input("what is your name: ") with open(filename, 'w') as f: json.dump(username, f) print(f"We will remember you, {username}") else: print(f"Welcome back {username}")
c750a3e21c6a25d1095a028ae4e2c2bb98bdded6
Danielarwj/CSE
/notes/Daniel Remington- Inheritance.py
9,866
3.546875
4
class Item(object): def __init__(self, name=None, health=None): self.name = name self.health = health class Armor(Item): def __init__(self, name, classification, health): super(Armor, self).__init__(name, health) self.type = classification def get_hit(self, dmg): print("Your armor looses some health") self.health -= 1 def power(self, exertion): print("Your helmet tries to shoot energy back to the enemy") class Helmet(Armor): def __init__(self, name, color, protection_ability, health=100): super(Helmet, self).__init__(name, "Helmet", health) self.ability = protection_ability self.color = color class Aegon(Helmet): def __init__(self): super(Aegon, self).__init__("Aegon", "Blue", "Indestructible", 999999999999999999999999999999999999999999999) self.power = 100 def get_hit(self, dmg): super(Aegon, self).get_hit(dmg) print("Your helmet cannot be damaged.") self.health += 1 def power(self, exertion): super(Aegon, self).power(100) print("Your helmet sends back TEN THOUSANDS units of energy. Good Job") self.power += 1 class Gold(Helmet): def __init__(self): super(Gold, self).__init__("Gold", "Gold", "Normal", health=100) self.power = 50 def get_hit(self, dmg): super(Gold, self).get_hit(dmg) print("Your helmet tries to fight back. IT IS A FUGILE ATTEMPT!") def power(self, exertion): super(Gold, self).power(50) print("Your helmet is attempting... so close but no.") class Leaf(Helmet): def __init__(self): super(Leaf, self).__init__("Leaf", "Green", "Weak", health=10) self.power = 1 def get_hit(self, dmg): super(Leaf, self).get_hit(dmg) print("Your helmet doesn't even try. It is destroyed") def power(self, exertion): super(Leaf, self).power(1) print("Don't even try.") class Weapon(Item): def __init__(self, size, name, health, classification): super(Weapon, self).__init__() self.health = health self.size = size self.name = name self.classification = classification class Sword(Weapon): def __init__(self, name, agility, weight, size, damage_output, health=100): super(Sword, self).__init__(size, name, health, "Sword") self.agility = agility self.weight = weight self.name = name self.health = health self.damage_output = damage_output class SevenBranchedSword(Sword): def __init__(self): super(SevenBranchedSword, self).__init__("Seven Branched Sword", "Quick", 150, 25, 100, 30) class Urumi(Sword): def __init__(self): super(Urumi, self).__init__("The Urumi", "Quick", 400, 35, 999999999999999999999, 99999999) class Pencil(Sword): def __init__(self): super(Pencil, self).__init__("A Pencil", "Slow", 0.2, 12, 2, 3) class Noodle(Sword): def __init__(self): super(Noodle, self).__init__("A Noodle", "Immobile", "0.001", 5, 1, 1) class SchoolMaterials(Item): def __init__(self, name, health): super(SchoolMaterials, self).__init__() self.name = name self.health = health class Food(SchoolMaterials): def __init__(self, name, taste, size, quality, health, restoration): super(Food, self).__init__(name, health) self.taste = taste self.size = size self.quality = quality self.health_restoration = restoration class CrappyLunch(Food): def __init__(self, name, restoration, size, edibility, health): super(CrappyLunch, self).__init__(name, "Deplorable", size, "Bad", restoration, health) self.name = name self.health_restoration = restoration self.size = size self.edibility = edibility # Reheated Broccoli, Chili, Pizza, Raw Chicken class Chili(CrappyLunch): def __init__(self, color, present_container, health_restoration, size, health): super(Chili, self).__init__("Chili", -20, size, "Unpalatable", health) self.color = color self.present_container = present_container self.health_restoration = health_restoration class MeatLoversChili(Chili): def __init__(self): super(MeatLoversChili, self).__init__("Brown", "Styrofoam_Cup", -100, 80, -90) class VegetarianChili(Chili): def __init__(self): super(VegetarianChili, self).__init__("Green", "Red_Cup", -70, 15, 9) class Pizza(CrappyLunch): def __init__(self, restoration, size, edibility, color, health): super(Pizza, self).__init__("Pizza", restoration, size, edibility, health) self.color = color self.size = size self.health_restoration = restoration self.edibility = edibility class SaladPizza(Pizza): def __init__(self): super(SaladPizza, self).__init__(10, 15, "Tolerable", "Green", 10) class CannedTunaPizza(Pizza): def __init__(self): super(CannedTunaPizza, self).__init__(1, 25, "Disgusting", "Brown", 10) class DecentPizza(Pizza): def __init__(self): super(DecentPizza, self).__init__(20, 10, "Good", "Normal", 10) class TeacherSustenance(Food): def __init__(self, name, taste, size, quality, restoration, health): super(TeacherSustenance, self).__init__(name, taste, size, quality, health, restoration) self.name = name self.taste = taste self.size = size self.quality = quality self.health_restoration = restoration class Eggs(TeacherSustenance): def __init__(self, taste, size, quality, state, health, texture, name, restoration=100): super(Eggs, self).__init__("EGGS", taste, size, quality, restoration, health) self.taste = taste self.size = size self.quality = quality self.texture = texture self.state = state self.health_restoration = restoration self.name = name class BoiledEggs(Eggs): def __init__(self): super(BoiledEggs, self).__init__("GOOD", 10, "GOOD", "BOILED", "MUSHY", "Boiled Eggs", 10) class ScrambledEggs(Eggs): def __init__(self): super(ScrambledEggs, self).__init__("GREAT", 12, "GOOD", "SCRAMBLED", "SOFT", "Scrambled Eggs", 10) class VervainHummingbirdEggs(Eggs): def __init__(self): super(VervainHummingbirdEggs, self).__init__("GREAT", 0.3, "GREAT", "RAW", "LIQUID", "Vervain Hummingbird Eggs", 9999999999999) class BodyArmor(Armor): def __init__(self, name, protection_ability, size, damage_output, health=100): super(BodyArmor, self).__init__(name, "Body Armor", health) self.protection_ability = protection_ability self.size = size self.name = name self.damage_output = damage_output class Cardstock(BodyArmor): def __init__(self, exertion): super(Cardstock, self).__init__("Cardstock", "WEAK", 15, 0, 20) self.power = 10 self.exertion = exertion def get_hit(self, dmg): super(Cardstock, self).get_hit(dmg) print("Your armor tries to fight back. IT IS A FUGILE ATTEMPT!") def power(self, exertion): super(Cardstock, self).power(10) self.exertion = 10 print("It can't exert power back at them! It is destroyed") class ModularTacticalVest(BodyArmor): def __init__(self, exertion, size): super(ModularTacticalVest, self).__init__('Modular Tactical Vest', "STRONG", size, 9999999, 10) self.exertion = exertion self.power = 99999999999 def get_hit(self, dmg): super(ModularTacticalVest, self).get_hit(dmg) print("Your armor hits them back with the MIGHT OF ZEUS") def power(self, exertion): super(ModularTacticalVest, self).power(99999999999) self.exertion = 999999999 print("YOU ARE INVINCIBLE! They are destroyed") class Lasers(Weapon): def __init__(self, size, name, health, classification, joules, energy_output, damage_output): super(Lasers, self).__init__(size, name, health, classification) self.joules = joules self.energy = energy_output self.size = size self.name = name self.classification = classification self.damage_output = damage_output class TwoPettawattLaser(Lasers): def __init__(self, damage_ouput): super(TwoPettawattLaser, self).__init__(78, "Two Pettawatt Laser", 99999, Lasers, 2000000000000, 2000000000000, 2000000000) self.damage_output = damage_ouput class LaserPointer(Lasers): def __init__(self, damage_output): super(LaserPointer, self).__init__(20, "Laser Pointer", 1, Lasers, 20, 10, 1) self.damage_output = damage_output class Character(object): def __init__(self, name, health: int, weapon, armor): self.name = name self.health = health self.weapon = weapon self.armor = armor def take_damage(self, damage: int): if self.armor.health >= damage: print("No damage is done because of some AMAZING armor") else: self.health -= damage - self.armor.health print("%s has %d health left" % (self.name, self.health)) def attack(self, target): print("%s attacks for %s for %d damage" % (self.name, target.name, self.weapon.health)) target.take_damage(self.weapon.health) sword = Sword("Sword", "Quick", 15, 20, 10) canoe = Sword("Canoe Sword", "SLOW", 90, 150, 42) weibe_armor = BodyArmor("Armor of the gods", "GOOD", 18, 10000000000000000000000000000) Laser_pointer_1 = LaserPointer(5) _007_Laser = TwoPettawattLaser(7000) Cardstock_Armor = Cardstock(10)
d8de788e42e147b3c971ee4e39d955fd824827c0
Joyykim/study_algorithm
/woowa_techcourse/4.py
843
3.65625
4
def get_distance(a, b, n): if a > b: a, b = b, a way1 = abs(a - b) way2 = (n - 1 - b) + a + 1 short = min(way1, way2) return short def solution(n, board): table = {} for y, sub_list in enumerate(board): for x, number in enumerate(sub_list): table[number] = (x, y) current = [0, 0] answer = 0 for i in range(1, (n ** 2) + 1): # i์˜ ์นธ์„ ์•Œ์•„๋‚ด๊ธฐ location = table[i] # ์ขŒ์šฐ ๋ฐฉํ–ฅ ๊ฒฐ์ • answer += get_distance(current[0], location[0], n) # ์ƒํ•˜ ๋ฐฉํ–ฅ ๊ฒฐ์ • answer += get_distance(current[1], location[1], n) # ์—”ํ„ฐ answer += 1 # ์ปค์„œ ์ด๋™ current = location return answer r = solution(4, [[11, 9, 8, 12], [2, 15, 4, 14], [1, 10, 16, 3], [13, 7, 5, 6]]) print(r)
968a7bf225705be17806e907a2a14753fcbcea2e
Swastik-Saha/Python-Programs
/gramenerPython.py
1,428
3.734375
4
#Program - Calculating the Median import sys import csv import operator #Display the contents of the CSV file print open('salaries.csv').read() data = csv.DictReader(open('salaries.csv','rb')) data_values = sorted(data) data_values_plumbers = {} data_values_lawyers = {} data_values_doctors = {} for i in xrange(len(data_values)): if data_values[i].values()[2]=='Plumbers': data_values_plumbers[data_values[i].values()[1]]=data_values[i].values()[0] data_values_plumbers = dict((k,int(v)) for k,v in data_values_plumbers.iteritems()) data_values_plumbers = data_values_plumbers.values() for i in xrange(len(data_values)): if data_values[i].values()[2]=='Lawyers': data_values_lawyers[data_values[i].values()[1]]=data_values[i].values()[0] data_values_lawyers = dict((k,int(v)) for k,v in data_values_lawyers.iteritems()) data_values_lawyers = data_values_lawyers.values() for i in xrange(len(data_values)): if data_values[i].values()[2]=='Doctors': data_values_doctors[data_values[i].values()[1]]=data_values[i].values()[0] data_values_doctors = dict((k,int(v)) for k,v in data_values_doctors.iteritems()) data_values_doctors = data_values_doctors.values() print "Plumbers ",sorted(data_values_plumbers)[len(data_values_plumbers)//2] print "Lawyers ",sorted(data_values_lawyers)[len(data_values_lawyers)//2] print "Doctors ",sorted(data_values_doctors)[len(data_values_doctors)//2]
56e50c7a5e7a29c4645f0de0dcae47a9b5751245
dogustuluk/RockPaperScissorGameWithNoIfStatements
/RPSNoIfStatements.py
789
3.875
4
import random while True: print("make your choice:") choice = input() choice = choice.lower() print("my choice is:", choice) choices = ['rock','paper','scissors'] computerChoice = random.choice(choices) print("computer choice is:", computerChoice) choiceDict = {'rock': 0, 'paper': 1, 'scissors': 2} choiceIndex = choiceDict.get(choice,3) computerIndex = choiceDict.get(computerChoice) resultMatrix = [[0,2,1], [1,0,2], [2,1,0], [3,3,3] ] resultIdx= resultMatrix[choiceIndex][computerIndex] resultMessage = ['it is a tie','you win','you lose','invalid choicerock'] result = resultMessage[resultIdx] print(result) print()
0544b3ff4d8edbd019f8be3f25da907164b7e3e7
Manu-Fraile/IMDB-film-recommendator
/src/main/python/Main.py
2,050
3.703125
4
#!/usr/bin/python3.8 import sys import pandas as pd from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer # defining the function that takes in movie title as input and returns the top 10 recommended movies def recommender(title, cosine_sim): # initializing the empty list of recommended movies recommended_movies = [] # gettin the index of the movie that matches the title idx = indices[indices == title].index[0] # creating a Series with the similarity scores in descending order score_series = pd.Series(cosine_sim[idx]).sort_values(ascending=False) # getting the indexes of the 10 most similar movies top_10_indexes = list(score_series.iloc[1:11].index) # populating the list with the titles of the best 10 matching movies for i in top_10_indexes: recommended_movies.append(list(df.index)[i]) return recommended_movies if __name__ == "__main__": df = pd.DataFrame() for line in sys.stdin: parsed = line.replace("[", "").replace("]", "").rsplit(',', 1) toAppend = pd.DataFrame([parsed], columns=["title", "bag_of_words"]) df = df.append(toAppend) df.set_index('title', inplace=True) print(df) # instantiating and generating the count matrix count = CountVectorizer() count_matrix = count.fit_transform(df['bag_of_words']) # generating the cosine similarity matrix cosine_sim = cosine_similarity(count_matrix, count_matrix) # creating a Series for the movie titles so they are associated to an ordered numerical # list we will use in the function to match the indexes indices = pd.Series(df.index) recommendations = recommender('The Strangers', cosine_sim) print('\n\n-----------------------------------------------------') print('| If you liked THE STRANGERS, you could also like |') print('-----------------------------------------------------') for recommendation in recommendations: print('- ' + recommendation)
96eac0cd90679114e5eb403e6c4c2c4f1b3ba02a
baihuanyu/text
/ๅคš็บฟ็จ‹/ๅคš็บฟ็จ‹ๆกˆไพ‹11ๅ…ฑไบซๅ˜้‡้—ฎ้ข˜.py
766
3.578125
4
# ๅฏผๅ…ฅๅคš็บฟ็จ‹ import threading sum = 0 loopsum = 1000000 def myAdd(): '''ๅฎšไน‰ไธ€ไธชsumๆฏๆฌกๅŠ ไธ€็š„ๅ‡ฝๆ•ฐ''' global sum , loopsum for i in range(1,loopsum) : sum +=1 def myMinu(): '''ๅฎšไน‰ไธ€ไธชๅ‡ฝๆ•ฐ sumๆฏๆฌกๅ‡ไธ€''' global sum ,loopsum for i in range(1,loopsum): sum -=1 if __name__ == '__main__': # ๆ”นๆˆๅคš็บฟ็จ‹๏ผš print('่ฎก็ฎ—ไธญ----->ๆ€ปๅ’Œๆ˜ฏ :{0}'.format(sum)) t = threading.Thread(target=myAdd,args=()) t.start() t1 =threading.Thread(target=myMinu,args=()) t1.start() # ๅคš็บฟ็จ‹็ญ‰ๅพ… t.join() t1.join() print('done ใ€‚ใ€‚ใ€‚ใ€‚ใ€‚{0}'.format(sum)) # ๅ‡บ็Žฐ่ฟ™ไธช็ป“ๆžœๅŽŸๅ›  1ใ€‚ + - ไธๆ˜ฏๅŽŸๅญๆ“ไฝœ ๏ผŒ ๆ‰€ไปฅๅœจๅ…ฑไบซๅ˜้‡ๆ—ถๅ€™ๅฐฑๅ‘็”Ÿไบ†ๅ†ฒ็ช
0925a8cda45611d53b2d5c9fc100603ddd9450ee
Vimaltheprogrammer/dictionary
/dictmethods.py
444
3.90625
4
myDict = {"Vimal": 'A Beginer', "Manoj":'A salesperson', "list":[1,5,10,45,8], "andict": {"umesh":'master of coding'} } # print(myDict.keys()) # print the keys of dictionery # print(myDict.values()) # print all values of the dictionery # print(myDict.items()) #cprint all (key + value)all content of dictionery # print(myDict) # updatedict = { # "Maheep":"Chamadi" # } # myDict.update(updatedict) # to update a dictonery print(myDict.get("Vimal"))
f2b2d425ac65220eb75806dc1ece6e37b4d11c8f
mmoscovics/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
367
3.765625
4
#!/usr/bin/python3 """ Class MyInt that inherits from int. """ class MyInt(int): """ Class MyInt that inherits from int inverts eq and ne operators. """ def __eq__(self, value): """ Returns ne value. """ return super().__ne__(value) def __ne__(self, value): """ Returns eq value. """ return super().__eq__(value)