blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
9206528ea484b33d63978ae8c8c37a06ba332706
AbelhaJR/Huffman
/data_structures.py
6,365
4.125
4
# imports import os , heapq from collections import defaultdict from bitstring import BitArray # Global variables dic_char_codes = {} frequency = defaultdict(int) # GIT HUB link : https://github.com/AbelhaJR/Huffman # Functions # 1 - Read File def read_file(file_path : str)-> str: """Allow the python script reading the text file , removing all paragraphs and changing spaces by '-'.""" with open(file_path,"r",encoding="utf-8") as text_file : return text_file.read() # 2 - Huffman Coding def huffman_coding(file_text : str)->list: """Uses the Huffman Coding technique to compress data , allowing size reduction without losing anything.""" # Import the frequency default dictionary global frequency for character in file_text : frequency[character] += 1 heap = [[frequency, [letter, '']] for letter, frequency in frequency.items()] heapq.heapify(heap) # Push the smallest ( the smallest element is the one with the lowest frequency) to index 0 while len(heap) > 1: # Removes the smallest item that stays at index 0 first_small_element = heapq.heappop(heap) second_small_element = heapq.heappop(heap) # Add 0 or 1 to the number of bits for pair in first_small_element[1:]: pair[1] = '0' + pair[1] # Add 0 or 1 to the number of bits for pair in second_small_element[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [first_small_element[0] + second_small_element[0]] + first_small_element[1:] + second_small_element[1:]) # Return the iterable in sorted order , in this case we use lambda because if we didnt use it we would have to create a separate function for that . return sorted(heapq.heappop(heap)[1:], key=lambda element: (len(element[-1]), element)) # 3 - Encoding def encoded_bits_text(huffman_coding : list , file_text : str ) -> str: """Allow to encode the huffman tree refering to the characters and bit code.""" # Import global variables dic_char_codes global dic_char_codes for pair in huffman_coding : dic_char_codes[pair[0]] = pair[1] # Return a translation table that maps each character table = file_text.maketrans(dic_char_codes) return file_text.translate(table) # 4 - Padding encoding def pad_encoded_text(encoded_bits_text : str) -> str: """Allow to add the ammount of zeros to beggiining the if the overall lenght of final encoded is not multiple of 8 (8-bit).""" padding = 8-(len(encoded_bits_text)%8) text = encoded_bits_text.ljust(len(encoded_bits_text)+padding,'0') padded_data = "{0:08b}".format(padding) encoded = padded_data + text return encoded # 5 - compressed file def compressed_file(file_path : str)-> str: """Allow to compress a specific file by using helper functions that are in the python script.""" file_text = read_file(file_path) # Get the file name split -> [0] = file_name / [1] = file_extension file_name = os.path.splitext(file_path)[0] # Create the new file -> file_name + file_extension file_details = file_name + ".bin" bit_code_unique_character = encoded_bits_text(huffman_coding(file_text),file_text) padding_bit_code_unique_character = pad_encoded_text(bit_code_unique_character) # Transform String of corresponding bit codes to a BitArray by using the library bitString bit = BitArray(bin=padding_bit_code_unique_character) # We use the parameter 'wb' -> w = write , b = bit with open(file_details,'wb') as compressed_file : bit.tofile(compressed_file) return file_details # 6 - Decompress file def decompress_file(compressed_file_path : str)->str : """Allow to decompressed a specific file by using helper functions that are in the python script.""" # Get the file name split -> [0] = file_name / [1] = file_extension file_name = os.path.splitext(compressed_file_path)[0] # Create the new file -> file_name + file_extension file_details = file_name+ "_after.txt" # We use the parameter 'rb' -> r = read , b = bit with open(compressed_file_path,'rb') as compressed_file: bit_string = "" byte = compressed_file.read(1) while(len(byte) > 0): byte = ord(byte) bits = bin(byte)[2:].rjust(8,'0') # Add bits to the bit_string bit_string += bits byte =compressed_file.read(1) # Initially to encode we use padding to add in case of need zeros to the initially code (8-bit) , so now is necessary to remove it encoded_text = remove_paddding(bit_string) decoded_text = decode_text(encoded_text) with open(file_details ,'w',encoding='utf-8') as output : output.write(decoded_text) return file_details # 7 - Remove padding def remove_paddding(bit_string : str) -> str : """Allow to remove the extra padding adding in the encode.""" # String Slice to remove the first 8 characters padded_info = bit_string[:8] extra_padding = int(padded_info,2) bit_string = bit_string[8:] encoded_text = bit_string[:-1*extra_padding] return encoded_text # 8 - Deconding def decode_text(encoded_text : str) -> str : """Allow to decode the compressed file containing the bit code for every single character in the original file.""" global dic_char_codes current_code = "" decoded_text = "" # We reverse the dictionary to be easier acessing the keys with the bit code chars_and_codes_reverse= dict((y, x) for x, y in dic_char_codes.items()) for bit in encoded_text: current_code+=bit if(current_code in chars_and_codes_reverse): char=chars_and_codes_reverse[current_code] decoded_text+=char current_code="" return decoded_text # 9 - Script def run_script(): """Allow to execute both compression and decompression.""" file_path = str(input("Insert File Path :")) compressed = compressed_file(file_path) decompress = decompress_file(compressed) run_script()
036d1c65f775dbb424dd7d905ac3dcf799a73e67
arcadiabill/Learn_GIT
/Src/Python/Intro to Tkinter/menu01.py
1,138
3.78125
4
from tkinter import * top = Tk() top.title('Find & Replace') Label(top,text="Find:").grid(row=0, column=0, sticky='e') Entry(top).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=9) Label(top, text="Replace:").grid(row=1, column=0, sticky='e') Entry(top).grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=9) Button(top, text="Find").grid(row=0, column=10, sticky='ew', padx=2, pady=2) Button(top, text="Find All").grid(row=1, column=10, sticky='ew', padx=2) Button(top, text="Replace").grid(row=2, column=10, sticky='ew', padx=2) Button(top, text="Replace All").grid(row=3, column=10, sticky='ew', padx=2) Checkbutton(top, text='Match whole word only').grid(row =2, column=1, columnspan=4, sticky='w') Checkbutton(top, text='Match Case').grid(row =3, column=1, columnspan=4, sticky='w') Checkbutton(top, text='Wrap around').grid(row =4, column=1, columnspan=4, sticky='w') Label(top, text="Direction:").grid(row=2, column=6, sticky='w') Radiobutton(top, text='Up', value=1).grid(row=3, column=6, columnspan=6, sticky='w') Radiobutton(top, text='Down', value=2).grid(row=3, column=7, columnspan=2, sticky='e') top.mainloop()
3b8af5ee45028b94c0cfa4ab0e82d5e0d6f57e23
girishalwani/Training
/python prog/Pyhton Fundamentals/divisible by 5.py
158
4.21875
4
""" Write a program to find the given number is divisible by 5 """ a = 100 if(a%5 == 0): print("Divisible by 5") else: print("not divisible by 5")
ac27f0d5e2cfcec2f2e924ba11a47704940eb5ed
tspoon1/sales
/reporter.py
1,080
4.03125
4
# reporter.py import os import pandas def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Source: https://github.com/prof-rossetti/intro-to-python/blob/master/notes/python/datatypes/numbers.md#formatting-as-currency Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}" #> $12,000.71 print("READING GRADEBOOK CSV FILE...") #if csv file in same directory as this python script, csv filepath = name of the file #csv_filepath = "gradebook2.csv" #if the csv file is in the data directory, dont do "data/gradebook.csv" csv_filepath = os.path.join(os.path.dirname(__file__), "data", "gradebook.csv") print(os.path.abspath(csv_filepath)) grades = pandas.read_csv(csv_filepath) print("GRADES:", type(grades)) #print(dir(grades)) print(grades.head()) avg_grade = grades["final_grade"].mean() print(avg_grade) for index, row in grades.iterrows(): print(index) print(row["final_grade"]) print ("---")
0f17f01ef772b8596dc9f96d5eb3241202b39caa
sonhmai/harvard-cs50
/w7-sql/src7/favorites4.py
638
3.875
4
import csv # For counting favorites counts = {} # Open CSV file with open("CS50 2019 - Lecture 7 - Favorite TV Shows (Responses) - Form Responses 1.csv", "r") as file: # Create DictReader reader = csv.DictReader(file) # Iterate over CSV file for row in reader: # Force title to lowercase title = row["title"].lower() # Add title to counts if title in counts: counts[title] += 1 else: counts[title] = 1 # Print counts, sorted by key for title, count in sorted(counts.items(), key=lambda item: item[1], reverse=True): print(title, count, sep=" | ")
aa51dbada9633e1a55e23376860cb73da84b1c5e
CyborgVillager/Learning_py_info
/snake_game/snake.py
2,178
3.546875
4
# learning on how to make a snake game / user controls / etc # thanks in part to Engineer Man -> https://www.youtube.com/watch?v=rbasThWVb-c&t=85s # Engineer Man Python Playlist -> https://www.youtube.com/watch?v=lbbNoCFSBV4&list=PLlcnQQJK8SUj5vlKibv8_i42nwmxDUOFc&index=7 # make sure to install curses via terminal -> pip install windows-curses #to start the game use cmd or cmder access the folder and type either python snake.py or tree_electric_code.py import random import curses initlize = curses.initscr() curses.curs_set(0) screen_height,screen_width = initlize.getmaxyx() window = curses.newwin(screen_height,screen_width, 0, 0) window.keypad(1) #refresh every mili-second window.timeout(100) snake_xposition = screen_width/4 snake_yposition = screen_height/2 snake = [ #body part of the snake # diagram of the snake [][][] [snake_yposition, snake_xposition], [snake_yposition, snake_xposition-1], [snake_yposition, snake_xposition-2], ] food = [screen_height/2, screen_width/2] window.addch(int(food[0]), int(food[1]), curses.ACS_LANTERN) key = curses.KEY_RIGHT while True: next_key = window.getch() key = key if next_key == -1 else next_key if snake[0][0] in [0,screen_height] or snake[0][1] in [0, screen_width] or snake[0] in snake[1:]: import image image() quit() new_snake_head = [snake[0][0], snake[0][1]] if key == curses.KEY_DOWN: new_snake_head[0] += 1 if key == curses.KEY_UP: new_snake_head[0] -= 1 if key == curses.KEY_LEFT: new_snake_head[1] -= 1 if key == curses.KEY_RIGHT: new_snake_head[1] += 1 snake.insert(0,new_snake_head) if snake[0] == food: food = None while food is None: new_food = [ random.randint(1,screen_height-1), random.randint(1,screen_width-1) ] food = new_food if new_food not in snake else None window.addch(food[0],food[1], curses.ACS_LANTERN) else: tail = snake.pop() window.addch(int(tail[0]), int(tail[1]), ' ') window.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)
c248ed413449df5bc560032b5c240d74c7c7349e
turenc/workspace
/framework-learning/pythonWorkspace/chapter01-PythonBased/demo03.py
1,536
4.21875
4
# -*- coding: utf-8 -*- # @Author: gaopeng # @Date: 2017-01-16 15:40:59 # @Last Modified by: gaopeng # @Last Modified time: 2017-01-16 16:12:35 # dict้€š่ฟ‡key-valueๅฝขๅผๅญ˜ๅ‚จ๏ผŒไธ€ไธชkeyๅช่ƒฝๅฏนๅบ”ไธ€ไธชvalue๏ผŒๅฆ‚ๆžœๅคšๆฌกๅฏนไธ€ไธชkeyๆ”พๅ…ฅvalue๏ผŒๅŽ้ข็š„ๅ€ผไผšๆŠŠๅ‰้ข็š„่ฆ†็›–ๆމ d = {} d['Adam'] = 67 print d['Adam'] # ๅฆ‚ๆžœkeyไธๅญ˜ๅœจ๏ผŒdictไผšๆŠฅ้”™ # ่ฆ้ฟๅ…keyไธๅญ˜ๅœจ็š„้”™่ฏฏ๏ผŒไธ€ๆ˜ฏ้€š่ฟ‡inๅˆคๆ–ญkeyๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒไบŒๆ˜ฏ้€š่ฟ‡dictๆไพ›็š„getๆ–นๆณ•๏ผŒ่‹ฅไธๅญ˜ๅœจ๏ผŒๅฏไปฅ่ฟ”ๅ›žNone๏ผŒๆˆ–่€…่‡ชๅทฑๆŒ‡ๅฎš็š„value print('Thomas' in d) d.get('Thomas', -1) print (d.get('Thomas', -1)) # setๅ’Œdict็ฑปไผผ๏ผŒไนŸๆ˜ฏไธ€็ป„key็š„้›†ๅˆ๏ผŒไฝ†ไธๅญ˜ๅ‚จvalue๏ผŒ็”ฑไบŽkeyไธ่ƒฝ้‡ๅค๏ผŒๅ› ๆญคๅœจsetไธญๆฒกๆœ‰้‡ๅค็š„key # ่ฆๅˆ›ๅปบไธ€ไธชset๏ผŒ้œ€่ฆๆไพ›listไฝœไธบ่พ“ๅ…ฅ้›†ๅˆ s = set([1, 2, 3]) print s # ้€š่ฟ‡removeๆ–นๆณ•ๆฅๅˆ ้™คๆŒ‡ๅฎš็š„ๅ…ƒ็ด  # setๅฏไปฅๅšๆ•ฐๅญฆๆ„ไน‰ไธŠ็š„ไบค้›†ใ€ๅนถ้›†็ญ‰ๆ“ไฝœ s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) print (s1 & s2) print (s1 | s2) # setๅ’Œdictไธ€ๆ ท๏ผŒไธๅฏไปฅๆ”พๅ…ฅๅฏๅ˜ๅฏน่ฑก๏ผˆdictไธๅฏ็”จๅฏๅ˜ๅฏน่ฑกไฝœไธบkey๏ผ‰ # ๅฏนๅฏๅ˜ๅฏน่ฑก่ฟ›่กŒๆ“ไฝœ a = ['c', 'b', 'a'] a.sort() print a # ๅฏนไธๅฏๅ˜ๅฏน่ฑก่ฟ›่กŒๆ“ไฝœ str = 'abc' str1 = str.replace('a', 'A') print (str) # abc print (str1) # Abc # ๅฏนไบŽไธๅฏๅ˜ๅฏน่ฑกๆฅ่ฏด๏ผŒ่ฐƒ็”จๅฏน่ฑก่‡ช่บซ็š„ไปปๆ„ๆ–นๆณ•๏ผŒไนŸไธไผšๆ”นๅ˜ๅฏน่ฑก่‡ช่บซ็š„ๅ†…ๅฎน๏ผŒ็›ธๅ๏ผŒไผšๅˆ›ๅปบๆ–ฐ็š„ๅฏน่ฑกๅนถ่ฟ”ๅ›ž s1.add((1, 2, 3)) print s1 s1.add([1, 2, 3]) # ไผšๆŠฅ้”™ print s1
e85c48a6db20da76f06816dc5f289507c592eb33
SunmoonHans/boj
/other/2523.py
137
3.703125
4
n = int(input()) + 1 for i in range(1, n): print('*' * i) line = list(range(1, n-1)) line.reverse() for i in line: print('*' * i)
c8771071fe4d2e8b193f9efbaa492935397313b7
benitez96/unsam
/unsam/Clase 11/burbujeo.py
931
3.78125
4
def ord_burbujeo(lista, debug=False): n = len(lista)-1 if debug: print('{:^10s} - {:^20s}'.format('N', 'LISTA')) comparaciones = 0 while n: if debug: print(f'{n:^10} - {lista}') for i in range(n): comparaciones += 1 if lista[i] > lista[i+1]: lista[i], lista[i+1] = lista[i+1], lista[i] n -= 1 return comparaciones lista_1 = [1, 2, -3, 8, 1, 5] lista_2 = [1, 2, 3, 4, 5] lista_3 = [0, 9, 3, 8, 5, 3, 2, 4] lista_4 = [10, 8, 6, 2, -2, -5] lista_5 = [2, 5, 1, 0] ''' El algoritmo es de complejidad cuadratica O(N^2) en el mejor o peor de los casos puesto que independientemente de si la lista esta ordenada o no, se realiza siempre el mismo nro de comparaciones ya que cada vuelta solo asegura que el ultimo elemento analizado se encuentra ordenado '''
0bf54fbbcce521b5b63661c117f8e469c65f0d40
minh1061998/D-ng-Quang-Minh-python-c4e27
/homework/Bai1b.py
2,034
4.03125
4
# sheep =[5, 7, 300, 90, 24, 50, 75] # print ("My name is Minh and these are my sheeps sizes: ",sheep) # maxweight = max(sheep) # print ("Now my biggest sheep has size ",maxweight ,"let's shear it") # index = sheep.index(maxweight) # sheep.insert(index, 8) # sheep.remove(maxweight) # print("After shearing, here is my flock: ",sheep) # sheep = [x+50 for x in sheep] # print("One month hass passed, now here is my flock: ", sheep) # ----------------------------------------------------------------------------- # sheep =[5, 7, 300, 90, 24, 50, 75] # print ("My name is Minh and these are my sheeps sizes: ",sheep) # for i in range (1,4): # sheep = [x+50 for x in sheep] # print('MONTH',i) # print("One month hass passed, here is my flock: ", sheep) # maxweight = max(sheep) # print("Now my biggest sheep has sized",maxweight,"let shear it") # index = sheep.index(maxweight) # sheep.insert(index, 8) # sheep.remove(maxweight) # print("After shearing, here is my flock: ",sheep) # ----------------------------------------------------------------------- sheep =[5, 7, 300, 90, 24, 50, 75] print ("My name is Minh and these are my sheeps sizes: ",sheep) maxweight = max(sheep) print ("Now my biggest sheep has size ",maxweight ,"let's shear it") index = sheep.index(maxweight) sheep.insert(index, 8) sheep.remove(maxweight) print("After shearing, here is my flock: ",sheep) for i in range (1,3): sheep = [x+50 for x in sheep] print('MONTH:',i) print("One month hass passed, here is my flock: ", sheep) maxweight = max(sheep) print("Now my biggest sheep has sized",maxweight,"let shear it") index = sheep.index(maxweight) sheep.insert(index, 8) sheep.remove(maxweight) print("After shearing, here is my flock: ",sheep) sheep=[x+50 for x in sheep] print("MONTH 3: ") print("One month hass passed, now here is my flock: ",sheep) print("My flock has sized in total: ",sum(sheep)) money = sum(sheep) * 2 print("i would get",sum(sheep),"*2$ = ",money,"$")
9e5627b5a51cbfe6c7771a6b57284d2cf2defbe0
magnoazneto/IFPI_Algoritmos
/Fabio03_For_com_for/Fabio03_01_inteiros.py
193
3.578125
4
from get_inputs import get_inteiro def main(): valor = get_inteiro('Por favor, digite um nรบmero inteiro: ') for i in range(1, valor+1): print(i, end = ' ') print() main()
b4243d69853a454b335d3a669a73f8acede55338
jtlai0921/XB1828-
/XB1828_Python้›ถๅŸบ็คŽๆœ€ๅผทๅ…ฅ้–€ไน‹่ทฏ-็Ž‹่€…ๆญธไพ†_็ฏ„ไพ‹ๆช”ๆกˆNew/ch18/ch18_18.py
1,060
3.5625
4
# ch18_18.py from tkinter import * def printInfo(): # ๅˆ—ๅฐ่ผธๅ…ฅ่ณ‡่จŠ print("Account: %s\nPassword: %s" % (e1.get(),e2.get())) window = Tk() window.title("ch18_18") # ่ฆ–็ช—ๆจ™้กŒ lab1 = Label(window,text="Account ").grid(row=0) lab2 = Label(window,text="Password").grid(row=1) e1 = Entry(window) # ๆ–‡ๅญ—ๆ–นๅกŠ1 e2 = Entry(window,show='*') # ๆ–‡ๅญ—ๆ–นๅกŠ2 e1.insert(1,"Kevin") # ้ ่จญๆ–‡ๅญ—ๆ–นๅกŠ1ๅ…งๅฎน e2.insert(1,"pwd") # ้ ่จญๆ–‡ๅญ—ๆ–นๅกŠ2ๅ…งๅฎน e1.grid(row=0,column=1) # ๅฎšไฝๆ–‡ๅญ—ๆ–นๅกŠ1 e2.grid(row=1,column=1) # ๅฎšไฝๆ–‡ๅญ—ๆ–นๅกŠ2 btn1 = Button(window,text="Print",command=printInfo) # sticky=Wๅฏไปฅ่จญๅฎš็‰ฉไปถ่ˆ‡ไธŠ้ข็š„Labelๅˆ‡้ฝŠ, pady่จญๅฎšไธŠไธ‹้–“่ทๆ˜ฏ10 btn1.grid(row=2,column=0,sticky=W,pady=10) btn2 = Button(window,text="Quit",command=window.quit) # sticky=Wๅฏไปฅ่จญๅฎš็‰ฉไปถ่ˆ‡ไธŠ้ข็š„Entryๅˆ‡้ฝŠ, pady่จญๅฎšไธŠไธ‹้–“่ทๆ˜ฏ10 btn2.grid(row=2,column=1,sticky=W,pady=10) window.mainloop()
5573b308910b6e131d07d99c31a01d2877a3cf2d
nmomaya/Python_Assignment
/tietactoe.py
549
3.78125
4
""" board = { "TopL" : ' ', 'TopM' :' ',"TopR":' ', "ML" : ' ', 'MM':' ', "MR":' ', "BL" : ' ', 'BM':' ',"BR":' ' } print(board) """ def displayInventory(inventory): import pprint print("Inventory:") item_total = 0 for k, v in inventory.items(): item_total = item_total + v print(v,' ',k.upper()) print("Total number of items: " + str(item_total)) stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} import pprint pprint.pprint(stuff) displayInventory(stuff)
73b2b4e18bf60a4a17ff7d606d77cb4f881ea93e
Jane2353/AlgoritmeAflevering
/Sort with random numbers.py
578
4.5
4
# Python program to find the largest number in the list # The list is empty in the beginning list = [] # It asks how many many numbers you want in the list number = int(input("Hvor mange tal vil du have i din liste? ")) # It will keep asking until you have the amount of numbers you want, # then it will sort them to see which is the largest for i in range(1, number + 1): tal = int(input("Indsรฆt tal: ")) list.append(tal) # It tells which is the largest number # from the list by looking at the append list print("Det hรธjeste tal er:", max (list))
86220ff5dcdbc281f29edd2981752a19b83cf115
PoolloverNathan/rotate-screen
/invscr.py
566
3.640625
4
#!/usr/bin/env python3 # Simple script that inverts the computer's screen(s). # Or rather, it gets the screen(s) into inverted mode, i.e. executing # the script twice won't get the screen(s) back to normal. import subprocess def invscr(): # Get screens get = subprocess.check_output(["xrandr"]).decode("utf-8").split() screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"] # Invert them for scr in screens: subprocess.call(["xrandr", "--output", scr, "--rotate", "inverted"]) if __name__ == "__main__": invscr()
a0586c8045992bf5083cbff4f926506234cb3dbc
awanishgit/python-course
/conditional.py
1,453
4.46875
4
# If/ Else conditions are used to decide to do something based on something being true or false x = 40 y = 40 # Comparison operators (==, !=, >, <, >=, <=) - Use to compare values # Simple if if x == y: print(f'{x} is equal to {y}') # Simple If/ else if x > y: print (f'{x} is greater than {y}') else: print(f'{x} is less than {y}') # Else If if x > y: print (f'{x} is greater than {y}') elif x == y: print(f'{x} is equal to {y}') else: print(f'{x} is less than {y}') # Nested If if x > 2: if x <= 10: print(f'{x} is greater than 2 and less than or equal to 10') # Logical operator (and, or, not) - Used to combine conditional statement # and operator if x > 2 and x <= 10: print(f'{x} is greater than 2 and less than or equal to 10') # or operator if x > 2 or x <= 10: print(f'{x} is greater than 2 or less than 10') # not operator if not x == y: print(f'{x} is not equal to {y}') # Membership Operators (not, not in) - Membership Operators are used to test if a # sequence is presented in an object number = [1, 2, 3, 4, 5] # in operator if x in number: print(x in number) if x not in number: print(x not in number) # Identity Operators (is, is not) - Compare the object, not if they are equal, but # if they are actually the same object, with the same memory location # is operator if x is y: print(x is y) # is not operator if x is not y: print(x is not y)
ee910c1aca41df4de640a28ab88b09d972e09747
gokou00/python_programming_challenges
/leetcode/searchRange.py
299
3.53125
4
def searchRange(nums,target): if target not in nums: return[-1,-1] idx1 = nums.index(target) if target not in nums[idx1+1:]: return[idx,-1] idx2 = nums[::-1].index(target) return[idx1,(len(nums) -1) - idx2] print(searchRange([5,7,7,8,8,10],6))
98a1ad766c163f486e79cbbc61117b9ad317747a
hvncodes/Dojo_Assignments
/Python/fundamentals/oop/bank/bankaccount.py
1,960
4
4
class BankAccount: # class attribute bank_name = "First National Dojo" all_accounts = [] def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance BankAccount.all_accounts.append(self) # class method to change the name of the bank @classmethod def change_bank_name(cls,name): cls.bank_name = name # class method to get balance of all accounts @classmethod def all_balances(cls): sum = 0 # we use cls to refer to the class for account in cls.all_accounts: sum += account.balance return sum def deposit(self, amount): self.balance += amount return self def withdraw(self,amount): # we can use the static method here to evaluate # if we can with draw the funds without going negative if BankAccount.can_withdraw(self.balance,amount): self.balance -= amount else: print("Insufficient funds: Charging a $5 fee") self.balance -= 5 return self def display_account_info(self): print(f"Balance: ${self.balance}") return self def yield_interest(self): if self.balance > 0: self.balance *= (1+self.int_rate) return self def printAccInfo(self): print(f"Current Balance: {self.balance}, Current Interest Rate: {self.int_rate}") # static methods have no access to any attribute # only to what is passed into it @staticmethod def can_withdraw(balance,amount): if (balance - amount) < 0: return False else: return True acc1=BankAccount(0.01,1000) acc2=BankAccount(0.021,9000) acc1.deposit(100).deposit(100).deposit(100).withdraw(50).yield_interest().display_account_info() acc2.deposit(100).deposit(100).withdraw(1500).withdraw(1500).withdraw(1500).withdraw(1500).yield_interest().display_account_info() acc2.printAccInfo()
ce65e99629c14369889a3862f43c8d1de2f97bff
jeff-a-holland/python_class_2020_B3
/exercise_13/solution.py
2,505
4.09375
4
#!/Users/jeff/.pyenv/shims/python from queue import PriorityQueue from threading import Thread import time import random import sys def main(): """Main functin for Threadify solution""" def add(q, x, y, tuple): """Add function. Simply return the sumer of values in a tuple passed as the argument.""" sum = 0 start = time.time() for value in tuple: sum += value time.sleep(random.randint(1, 7)) stop = time.time() elapsed = stop - start print(f' Time spent in add function for Thread-{y} with ' f'priority {y}: {elapsed}') # Put sum of tuple in proper index position based on queue priority # value passed in from threadify function (which is the argument 'x') print(f' Putting sum value {sum} in index {x} of result_list for ' f'Thread-{y}\n --') result_list[x] = sum sum = 0 q.task_done() def threadify(func, input_list): """Threadify function. Calls the add function x times, where is the cardinality of the number of tuples in the list passed as the second argument (the function to call being the first argument). Threadify will run the add computations in parallel using a PriorityQueue.""" q = PriorityQueue() for index, value in enumerate(input_list, start=1): q.put((index, value)) print('\nPriorityQueue for list of tuples is as follows:') for item in q.queue: print(f' {item}') print(' ------------') for x in range(num_tuples): y = x + 1 tuple_str = q.get() tuple_str = tuple_str[1] tuple_str = tuple_str[1:] tuple_str = tuple_str[:-1] tuple_val = tuple(map(int, tuple_str.split(','))) worker = Thread(target=add, name=y, args=(q, x, y, tuple_val,)) worker.setDaemon(True) worker.start() q.join() return result_list argv_list = sys.argv func = argv_list[1] input_list = argv_list[2] input_list = input_list[1:] input_list = input_list[:-1] input_list = input_list.split(', ') num_tuples = len(input_list) # Set result_list to proper size based on number of threads result_list = [0] * num_tuples output = threadify(func, input_list) print(f'Sum of each tuple from argument list is: {output}') if __name__ == "__main__": main()
e4450f9468766e742cebef6289ee92cede4ab92b
copland/python_algorithms
/trees/binary_heap.py
791
3.65625
4
class BinaryHeap: def __init__(self): self.heapList = [0] self.currentSize = 0 def insert(self, obj): self.heapList.append(obj) self.currentSize = self.currentSize + 1; self.percUp(self.currentSize) def findMin(self): return self.heapList[1] def delMin(self): print "Unimplemented" # TODO fill in def isEmpty(self): isEmpty = True if self.currentSize > 0: isEmpty = False return isEmpty def size(self): return self.currentSize def buildHeap(self, list): print "Unimplemented" # TODO fill in def percUp(self, i): while i // 2 > 0: parentIndex = i // 2 if self.heapList[i] < self.heapList[parentIndex]: temp = self.heapList[parentIndex] self.heapList[parentIndex] = self.heapList[i] self.heapList[i] = temp i = parentIndex
51c60d08bb50eb4b822b989bc0c44f2640636086
MP076/Python_Practicals_02
/11_While/40_counting.py
846
4.34375
4
# WHILE LOOP --- # A while loop will repeatedly execute a single statement or group of statements # as long as the condition being checked is true. # 197 current_number = 1 while current_number <= 5: print(current_number) current_number += 1 # 198 # x = 0 # # while x < 3: # print('X is currently', x) # print("Adding 1 to x") # x += 1 # alternatively you could write x = x + 1 # Cautionary Note! # Be careful with while loops! There is a potential to write a condition that always remains True, # meaning you have an infinite running while loop. If this happens to you, try using Ctrl+C to kill the loop. # Avoiding Infinite Loops -- # 199 # x = 1 # while x <= 5: # print(x) # O/p: # 1 # 2 # 3 # 4 # 5 # # X is currently 0 # Adding 1 to x # X is currently 1 # Adding 1 to x # X is currently 2 # Adding 1 to x
224ba62ca4df8b3328c71c078471660d04326bd6
dharmesh99s/college
/python/python_practicle/39_INPUT_statment_integer_from_keyboard.py
198
4.0625
4
no1=input("enter a number 1:") no2=input("enter a number 2:") no3=input("enter a number 3:") print("you entered a no1 as:",no1) print("you entered a no2 as:",no2) print("you entered a no3 as:",no3)
521d0b2de44a0bdd8a3aaf03a14fbc2fa7559ba7
gabriellaec/desoft-analise-exercicios
/backup/user_108/ch139_2020_04_01_19_16_15_539700.py
232
3.53125
4
def arcotangente(x,n): sinal = -1 soma = x lista = list(range(3,(3+(n-1)*2)+1,2)) print(n,lista) for i in range(3,(3+(n-1)*2)+1,2): soma += (x**i/i) * sinal sinal = -sinal return soma
765990d1d63e1b1559a2b47f218d82d8c45237bd
anamhayat/dsa_prog
/dsap_toolbox/prog_dir/bconcepts_exps/DFS_easy.py
644
3.90625
4
# graph using dictionaries ''' pseudocode DFS init graph // stack is being used implicitly init visited DFS(s): s.append(visited) for w in neigbours(s): if w not in visited: DFS(w) return ''' G = {"1": ["2", "3", "4"], "2": ["1", "3"], "3": ["1", "2", "4", "5"], "4": ["1", "3", "5"], "5": ["3", "4", "6", "7"], "6": ["5"], "7": ["5"]} visited = [] def DFS(s): visited.append(s) print('F', end= ' ') for w in G[s]: if w not in visited: DFS(w) print('B', end= ' ') return # driver start = input("Enter starting node: ") DFS(start) print("\n",visited)
5c3e0db7af2ffae626666a549f4e6ee040d6b45b
hemapriyadharshini/Text-Summarizer
/summarize.py
3,111
3.625
4
import bs4 as bs #Beautifulsoup package import urllib.request #Fetch url import nltk #Natural Language tool kit import re #Regular Expression scraped_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/Machine_learning') #scrap data from web url article = scraped_data.read() #Read scraped data parsed_article = bs.BeautifulSoup(article,'lxml') #Parse scraped data paragraphs = parsed_article.find_all('p') # Use find_all function of the Beautiful Soup object to fetch all contents from the paragraph tags of the article article_text = "" for p in paragraphs: article_text += p.text #Append all paragraph contents #Pre-process text #article_text = re.sub(r'[[0-9]*\]', ' ', article_text) # Substitute numbers, Square Brackets and Extra Spaces with a space article_text = re.sub(r'[*[0-9]*]', ' ', article_text) formatted_article_text = re.sub('[^a-zA-Z]', ' ', article_text) # Removing anything (like special characters and numbers) other than alphabets #formatted_article_text = re.sub(r's+', ' ', formatted_article_text) sentence_list = nltk.sent_tokenize(article_text) #mark the beginning and end of sentence #Calculate word scores stopwords = nltk.corpus.stopwords.words('english') #Remove words like is, at, the, etc., word_frequencies = {} for word in nltk.word_tokenize(formatted_article_text): #If the word is tokenized if word not in stopwords: #and not in stopwords if word not in word_frequencies.keys(): #and not part of word frequencies dictionary word_frequencies[word] = 1 #then assign the bag of words value as 1 else: word_frequencies[word] += 1 #else add 1 to the existing value maximum_frequncy = max(word_frequencies.values()) for word in word_frequencies.keys(): word_frequencies[word] = (word_frequencies[word]/maximum_frequncy) #TF-IDF formula to obtain weighted word frequency i.e., frequency of the most occuring word #Calculate sentence scores sentence_scores = {} for sent in sentence_list: #mark the beginning and end of sentence for word in nltk.word_tokenize(sent.lower()): #Tokenize all the words in a sentence if word in word_frequencies.keys(): #If the word exists in word_frequences if len(sent.split(' ')) < 30: #if the length of sentences is less than 30 if sent not in sentence_scores.keys():#If the sentence is not occuring frequently in the over all article sentence_scores[sent] = word_frequencies[word] #then add word frequency to sentence score else: sentence_scores[sent] += word_frequencies[word]#else add 1 to the existing value #Print Summary: import heapq #priority queue algorithm to sort sentences with top n largest score summary_sentences = heapq.nlargest(7, sentence_scores, key=sentence_scores.get) #Get sentence score; sort sentences based on the sentence score. Please note to count sentences ending with . and not the no of lines reading the output summary = ' '.join(summary_sentences) #Join sentences in a paragraph format to present as a summary print(summary) #print summary as output
dff70c7f3eb2e9abb66461decf35f575822496ec
wesleyramalho/fatec-exercises
/Exemplos/hello.py
263
3.578125
4
print('Inรญcio do Programa') import random arq = open('NUMEROS.txt', 'w') for i in range(1,2001): n = random.randint(1,100000) arq.write("{}\n".format(n)) arq.close() print("{} gravados no arquivo NUMEROS.txt!".format(i)) print('Fim do Programa')
e558c1e75284ce9d96da90fe343fe3f66bb64e00
aindrila2412/DSA-1
/Queue/queue.py
779
3.90625
4
class Queue: def __init__(self): self.q = [] def is_empty(self): return len(self.q) == 0 def enqueue(self, elm): self.q.append(elm) def dequeue(self): if self.is_empty(): raise Exception("Queue is empty.") return self.q.pop(0) def top(self): if self.is_empty(): return None return self.q[0] def size(self): return len(self.q) def print_queue(self): return self.q def test(): a = Queue() a.enqueue(10) a.enqueue(-12) assert a.print_queue() == [10, -12], "Test case 1 failed." assert a.top() == 10, "Test case 2 failed." a.dequeue() assert a.top() == -12, "Test case 3 failed." if __name__ == "__main__": test()
246efad54c515720d6435a057eb62c8abdcb2e6b
d8aninja/persCode
/pythonCookBook/sequences.py
904
3.6875
4
# for hashable types def dedupeHash(items): seen = set() for item in items: if item not in seen: yield item # generator = general purpose! seen.add(item) l = [1,2,3,3,4,3,2,2,2,1,1,1,1] dGen = dedupeHash(l) list(dGen) #dGen gets used up! # for unhashable type (like dicts/maps) def dedupeUnhash(items, key=None): seen = set() for item in items: # key: specify a function that converts sequence items # into a hashable type val = item if key is None else key(item) if val not in seen: yield item seen.add(val) a = [ # all unhasable dicts... {'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, # dupe {'x': 2, 'y': 4} ] # dedupe on unique pairs of keys list(dedupeUnhash(a, key = lambda d: (d['x'], d['y']))) # dedupe on unique key x list(dedupeUnhash(a, key = lambda d: (d['x'])))
f44a8f3432e664cf37ea69d407a3f49ef8c5f0b9
aaaaasize/algorithm
/func/6_random.py
898
4.125
4
# 6. ะ’ ะฟั€ะพะณั€ะฐะผะผะต ะณะตะฝะตั€ะธั€ัƒะตั‚ัั ัะปัƒั‡ะฐะนะฝะพะต ั†ะตะปะพะต ั‡ะธัะปะพ ะพั‚ 0 ะดะพ 100. # ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะดะพะปะถะตะฝ ะตะณะพ ะพั‚ะณะฐะดะฐั‚ัŒ ะฝะต ะฑะพะปะตะต ั‡ะตะผ ะทะฐ 10 ะฟะพะฟั‹ั‚ะพะบ. # ะŸะพัะปะต ะบะฐะถะดะพะน ะฝะตัƒะดะฐั‡ะฝะพะน ะฟะพะฟั‹ั‚ะบะธ ะดะพะปะถะฝะพ ัะพะพะฑั‰ะฐั‚ัŒัั, ะฑะพะปัŒัˆะต ะธะปะธ ะผะตะฝัŒัˆะต ะฒะฒะตะดะตะฝะฝะพะต ั‡ะธัะปะพ, ั‡ะตะผ ั‚ะพ, ั‡ั‚ะพ ะทะฐะณะฐะดะฐะฝะพ. # ะ•ัะปะธ ะทะฐ 10 ะฟะพะฟั‹ั‚ะพะบ ั‡ะธัะปะพ ะฝะต ะพั‚ะณะฐะดะฐะฝะพ, ะฒั‹ะฒะตัั‚ะธ ะพั‚ะฒะตั‚. import random result = random.randint(1, 100) step = 0 while True: step += 1 number = int(input('ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ: ')) if step == 10: print('ะ’ั‹ ะฟั€ะพะธะณั€ะฐะปะธ') break elif number == result: print('ะ’ั‹ ะฒั‹ะธะณั€ะฐะปะธ') break else: print('ะ‘ะพะปัŒัˆะต' if number < result else 'ะœะตะฝัŒัˆะต') print(result)
d5d0ee1ab5e339613a93777a53935b747d02329d
ogianatiempo/natasWriteups
/utils.py
479
3.578125
4
def read_passwords(file): """ Esta funcion crea un diccionario con las credenciales de cada nivel a partir de un archivo. Ver el archivo modelo natas_passwords_sample. """ credentials = {} for line in open(file, 'r'): line = ''.join(line.split()) data = [element.replace('\n', '') for element in line.split(':')] data = [''.join(element.split()) for element in data] credentials[data[0]] = data[1] return credentials
49ab25716b6c7dc7d8ba0ed3d8145860812c7ae8
darshan-gandhi/Hackkerank
/diagonal diff.py
807
3.578125
4
def diagonalDifference(arr): sum1 = 0 # sum2 = 0 save = [] for i in range(n): for j in range(n): if int(arr[i][j])>=-100 and int(arr[i][j])<=100: if i == j: sum1 = sum1 + int(arr[i][j]) # print(f"the sum is {sum1}") save.append(sum1) # sum2=sum2+int(mat[0][2])+int(mat[1][1])+int(mat[2][0]) # # print(sum2) # save.append(sum2) sum2 = 0 for i in range(n): if int(arr[i][j]) >= -100 and int(arr[i][j] )<= 100: sum2 = sum2 + int(arr[i][n - 1 - i]) # print(sum2) save.append(sum2) diff = 0 diff = abs(int(save[0]) - int(save[1])) print(diff) n=int(input()) arr=[] for i in range(n): row=input().split() arr.append(row) # print(mat) diagonalDifference(arr)
4281558a1f79d3488ca41b6efc5153b3c13b7744
LIMMIHEE/python_afterschool
/Code05-12.py
318
3.984375
4
answer = 0 num1 = int(input("์ฒซ ๋ฒˆ์งธ ์ˆซ์ž ์ž…๋ ฅํ•˜์„ธ์š” : " )) num2 = int(input("๋‘ ๋ฒˆ์งธ ์ˆซ์ž ์ž…๋ ฅํ•˜์„ธ์š” : " )) num3 = int(input("๋”ํ•  ์ˆซ์ž ์ž…๋ ฅํ•˜์„ธ์š” : " )) for i in range(num1,num2+1,num3): answer = answer+i print(num1,"+",(num1+num3),"...+",num2,"๋Š” ",answer,"์ž…๋‹ˆ๋‹ค")
3a99e48a0144551f92a9f39ff7bef30358ff0f2a
LP13972330215/algorithm010
/Week01/็ˆฌๆฅผๆขฏ.py
763
3.984375
4
import functools class Solution: """ ่งฃ้ข˜ๆ–นๆณ•๏ผš1ใ€ๅˆฉ็”จF(n) = F(n-1) +F(n-2)้€’ๅฝ’๏ผŒๆ—ถ้—ดๅคๆ‚ๅบฆO(n^2)ใ€‚้€’ๅฝ’ 2ใ€ๅœจ1็š„ๅŸบ็ก€ไธŠ๏ผŒๅฐ†่ฎก็ฎ—่ฟ‡็š„็ผ“ๅญ˜ไธ‹ๆฅ๏ผŒไธ‹ๆฌก็ขฐๅˆฐๅฐฑไธๅœจ่ฎก็ฎ—๏ผŒ็›ดๆŽฅไปŽ็ผ“ๅญ˜ไธญๆ‹ฟใ€‚้€’ๅฝ’+่ฎฐๅฟ†ๅŒ–ๆœ็ดขใ€‚ๆ—ถ้—ดๅคๆ‚ๅบฆO(n),็ฉบ้—ดๅคๆ‚ๅบฆO(n) 3ใ€ๅŠจๆ€่ง„ๅˆ’๏ผŒๆ—ข้€’ๆŽจใ€‚ๅŽ้ข็š„ๅฐ†ๅ‰ไธ€ไธช่ฆ†็›–ใ€‚ๆ—ถ้—ดๅคๆ‚ๅบฆO(n)ใ€็ฉบ้—ดๅคๆ‚ๅบฆO(1) 4ใ€็Ÿฉ้˜ตๅฟซ้€Ÿๅน‚ๆˆ–้€šๅ‘ๅ…ฌๅผใ€‚ๆ—ถ้—ดๅคๆ‚ๅบฆO(logn) """ @functools.lru_cache(100) # ็ผ“ๅญ˜่ฃ…้ฅฐๅ™จ def climbStairs(self, n: int) -> int: if n == 1: return 1 if n == 2: return 2 return self.climbStairs(n-1) + self.climbStairs(n-2) a = 3 print(Solution().climbStairs(a))
27d3b605af7e21f1900447092d400f9760749e65
sjzyjc/leetcode
/272/272-0.py
2,002
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :type k: int :rtype: List[int] """ if not root: return [] self.sorted = [] self.inOrder(root) start, end = 0, len(self.sorted) - 1 firstLarge = self.findFirstLarge(target) counter = 0 ans = [] if firstLarge == 0: return self.sorted[: k] left, right = firstLarge - 1, firstLarge while counter < k: if left < 0 or right > len(self.sorted) - 1: break if abs(self.sorted[left] - target) <= abs(self.sorted[right] - target): ans.append(self.sorted[left]) left -= 1 else: ans.append(self.sorted[right]) right += 1 counter += 1 if counter < k: if left < 0: ans.extend(self.sorted[counter: k]) else: ans.extend(self.sorted[len(self.sorted) - k : len(self.sorted) - counter]) return ans def inOrder(self, root): if not root: return self.inOrder(root.left) self.sorted.append(root.val) self.inOrder(root.right) def findFirstLarge(self, target): start, end = 0, len(self.sorted) - 1 while start < end: mid = (start + end) // 2 if self.sorted[mid] == target: return mid elif self.sorted[mid] < target: start = mid + 1 else: end = mid return start
9c9f36803e5c72a87b24ffe4d77d66a8cfc78381
marcelofreire1988/python-para-zumbis-resolucao
/Lista 1/questรฃo07.py
227
4.1875
4
#Converta uma temperatura digitada em Celsius para Fahrenheit. F = 9*C/5 + 32 tempC = int(input("insira o valor da temperatura em Celsius: ")) tempF = tempC = 9*tempC/5 + 32 print 'a temperatura em Fahrenheit de: ' , tempF
4c0dafc8cd639210dbfe3c7b52d3fcdbc916f88f
DhineshPV/function.py
/digits.py
1,317
3.84375
4
#py1_sumofdigits num =int(input()) sum=0 while(num!=0): n=num%10 #o/p_15=6 sum=sum+n num=num//10 print(sum) #PY2_reverse num =int(input()) reverse=0 while(num>0): #o/p_1505=5051 n=num%10 reverse=(reverse*10)+n num=num//10 print(reverse) [OR] num=input(): n=num[::-1] print(n) #py3 palindrome or not num=input() n=num[::-1] if(n==num): #o/p:amma,amma is a palindrome;dhinesh,dhinesh is not palindrome print(num," is a palindrome") else: print(num," is not palindrome") #PY4 Amstrong number or not num=int(input()) sum=0 temp=num while(temp>0): d=temp%10 #O/P=135,135 is Amstrong number;134 is not Amstrong number sum+=d**3 temp=temp//10 if(num==sum): print(num," is a Amstrong number") else: print(num," is not Amstrong number") #amstrong between two interval num1=int(input()) num2=int(input()) for i in range(num1,num2+1): order = len(str(i)) sum=0 temp=i while(temp>0): d=temp%10 sum+=d**order temp=temp//10 if (i==sum): print (i) #BINARY TO DECIMAL t=int(input()) for _ in range(t): n=input() print(int(n,2))
056079a9294e9bdfa1180b564574718fdd5167dc
anshikatiwari11/PythonPractice
/assignment.py
2,320
4.375
4
# How to reverse the function w/o using builtin function: # a = "Hello World"[::-1] # print(a) # a = [1,2,3,4,5,6,7,8][::-1] # print(a) # How to append in a list in python w/o using append builtin function: # a = [1,2,3] # b = [4,5,6] # a[:0] = b # print(a) # How to insert in list in python w/o using insert builtin function: # a = [1,2,3] # b = [4,5,6] # a[1:0] = b # print(a) # How to extend list in the last in python w/o using extend builtin function: # a = [1,2,3] # b = ['x','y','z'] # a[3:0] = b # print(a) # How to sort in list in python without using sort builtin function # a = [5, 3, 7, 2, 8, 4] # print(a) # n = len(a) # for i in range(n): # for j in range(1, n-i): # if a[j-1] < a[j]: # (a[j-1], a[j]) = (a[j], a[j-1]) # print(a) a = ['b','c','a','d'] # print(a) # n = len(a) # for i in range(n): # for j in range(1, n-i): # if a[j-1] < a[j]: # (a[j-1], a[j]) = (a[j], a[j-1]) # print(a) # How to delete/clear in list in python without using sort builtin function # a = [1,2,3,4,5,6,7,8] # a= a[7:7] # print(a) # How to pop in list in python without using sort builtin function # a = [1,2,3,4,5,6,7,8] # a= a[0:7] or a= a[0:-1] # print(a) # How to copy in list in python without using sort builtin function # a = [1,2,3,4,5,6,7,8] # b = a # print(b) #fibnaci series # def fib(n): # a,b=0,1 # while a<n: # print(a,end=' ') # a,b = b, a+b # print() # fib(1000) # Making Shallow Copies: It creates a new object which stores the reference of the original elements. # So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. # This means, a copy process does not recurse or create copies of nested objects itself. # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # y = list(x) # print(x) # print(y) # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # xx = ['anshika'] # x[2:0] = xx # print(x) # print(y) # old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 'a']] # new_list = old_list # new_list[2][2] = 9 # print('Old List:', old_list) # print('ID of Old List:', id(old_list)) # print('New List:', new_list) # print('ID of New List:', id(new_list)) # Making Deep Copies: A deep copy creates a new object # and recursively adds the copies of nested objects present in the original elements.
49a40e58dd89d56f844e6f12d4c7b301f1ce6000
GophnaUrease/scripts
/fasta_utils.py
716
4.0625
4
''' utililties for reading and writing fasta files to / from a {header : sequence} dictionary ''' def read_file(filename): ''' read a fasta file, returns a {header : sequence} dictionary ''' sequence = {} with open(filename, 'r') as f: head = '' for line in f: if line[0] == '>': key = line sequence[key] = '' else: sequence[key] += line[:-1] return sequence def write_file(filename, sequence): ''' creates a fasta file with the name filename containing the sequences in the sequence dictionary ({header : sequence} format) ''' with open(filename, 'w') as f: for head in sequence: f.write(head) f.write(sequence[head] + '\n')
3e647d76b2c2dd6eeca7f5e61d460743ee249087
MistyLeo12/Learning
/Python/twopointerpractice.py
1,954
3.890625
4
class Node: def __init__(self, val, next = None): self.val = val self.next = next class LinkedList: def __init__(self): self.head = Node(None) self.size = 0 def get(self, index: int) -> int: if index >= self.size: return -1 node = self.head.next while index > 0: node = node.next index -= 1 print(node.val) return node.val def appendHead(self, val: int) -> None: newHead = Node(val) newHead.next = self.head.next self.head.next = newHead self.size += 1 def appendTail(self, val: int) -> None: index = self.size last = self.head.next while index > 1: last = last.next index -= 1 last.next = Node(val) self.size += 1 def addAtIndex(self, index: int, val: int) -> None: if index > self.size: return temp = Node(val) if index == 0 and self.size == 0: self.head.next = temp self.size += 1 return elif index == 0 and self.size == 1: temp.next = self.head.next self.head.next = temp self.size += 1 return node = self.head.next while index > 1: node = node.next index -= 1 temp.next = node.next node.next = temp self.size += 1 def deleteAtIndex(self, index: int) -> None: if index >= self.size: return if index == 0 and self.size <= 1: self.head.next = None self.size -= 1 return elif index == 0: self.head.next = self.head.next.next self.size -= 1 node = self.head.next while index > 1: node = node.next index -= 1 node.next = node.next.next self.size -= 1
779bc7be91a97ddadda28ef51d7f1ff3b0e181c2
zackfravel/Movie-Library-Graph-Generation-using-IMDb-and-Python
/Code/promptGUI.py
1,733
4
4
# Zack Fravel # ECE508 - Python Workshop # Spring 2021 # Final Project # # filename: promptGUI.py # # description: Implements a simple GUI to be used by the top level program # for taking in user information. Gives the user a directory selection dialogue # for the program to use as the media folder for generating a list of movies. # # library references: # https://docs.python.org/3/library/tk.html # # Import tkinter for GUI development import tkinter as tk from tkinter import filedialog from tkinter import * # Configure GUI promptRoot = tk.Tk() promptRoot.title('Zack Fravel - Python Workshop - Final Project') Label(promptRoot).pack() # Blank Spacer # Variable to store user's selected media folder selected_folder = StringVar() # Function called on each button click def ask_for_folder(): # Prompt user to select a directory selected_folder.set(filedialog.askdirectory()) pass # Function called on each generate graph click def collect_data(): folder = selected_folder.get() print("Collecting IMDb Data . . . ") # Print Selected Folder print("Folder: ", folder) # Quit GUI window after setting variables to make room for Graph GUI promptRoot.destroy() pass # Add Search Button, calls button_clicked() Button(promptRoot, text="Select Movies Directory", command=ask_for_folder).pack() Label(promptRoot).pack() # Blank Spacer # Add Path Field Entry(promptRoot, width=120, textvariable=selected_folder).pack() Label(promptRoot).pack() # Blank Spacer # Add Collect Button, calls button_clicked() Button(promptRoot, text="Collect IMDb Metadata", command=collect_data).pack() Label(promptRoot).pack() # Blank Spacer
2408c8e28b4bb315cac68c09a501602e50981abc
oxhead/CodingYourWay
/src/lt_41.py
2,233
3.640625
4
""" https://leetcode.com/problems/first-missing-positive Related: - lt_268_missing-number - lt_287_find-the-duplicate-number - lt_448_find-all-numbers-disappeared-in-an-array - lt_765_couples-holding-hands """ """ Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ # Time: O(n) # Space: O(1) # https://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html # https://github.com/algorhythms/LeetCode/blob/master/040%20First%20Missing%20Positive.py if not nums: return 1 i = 0 while i < len(nums): if nums[i] <= 0 or nums[i] > len(nums) or nums[nums[i] - 1] == nums[i]: i += 1 else: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] for i in range(len(nums)): if nums[i] != i + 1: return i + 1 return nums[-1] + 1 def firstMissingPositive_failed(self, nums): """ :type nums: List[int] :rtype: int """ default_n = 0 for n in nums: if n > 0: default_n = n break if default_n == 0: return 1 for i in range(len(nums)): if nums[i] < 0: nums[i] = default_n print(nums) for i in range(len(nums)): if nums[abs(nums[i]) - 1] > 0: nums[abs(nums[i]) - 1] *= -1 print('#', nums) for i in range(len(nums)): if nums[i] >= 0: return i + 1 return len(nums) + 1 if __name__ == '__main__': test_cases = [ ([2], 1), ([1, 2, 0], 3), ([3, 4, -1, 1], 2), ([1, 2, 1, 4], 3), ([1, 2, 3], 4), ([1, 2, 3, -1], 4), ] for test_case in test_cases: print('case:', test_case) output = Solution().firstMissingPositive(test_case[0]) print('output:', output) assert output == test_case[1]
3ab6cbf680fd1c4ec82760e7f7579fb5fac92938
Tech-at-DU/CS-1.0-Introduction-To-Programming
/T010-Dictionaries-and-Code-Quality/assets/T10-WhichSong.py
529
3.9375
4
# Which Song # Step 1: Add one song to each category in the following dictionary of playlists playlists = { 'gym' : ['Eye of the Tiger', 'POWER', 'Level Up'], 'study': ['White Noise', 'ChilledCow', 'Space Ambient'], 'bbq' : ['Before I Let Go', 'Summertime', 'Outstanding'] } # Step 2: We want to make a new playlist based on the gym playlist. Create a variable called running and assign it the value of the list stored in the gym key of the dictionary # Step 3: Use a for loop to print each song from the gym playlist
be6c793bf3a8ca3be2affdb32d05018df48c05eb
huangyisan/lab
/python/partialfunc.py
299
3.6875
4
from functools import partial # range(m,n) ไธบๅŽŸๅ‡ฝๆ•ฐ print(list(range(2,11))) # ๅฐ†rangeๅ‡ฝๆ•ฐไธญ็š„็ฌฌไธ€ไธชๆ•ฐๅญ—2ๅ†ป็ป“ par = partial(range, 2) # ่‡ณๆญคpar้€š่ฟ‡rangeๅ’Œ็ป™ๅฎš็š„ๅ‚ๆ•ฐ2ๆž„ๅปบไบ†ไธ€ไธชๆ–ฐ็š„ๅ‡ฝๆ•ฐ๏ผŒๅŠŸ่ƒฝไธบrange(2,x) # ่ฟ›่กŒๅ†…ๅฎน่พ“ๅ‡บ print(par(11)) print(list(par(11)))
7f61bd7b2fc81e84932b9d16dbbac6e1c6a64994
hellorobo/PyCode
/Udemy Python Mega Course/sqlite_operations.py
1,440
3.625
4
import sqlite3 def connect_database(database): return sqlite3.connect(database) def close_database(connection): connection.close() def create_table(connection, table, schema): cur = connection.cursor() cur.execute("CREATE TABLE IF NOT EXISTS " + table + " (" + schema + ")") connection.commit() def insert_data(connection, table, item, quantity, price): cur = connection.cursor() cur.execute("INSERT INTO " + table + " VALUES(?,?,?)", (item, quantity, price)) # using ? instead of %s to prevent sql injection connection.commit() def delete_item(connection, table, item): cur = connection.cursor() cur.execute("DELETE FROM " + table + " WHERE item=?", item) connection.commit() def update_item(connection, table, item, quantity, price): cur = connection.cursor() cur.execute("UPDATE " + table + " SET quantity=?, price=? WHERE item=?", (quantity, price, item)) connection.commit() def read_data(connection, table): cur = connection.cursor() cur.execute("SELECT * FROM " + table) return cur.fetchall() db = 'files\lite.db' table = 'vine_store' schema = 'item TEXT, quantity INTEGER, price REAL' conn = connect_database(db) create_table(conn, table, schema) insert_data(conn, table, 'Merlot', 1002, 4.99) insert_data(conn, table, 'Shiraz', 547, 7.99) insert_data(conn, table, 'Cabernet', 798, 6.99) print(read_data(conn, table)) close_database(conn)
0f9e88677be37d369dd39212c8aabe1e36e43880
MohamedAmeer/python-T2
/day8.py
2,438
4.25
4
# merge two dictionaries d1 = {'a': 1, 'b': 2} d2 = {'b': 1, 'c': 3} d1.update(d2) print(d1) # sort the list from des to ascen and convert list into set lst = ["xyz", "abc", "20", "16", "11"] print("list is:", lst) lst.sort() print("list in ascending order:", lst) set = set(lst) print("set is", set) # list number of items in a dictionary and sort the dictinary dict = { "a": 12, "b": 11, "c": 13, "d": 20 } print("no of items in a dictionary is:", len(dict.keys())) srt_dict = sorted(dict.items(), key=lambda x: x[1]) print(srt_dict) def sort_dict(): print("the sorted dict is:", sorted(dict.items(), key=lambda x: x[1])) sort_dict() # replace the first instance of word with a user given input str = "hello welcome" print("befor change the first word of string is:", str) my_str = input("enter a word:") a = str.replace("hello", my_str, 1) print("after changing the first word of string:", a) # capitalize the first char of given string s = "hi and welcome to my world" print(" ") print("the string before capitalize all first char:", s) q = s.title() print(" ") print("the string after capitalize all first char:", q) print(" ") # to find a repeated item in a list def Repeat(x): _size = len(x) repeated = [] for i in range(_size): k = i + 1 for j in range(k, _size): if x[i] == x[j] and x[i] not in repeated: repeated.append(x[i]) return repeated list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, 'a', 'a', 'abc'] print('the list is:', list) print("the repeated item in a list is:", Repeat(list)) x = input("Input the first number") y = input("Input the second number") z = input("Input the third number") print("Median of the above three numbers -") # find median if y < x and x < z: print(x) elif z < x and x < y: print(x) elif z < y and y < x: print(y) elif x < y and y < z: print(y) elif y < z and z < x: print(z) elif x < z and z < y: print(z) # swap case of given string az = "HeLLo HOw aRe YOu " print("string before swap case:", az) print("string after swap case:", az.swapcase()) # convert integer to binary def intToBinary(num): if num >= 1: intToBinary(num // 2) print(num % 2, end='') if __name__ == '__main__': int_val = 24 print(intToBinary(int_val))
f87e2f79cf0acb4841dc5053b38560b71467061b
Harshith-S/Python-4-Everybody
/ex_13/ex_13_03.py
288
3.953125
4
#Simple Python program using JSON2 import json data = '''[ { "name" : "Harshith", "id" : "485095" }, { "name" : "Geetha", "id" : "485381" } ]''' info = json.loads(data) print("Count : ",len(info)) for item in info: print("Name : ",item['name']) print("ID : ",item['id'])
4c4a69885dfe58ebb9fad1568c44bbfbda7cc5c3
m-mburu/data_camp
/python/extreme-gradient-boosting-with-xgboost/ex1.py
5,409
4.1875
4
""" XGBoost: Fit/Predict It's time to create your first XGBoost model! As Sergey showed you in the video, you can use the scikit-learn .fit() / .predict() paradigm that you are already familiar to build your XGBoost models, as the xgboost library has a scikit-learn compatible API! Here, you'll be working with churn data. This dataset contains imaginary data from a ride-sharing app with user behaviors over their first month of app usage in a set of imaginary cities as well as whether they used the service 5 months after sign-up. It has been pre-loaded for you into a DataFrame called churn_data - explore it in the Shell! Your goal is to use the first month's worth of data to predict whether the app's users will remain users of the service at the 5 month mark. This is a typical setup for a churn prediction problem. To do this, you'll split the data into training and test sets, fit a small xgboost model on the training set, and evaluate its performance on the test set by computing its accuracy. pandas and numpy have been imported as pd and np, and train_test_split has been imported from sklearn.model_selection. Additionally, the arrays for the features and the target have been created as X and y. """ # Import xgboost import xgboost as xgb # Create arrays for the features and the target: X, y X, y = churn_data.iloc[:,:-1], churn_data.iloc[:,-1] # Create the training and test sets X_train, X_test, y_train, y_test= train_test_split(X, y, test_size = .2, random_state=123) # Instantiate the XGBClassifier: xg_cl xg_cl = xgb.XGBClassifier(n_estimators = 10, objective= 'binary:logistic', seed=123) # Fit the classifier to the training set xg_cl.fit(X_train, y_train) # Predict the labels of the test set: preds preds = xg_cl.predict(X_test) # Compute the accuracy: accuracy accuracy = float(np.sum(preds==y_test))/y_test.shape[0] print("accuracy: %f" % (accuracy)) """ Decision trees Your task in this exercise is to make a simple decision tree using scikit-learn's DecisionTreeClassifier on the breast cancer dataset that comes pre-loaded with scikit-learn. This dataset contains numeric measurements of various dimensions of individual tumors (such as perimeter and texture) from breast biopsies and a single outcome value (the tumor is either malignant, or benign). We've preloaded the dataset of samples (measurements) into X and the target values per tumor into y. Now, you have to split the complete dataset into training and testing sets, and then train a DecisionTreeClassifier. You'll specify a parameter called max_depth. Many other parameters can be modified within this model, and you can check all of them out here. """ # Import the necessary modules from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier # Create the training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=123) # Instantiate the classifier: dt_clf_4 dt_clf_4 = DecisionTreeClassifier(max_depth = 4) # Fit the classifier to the training set dt_clf_4.fit(X_train, y_train) # Predict the labels of the test set: y_pred_4 y_pred_4 = dt_clf_4.predict(X_test) # Compute the accuracy of the predictions: accuracy accuracy = float(np.sum(y_pred_4==y_test))/y_test.shape[0] print("accuracy:", accuracy) """ Measuring accuracy You'll now practice using XGBoost's learning API through its baked in cross-validation capabilities. As Sergey discussed in the previous video, XGBoost gets its lauded performance and efficiency gains by utilizing its own optimized data structure for datasets called a DMatrix. In the previous exercise, the input datasets were converted into DMatrix data on the fly, but when you use the xgboost cv object, you have to first explicitly convert your data into a DMatrix. So, that's what you will do here before running cross-validation on churn_data. """ # Create arrays for the features and the target: X, y X, y = churn_data.iloc[:,:-1], churn_data.iloc[:,-1] # Create the DMatrix from X and y: churn_dmatrix churn_dmatrix =xgb.DMatrix(data= X, label= y) # Create the parameter dictionary: params params = {"objective":"reg:logistic", "max_depth":3} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain= churn_dmatrix, params=params, nfold= 3, num_boost_round= 5, metrics="error", as_pandas= True, seed=123) # Print cv_results print(cv_results) # Print the accuracy print(((1-cv_results["test-error-mean"]).iloc[-1])) """ Measuring AUC Now that you've used cross-validation to compute average out-of-sample accuracy (after converting from an error), it's very easy to compute any other metric you might be interested in. All you have to do is pass it (or a list of metrics) in as an argument to the metrics parameter of xgb.cv(). Your job in this exercise is to compute another common metric used in binary classification - the area under the curve ("auc"). As before, churn_data is available in your workspace, along with the DMatrix churn_dmatrix and parameter dictionary params. """ # Perform cross_validation: cv_results cv_results = xgb.cv(dtrain=churn_dmatrix, params=params, nfold=3, num_boost_round = 5, metrics="auc", as_pandas=True, seed=123) # Print cv_results print(cv_results) # Print the AUC print((cv_results["test-auc-mean"]).iloc[-1])
50a6ead38b8e3a1c6517fded6a1a3659715f98be
Priya2120/loop
/que 11.py
47
3.71875
4
ch=1 while ch<=5: print("#"*ch) ch=ch+1
beb5c9454fdcb992a702ccf636c54dd8ee3b581c
candyer/codechef
/October Challenge 2019/MSV/MSV.py
1,039
3.609375
4
# https://www.codechef.com/OCT19B/problems/MSV ##################### ##### subtask 1 ##### ##################### # def solve(n, array): # res = 0 # for i in range(n): # count = 0 # for j in range(i): # if array[j] % array[i] == 0: # count += 1 # res = max(res, count) # return res # if __name__ == '__main__': # t = int(raw_input()) # for _ in range(t): # n = int(raw_input()) # array = map(int, raw_input().split()) # print solve(n, array) ##################### ##### subtask 2 ##### ##################### from collections import defaultdict def divisor(n): res = [] for i in range(1, int(n**0.5) + 1): if n % i == 0: res.append(i) if i * i != n: res.append(n // i) return res def solve(arr): best = 0 d = defaultdict(int) for num in arr: best = max(best, d[num]) for div in divisor(num): d[div] += 1 return best if __name__ == '__main__': t = int(raw_input()) for _ in range(t): n = int(raw_input()) array = map(int, raw_input().split()) print solve(array)
6e8be00a5f6be2c2e604d83b15ffc879eeed5ee2
memomora/Tarea2
/E4_S4.py
3,949
4.25
4
''' Cree una funciรณn que se llame round_sum(num_a, num_b, num_c). La funciรณn round_sum recibe 3 nรบmeros enteros. Para cada uno de estos nรบmeros enteros, la funciรณn debe redondearlos a la decena mรกs cercana (ejemplo: si un nรบmero es 15, entonces se redondea a 20, pero si es 14, se redondea a 10) y luego debe sumar los nรบmeros redondeados y devolver el resultado. El programa debe utilizar funciones de responsabilidad รบnica por lo que debe modularizar su soluciรณn. ''' print("==============================================") print("= Ejercicio No. 4, Semana 4 =") print("= Por: =") print("= Guillermo Mora B. =") print("==============================================") print("") #Funcion para determinar si se digito un numero def verifica_si_es_numero(num_str): esta_bien = True for indice in (num_str): numero_cadena = indice if (numero_cadena != "0" and numero_cadena != "1" and numero_cadena != "2" and numero_cadena != "3" and numero_cadena != "4" and numero_cadena != "5" and numero_cadena != "6" and numero_cadena != "7" and numero_cadena != "8" and numero_cadena != "9"): if esta_bien == True: esta_bien = False return(esta_bien) #Funcion para solicitar los datos al usuario def solicita_datos(): print("==============================================") print("= Solicitud de datos =") print("==============================================") print("") numero_cadena = "" cantidad_veces = 3 #Este ciclo solicita los datos al usuario hasta que este digite "s" o "S" while cantidad_veces > 0 : dato = input("Digite un numero: ") verifica_numero = verifica_si_es_numero(dato) if verifica_numero: numero_cadena = numero_cadena + dato +"," #En esta variable se va formando la cadena de numeros cantidad_veces -= 1 else: print("Se deben digitar numeros") print("") return numero_cadena def convertir_numero(numero_str): numero_str = int(numero_str) return numero_str def determina_redondeo(numero_str): redondeo_superior = False unidades_del_numero = numero_str[len(numero_str)-1] unidades_del_numero = convertir_numero(unidades_del_numero) if unidades_del_numero >= 5: redondeo_superior = True return redondeo_superior #Funcion para procesar la cadena de numeros y obtener la suma de los redondeos def procesar_cadena(cadena): numero_cadena = "" sumar_redondeo = 0 for indice in range (len(cadena)): if cadena[indice] != ",": #cada numero esta separado por comas numero_cadena = numero_cadena + cadena[indice] #en esta variable se van formando los numeros a partir de la cadena else: numero_int = convertir_numero(numero_cadena) numero_sumar_restar = numero_cadena[len(numero_cadena) - 1] numero_sumar_restar = convertir_numero(numero_sumar_restar) redondeo_suerior = determina_redondeo(numero_cadena) if redondeo_suerior: numero_int = (numero_int - numero_sumar_restar) + 10 sumar_redondeo = sumar_redondeo + numero_int numero_cadena = "" else: numero_int = numero_int - numero_sumar_restar sumar_redondeo = sumar_redondeo + numero_int numero_cadena = "" return sumar_redondeo #Cuerpo del programa salir = "" #Variable para controlar el ciclo de reproduccion del programa while salir != "s" and salir != "S": cadena_numeros = solicita_datos() #se forma la cadena de numeros resultado_suma = procesar_cadena(cadena_numeros) print("La suma de los redondeos de los numeros es {}.".format(resultado_suma)) print("") salir = input("Digite <ENTER> para continuar o (S)alir) ")
343f80901d29cffb561627dcbc6d12bb929e3384
TEAMLAB-Lecture/text-processing-kjy93217
/text_processing.py
3,530
3.546875
4
####################### # Test Processing I # ####################### """ NLP์—์„œ ํ”ํžˆํ•˜๋Š” ์ „์ฒ˜๋ฆฌ๋Š” ์†Œ๋ฌธ์ž ๋ณ€ํ™˜, ์•ž๋’ค ํ•„์š”์—†๋Š” ๋„์–ด์“ฐ๊ธฐ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋“ฑ์˜ ํ…์ŠคํŠธ ์ •๊ทœํ™” (text normalization)์ž…๋‹ˆ๋‹ค. ์ด๋ฒˆ ์ˆ™์ œ์—์„œ๋Š” ํ…์ŠคํŠธ ์ฒ˜๋ฆฌ ๋ฐฉ๋ฒ•์„ ํŒŒ์ด์ฌ์œผ๋กœ ๋ฐฐ์›Œ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. """ def normalize(input_string): """ ์ธํ’‹์œผ๋กœ ๋ฐ›๋Š” ์ŠคํŠธ๋ง์—์„œ ์ •๊ทœํ™”๋œ ์ŠคํŠธ๋ง์„ ๋ฐ˜ํ™˜ํ•จ ์•„๋ž˜์˜ ์š”๊ฑด๋“ค์„ ์ถฉ์กฑ์‹œ์ผœ์•ผํ•จ * ๋ชจ๋“  ๋‹จ์–ด๋“ค์€ ์†Œ๋ฌธ์ž๋กœ ๋˜์–ด์•ผํ•จ * ๋„์–ด์“ฐ๊ธฐ๋Š” ํ•œ์นธ์œผ๋กœ ๋˜์–ด์•ผํ•จ * ์•ž๋’ค ํ•„์š”์—†๋Š” ๋„์–ด์“ฐ๊ธฐ๋Š” ์ œ๊ฑฐํ•ด์•ผํ•จ Parameters: input_string (string): ์˜์–ด๋กœ ๋œ ๋Œ€๋ฌธ์ž, ์†Œ๋ฌธ์ž, ๋„์–ด์“ฐ๊ธฐ, ๋ฌธ์žฅ๋ถ€ํ˜ธ, ์ˆซ์ž๋กœ ์ด๋ฃจ์–ด์ง„ string ex - "This is an example.", " EXTRA SPACE " Returns: normalized_string (string): ์œ„ ์š”๊ฑด์„ ์ถฉ์กฑ์‹œํ‚จ ์ •๊ทœํšŒ๋œ string ex - 'this is an example.' Examples: >>> import text_processing as tp >>> input_string1 = "This is an example." >>> tp.normalize(input_string1) 'this is an example.' >>> input_string2 = " EXTRA SPACE " >>> tp.normalize(input_string2) 'extra space' """ # ๋ชจ๋“  ๋‹จ์–ด๋Š” ์†Œ๋ฌธ์ž๋กœ ๋ณ€ํ™˜ small_string = input_string.lower() # ์‹œํ€€์Šค ์ˆœ๋ฐฉํ–ฅ์œผ๋กœ ์ฒดํฌํ•˜๋ฉฐ ๊ฐ€์žฅ ์•ž ๊ณต๋ฐฑ ์ œ๊ฑฐ forward_check = [] flag = False for i in small_string: if i != " ": flag = True if flag == True: forward_check.append(i) # ์ž…๋ ฅ๋œ ๋ฌธ์ž๊ฐ€ ์—†์œผ๋ฉด ๊ณต๋ฐฑ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜ if forward_check == []: return "" # ์‹œํ€€์Šค ์—ญ๋ฐฉํ–ฅ์œผ๋กœ ์ฒดํฌํ•˜๋ฉฐ ๊ฐ€์žฅ ์•ž ๊ณต๋ฐฑ ์ œ๊ฑฐ backword_check = [] flag = False while forward_check: i = forward_check.pop() if i != " ": flag = True if flag == True: backword_check.insert(0,i) # ๋ฌธ์ž ์ค‘๊ฐ„์— ์กด์žฌํ•˜๋Š” ์—ฐ์†๋˜๋Š” ๊ณต๋ฐฑ ํ•˜๋‚˜์˜ ๊ณต๋ฐฑ์œผ๋กœ normalized_string = "" pre = True for i in backword_check: if i == " " and pre == True: pre = False elif i != " " and pre == False: normalized_string += " " normalized_string += i pre = True elif i != " " and pre == True: normalized_string += i return normalized_string def no_vowels(input_string): """ ์ธํ’‹์œผ๋กœ ๋ฐ›๋Š” ์ŠคํŠธ๋ง์—์„œ ๋ชจ๋“  ๋ชจ์Œ (a, e, i, o, u)๋ฅผ ์ œ๊ฑฐ์‹œํ‚จ ์ŠคํŠธ๋ง์„ ๋ฐ˜ํ™˜ํ•จ Parameters: input_string (string): ์˜์–ด๋กœ ๋œ ๋Œ€๋ฌธ์ž, ์†Œ๋ฌธ์ž, ๋„์–ด์“ฐ๊ธฐ, ๋ฌธ์žฅ๋ถ€ํ˜ธ๋กœ ์ด๋ฃจ์–ด์ง„ string ex - "This is an example." Returns: no_vowel_string (string): ๋ชจ๋“  ๋ชจ์Œ (a, e, i, o, u)๋ฅผ ์ œ๊ฑฐ์‹œํ‚จ ์ŠคํŠธ๋ง ex - "Ths s n xmpl." Examples: >>> import text_processing as tp >>> input_string1 = "This is an example." >>> tp.normalize(input_string1) "Ths s n xmpl." >>> input_string2 = "We love Python!" >>> tp.normalize(input_string2) ''W lv Pythn!' """ vowel = ['a','e','i','o','u','A','E','I','O','U'] no_vowel_string = "" for i in input_string: if i not in vowel: no_vowel_string += i return no_vowel_string
ce22e32e5f8861cfa09efe1736e92047c79d6155
Joshverge/algorithms
/mergeSort.py
587
3.765625
4
# O(nlogn) time | O(nlogn) space def mergeSort(array): # Write your code here. if len(array) == 1: return array middleIdx = len(array) // 2 lh = array[:middleIdx] rh = array[middleIdx:] return mergeSortA(mergeSort(lh), mergeSort(rh)) def mergeSortA(lh, rh): sArray = [None]*(len(lh) + len(rh)) k = i = j = 0 while i < len(lh) and j < len(rh): if lh[i] <= rh[j]: sArray[k] = lh[i] i += 1 else: sArray[k] = rh[j] j += 1 k +=1 while i < len(lh): sArray[k] = lh[i] i +=1 k +=1 while j < len(rh): sArray[k] = rh[j] j += 1 k += 1 return sArray
5d55d0388f0a09e24c70f360e613555c602bc75e
jrmanrique/codingproblems
/dailycodingproblem/day_5.py
1,091
4.28125
4
"""cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): return lambda f : f(a, b) Implement car and cdr. """ # Explanation: https://stackoverflow.com/questions/21769348/use-of-lambda-for-cons-car-cdr-definition-in-sicp def cons(a, b): return lambda f: f(a, b) def car(cons): return cons(lambda a, b: a) def cdr(cons): return cons(lambda a, b: b) def main(): print('car(cons(3, 4)) == 3:', car(cons(3, 4)) == 3) print('cdr(cons(3, 4)) == 4:', cdr(cons(3, 4)) == 4) # [STEP BY STEP SOLUTION] # cons(3, 4) == lambda f: f(3, 4) # (lambda f: f(3, 4))(f) == 3 # f(3, 4) == 3 # f == (lambda a, b: a) # (lambda a, b: a)(3, 4) == 3 # f(3, 4) == 3 # (lambda f: f(3, 4))(lambda a, b: a) == 3 # (cons(3, 4))(lambda a, b: a) == 3 # car(cons(3, 4)) == 3 # car(cons(3, 4)) == (cons(3, 4))(lambda a, b: a) if __name__ == '__main__': main()
63e3e1f4d5612b8dce39625f005ab6bd5d06d07e
IMDCGP105-1819/portfolio-XHyperNovaX
/ex11.py
271
4.03125
4
from random import randint x = randint(0, 100) guess = x - 1 while guess != x: guess = int(input("Enter what you think the number is: ")) if guess > x: print("Too high.") if guess < x: print("Too low.") print("Correct, you got it!")
2b3d41907dd7d0c4b761d947c8a15cffc9a25245
DIdaniel/coding-training
/4-quotes/demo.py
207
3.546875
4
print("What is the quote?") print("These aren't the droids you're looking for") prompt = input("Who said it? ") prompt2 = input("tell me what he(she) says : ") print(prompt + " says " + f"'{prompt2}'")
5c6a9fec877c778e2c731c10439e3d256db1e561
hulaba/GeeksForGeeksPython
/Search/BinarySearch.py
1,295
4.125
4
class BinarySearch: def run_recursive(self, input_arr, element, left, right): if left >= right: print("Element {0} is not in the input array".format(element)) mid = left + (right - left) / 2 if input_arr[mid] == element: print("Found element {0} at position {1}".format(element, mid + 1)) elif input_arr[mid] > element: right = mid - 1 # because we do not want to consider the mid anymore self.run_recursive(input_arr, element, left, right) else: left = mid + 1 # because we do not want to consider the mid anymore self.run_recursive(input_arr, element, left, right) def run_iterative(self, input_arr, element): left = 0 right = len(input_arr) while right >= left: mid = left + (right - left) / 2 if input_arr[mid] == element: print("Found element {0} at position {1}".format(element, mid + 1)) break elif input_arr[mid] > element: right = mid - 1 else: left = mid + 1 if left >= right: # we've reached the end of the while loop without finding the element print("{0} does not exist in this list".format(element))
d311c4ca9b961dcd96b8186dc9bdd3bbec14d156
UG-SEP/NeoAlgo
/Python/cp/anagram_problem.py
1,372
4
4
""" Problem Statement : To find out if two given string is anagram strings or not. What is anagram? The string is anagram if it is formed by changing the positions of the characters. Problem Link:- https://en.wikipedia.org/wiki/Anagram Intution: Sort the characters in both given strings. After sorting, if two strings are similar, they are an anagram of each other. Return : A string which tells if the given two strings are Anagram or not. """ def checkAnagram(str1, str2): #Checking if lenght of the strings are same if len(str1) == len(str2): #Sorting both the strings sorted_str1 = sorted(str1) sorted_str2 = sorted(str2) #Checking if both sorted strings are same or not if sorted_str1 == sorted_str2: return "The two given strings are Anagram." else: return "The two given strings are not Anagram." def main(): #User input for both the strings str1 = input("Enter 1st string: ") str2 = input("Enter 2nd srring: ") #function call for checking if strings are anagram print(checkAnagram(str1, str2)) main() """ Sample Input / Output: Enter 1st string: lofty Enter 2nd srring: folty The two given strings are Anagram. Enter 1st string: bhuj Enter 2nd srring: ghuj The two given strings are not Anagram. """
f5e365acfce86c39ed1501e667e3371a4e07048c
Oukey/data_visualization
/scatter_squares.py
892
3.53125
4
# scatter_squares.py import matplotlib.pyplot as plt # x_values = [1, 2, 3, 4, 5] # y_values = [1, 4, 9, 16, 25] x_values = list(range(1, 1001)) y_values = [x ** 2 for x in x_values] # plt.scatter(x_values, y_values, s=40) plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='None', s=40) # ะะฐะทะฝะฐั‡ะตะฝะธะต ะทะฐะณะพะปะพะฒะบะฐ ะดะธะฐะณั€ะฐะผะผ ะธ ะผะตั‚ะพะบ ะพัะตะน plt.title('Square Numbers', fontsize=24) plt.xlabel('Value', fontsize=14) plt.ylabel('Square of Value', fontsize=14) # ะะฐะทะฝะฐั‡ะตะฝะธะต ั€ะฐะทะผะตั€ะฐ ัˆั€ะธั„ั‚ะฐ ะดะตะปะตะฝะธะน ะฝะฐ ะพััั… plt.tick_params(axis='both', which='major', labelsize=14) # ะะฐะทะฝะฐั‡ะตะฝะธะต ะดะธะฐะฟะฐะทะพะฝะฐ ะดะปั ะบะฐะถะดะพะน ะพัะธ plt.axis([0, 1100, 0, 1100000]) plt.show() # ะฒั‹ะฒะพะด ะฝะฐ ัะบั€ะฐะฝ plt.savefig('squeres_plot.png', bbox_inches='tight') # ัะพั…ั€ะฐะฝะตะฝะธะต ั„ะฐะนะปะฐ # 319
429369b5cc9f2840e6f35f139c64cdf5920d2e67
MilkUndPanis/MilkUndPanis-Python-Exercise-2019.6.27-2020.2.15
/Exercising/glass/glass.py
5,573
3.828125
4
import math as m EAST=0 SOUTH=270 WEST=180 NORTH=90 A_TURN=90 GLASS_WIDTH=40 HALF_WIDTH=20 GLASS_HEIGHT=30 HALF_HEIGHT=15 import turtle turtle.hideturtle() turtle.pensize(3) turtle.speed(0) turtle.penup() turtle.goto(50,50) turtle.pendown() turtle.setheading(EAST) turtle.forward(GLASS_WIDTH) turtle.left(A_TURN) turtle.forward(GLASS_HEIGHT) turtle.left(A_TURN) turtle.forward(GLASS_WIDTH) turtle.left(A_TURN) turtle.forward(GLASS_HEIGHT) turtle.setheading(EAST) turtle.penup() turtle.goto(50,65) turtle.pendown() turtle.goto(-50,65) turtle.setheading(SOUTH) turtle.forward(HALF_HEIGHT) turtle.right(A_TURN) turtle.forward(GLASS_WIDTH) turtle.right(A_TURN) turtle.forward(GLASS_HEIGHT) turtle.right(A_TURN) turtle.forward(GLASS_WIDTH) turtle.right(A_TURN) turtle.forward(HALF_HEIGHT) turtle.penup() turtle.goto(-50-HALF_WIDTH,0) turtle.setheading(SOUTH+30) turtle.pendown() turtle.circle(140/(m.sqrt(3)),120) turtle.setheading(WEST) turtle.forward(140) turtle.penup() turtle.goto(-220/(m.sqrt(3)),65) turtle.pendown() turtle.setheading(SOUTH) turtle.circle(220/(m.sqrt(3)),180) turtle.setheading(NORTH) turtle.forward(120) turtle.circle(80,90) turtle.forward(440/(m.sqrt(3))-160) turtle.circle(80,90) turtle.penup() turtle.goto(220/(m.sqrt(3)),185) turtle.pendown() radius=15+2420/9 the=(m.atan((2420/9-15)/(220/m.sqrt(3)))*360)/(2*3.1415926535897932) turtle.setheading(NORTH+the) turtle.circle(radius,180-2*the) turtle.setheading(SOUTH) turtle.forward(120) turtle.penup() turtle.goto(-70,155) turtle.pendown() turtle.goto(70,155) turtle.penup() turtle.goto(-70,135) turtle.pendown() turtle.goto(70,135) turtle.penup() turtle.goto(-70,115) turtle.pendown() turtle.goto(70,115) turtle.penup() turtle.goto(-50,90) turtle.pendown() turtle.setheading(NORTH+30) turtle.circle(GLASS_WIDTH/m.sqrt(3),120) turtle.penup() turtle.goto(90,90) turtle.pendown() turtle.setheading(NORTH+30) turtle.circle(GLASS_WIDTH/m.sqrt(3),120) turtle.penup() turtle.goto(-54,65) turtle.pendown() theta=(m.atan(7.8/16))*360/(2*3.1415926535897932) turtle.setheading(theta+NORTH) turtle.circle(17.8,180-2*theta) turtle.setheading(SOUTH+theta) turtle.circle(17.8,180-2*theta) turtle.penup() turtle.goto(-70,72) turtle.pendown() turtle.setheading(WEST) turtle.circle(7) turtle.goto(-70,68) turtle.setheading(WEST) turtle.fillcolor('black') turtle.begin_fill() turtle.circle(3) turtle.end_fill() turtle.penup() turtle.goto(86,65) turtle.pendown() turtle.setheading(theta+NORTH) turtle.circle(17.8,180-2*theta) turtle.setheading(SOUTH+theta) turtle.circle(17.8,180-2*theta) turtle.penup() turtle.goto(70,72) turtle.pendown() turtle.setheading(WEST) turtle.circle(7) turtle.goto(70,68) turtle.setheading(WEST) turtle.fillcolor('black') turtle.begin_fill() turtle.circle(3) turtle.end_fill() turtle.penup() turtle.goto(-51,0) turtle.pendown() turtle.setheading(SOUTH) turtle.forward(22) turtle.penup() turtle.goto(-32,0) turtle.pendown() turtle.forward(33.7) turtle.penup() turtle.goto(-13,0) turtle.pendown() turtle.forward(38) turtle.penup() turtle.goto(6,0) turtle.pendown() turtle.forward(38) turtle.penup() turtle.goto(25,0) turtle.pendown() turtle.forward(36.8) turtle.penup() turtle.goto(44,0) turtle.pendown() turtle.forward(27) turtle.penup() turtle.goto(63,0) turtle.pendown() turtle.forward(8) turtle.penup() turtle.goto(-70,0) turtle.pendown() turtle.setheading(SOUTH+60) turtle.circle(140,20) x=turtle.xcor() t=turtle.heading() turtle.setheading(EAST) turtle.forward(-2*x) turtle.setheading(-t) turtle.circle(140,20) pro=220/m.sqrt(3) turtle.penup() turtle.goto(-pro,110) turtle.pendown() turtle.setheading(WEST) turtle.forward(14) turtle.circle(15,167) k=turtle.ycor() turtle.setheading(WEST+13) turtle.circle(15,227) y=turtle.ycor() turtle.penup() turtle.goto(pro,y) turtle.pendown() turtle.setheading(EAST) turtle.forward(14) turtle.circle(15,167) turtle.setheading(EAST+13) turtle.circle(15,227) turtle.setheading(EAST) turtle.penup() turtle.goto(-30,90) turtle.pendown() turtle.goto(30,90) turtle.penup() turtle.setheading(NORTH+30) turtle.goto(-7.5,90) turtle.pendown() turtle.forward(15) turtle.penup() turtle.goto(0,90) turtle.setheading(NORTH) turtle.pendown() turtle.forward(30/m.sqrt(3)) turtle.penup() turtle.setheading(NORTH-30) turtle.goto(7.5,90) turtle.pendown() turtle.forward(15) turtle.penup() turtle.goto(30,90) turtle.pendown() turtle.setheading(SOUTH-30) turtle.circle(120,30) turtle.penup() turtle.setheading(315) turtle.forward(15*m.sqrt(2)) turtle.setheading(EAST) turtle.pendown() turtle.circle(15,270) turtle.penup() turtle.setheading(315) turtle.forward(15*m.sqrt(2)) turtle.setheading(NORTH) turtle.pendown() turtle.circle(13,180) x=turtle.xcor() turtle.setheading(WEST) turtle.forward(2*x) turtle.setheading(NORTH) turtle.circle(13,180) turtle.setheading(45) turtle.penup() turtle.forward(15*m.sqrt(2)) turtle.pendown() turtle.setheading(NORTH) turtle.circle(15,270) turtle.penup() turtle.setheading(45) turtle.forward(15*m.sqrt(2)) turtle.pendown() turtle.setheading(NORTH) turtle.circle(120,30) turtle.setheading(EAST) turtle.penup() turtle.goto(-50,90) turtle.pendown() turtle.forward(100) turtle.penup() turtle.goto(90,65) turtle.pendown() turtle.forward(20) turtle.goto(pro,k) turtle.left(2*A_TURN) turtle.penup() turtle.goto(-90,65) turtle.pendown() turtle.forward(20) turtle.goto(-pro,k) turtle.done()
f4f1780adb44e6bd7daadc70b3e22ef814e3b342
capJavert/advent-of-code-2016
/5-day.py
733
3.515625
4
from hashlib import md5 def is_numeric(string): try: int(string) except: return False return True def main(): password_size = 0 password = ["_", "_", "_", "_", "_", "_", "_", "_"] door_id = "abbhdwsy" index = 0 while password_size < 8: m = md5() string = door_id+str(index) m.update(string.encode()) hash_string = m.hexdigest() if hash_string[0:5] == "00000" and is_numeric(hash_string[5]): if 8 > int(hash_string[5]) >= 0 and password[int(hash_string[5])] == "_": password_size += 1 password[int(hash_string[5])] = str(hash_string[6]) index += 1 print("".join(password)) main()
1e8406743d6752ab3b44f95ab0fa398feac54638
a1379478560/offer-python
/ๅ่ฝฌ้“พ่กจ.py
546
4
4
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # ่ฟ”ๅ›žListNode def ReverseList(self, pHead): # write code here if not pHead or not pHead.next: return pHead pre=pHead pHead=pHead.next post=pHead.next pre.next=None while post: pHead.next=pre pre=pHead pHead=post post=post.next pHead.next=pre return pHead
db83d0520e8c0ce8c6ae6a083d70a530b40bfbde
YangLiyli131/Leetcode2020
/in_Python/0025 Reverse Nodes in k-Group.py
1,741
3.671875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def rev(self, head): pre = None nex = None cur = head while cur: nex = cur.next cur.next = pre pre = cur cur = nex return pre def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if k == 1: return head le = 0 pp = head while pp: le += 1 pp = pp.next revlast = 1 if le % k != 0: revlast = 0 heads = [] cursum = 1 h = head while head: if head.next == None and cursum < k: heads.append(h) break cursum += 1 head = head.next if cursum == k: #print(h.val) heads.append(h) cursum = 1 h = head.next head.next = None head = h newheads = [] for x in heads[0: len(heads)-1]: newheads.append(self.rev(x)) if revlast == 1: newheads.append(self.rev(heads[-1])) else: newheads.append(heads[-1]) last = newheads[0] while last.next != None: last = last.next for nh in newheads[1:]: last.next = nh last = nh while last.next != None: last = last.next return newheads[0]
c1720754ba312fa8d6a4dfe56a5d29d8f1e14d8e
rodrigocamargo854/Some_codes_python
/COORDENADA_9ANO.py
523
3.65625
4
titulo= "GERADOR DO GRรFICO DE UMA FUNร‡รƒO" soma = 0 print("=" *80) print(titulo.center(70)) print("=" *80) import matplotlib.pyplot as grafico x = [] y =[] num = int(input(" Digite numero de coordenadas para x e para y\n")) for i in range (0,num): coodx = int(input(" digite a coordenada para x\n")) x.append (coodx) coody = int(input(" digite a coordenads para y\n")) y.append (coody) grafico.plot(x,y) grafico.title(" Coordenadas Cartesianas Interativas") grafico.show()
1bf089da861a1a7e57ccf4103091e3056bc8bda2
htmlprogrammist/kege-2021
/tasks_19-21/homework/zadanie_20_130920-automized.py
233
3.546875
4
end_of_interval = 200 x = 1 answer = 125 while x <= end_of_interval: # x = int(input()) L = 17 M = 70 while L <= M: L = L + 2*x M = M + x if L == answer: print(x) x += 1
abf4c295fbfe1594631121d6539f4ff91d3491b9
SkyBulk/bigb0ss-RD
/python_learning/w3resource/basics/basic_1-10.py
302
3.9375
4
# 10. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. # Sample value of n is 5 # Expected Result : 615 num = int(input("[*] Enter the number: ")) num1 = int("%s" % num) num2 = int("%s%s" % (num,num)) num3 = int("%s%s%s" % (num,num,num)) print(num + num2 + num3)
2aa58a44011362aa580ef38409fa0c52d497d1a7
jaarmore/holberton-system_engineering-devops
/0x16-api_advanced/2-recurse.py
973
3.609375
4
#!/usr/bin/python3 """ Recursive function that queries the Reddit API and returns a list containing the titles of all hot articles for a given subreddit. """ import requests def recurse(subreddit, hot_list=[], after=''): """ Recursive function that queries the Reddit API. Args URL: url of the API, formatted with subreddit to search header: custom header to avoid error Too Many Requests param: the variables to pass at URL """ URL = 'https://api.reddit.com/r/{}/hot'.format(subreddit) header = {'User-Agent': 'Custom-User'} param = {'after': after} resp = requests.get(URL, headers=header, params=param).json() try: top = resp['data']['children'] sig = resp['data']['after'] for item in top: hot_list.append(item['data']['title']) if sig is not None: recurse(subreddit, hot_list, sig) return hot_list except Exception: return None
9e3b454f2262af1b37cffcf1f6d77b3c8e437f05
fernandochimi/Intro_Python
/Exercรญcios/053_Contagem_Cedulas.py
609
3.8125
4
valor = int(input("Digite o valor a pagar: ")) cedulas = 0 atual = 100 a_pagar = valor while True: if atual <= a_pagar: a_pagar -= atual cedulas += 1 else: print("%d cรฉdula(s) de R$ %d" % (cedulas, atual)) if a_pagar == 0: break if atual == 100: atual = 50 elif atual == 50: atual = 20 elif atual == 20: atual = 10 elif atual == 10: atual = 5 elif atual == 5: atual = 1 elif atual == 1: atual = 0.50 elif atual == 0.50: atual = 0.10 elif atual == 0.10: atual = 0.05 elif atual == 0.05: atual = 0.02 elif atual == 0.02: atual = 0.01 cedulas = 0
6a6d4313b655a9d5ac34bb9f8dc45652d1f6502a
Rulowizard/Homework-Week-3-python-challenge
/PyPoll/main.py
1,724
3.59375
4
import os import csv csvpath = os.path.join("election_data.csv") num_votos=0 #Declaro un diccionario nulo cand={} with open(csvpath,"r") as csv_file: csvreader= csv.reader(csv_file, delimiter=",") csv_header = next(csvreader) #Creo lista de candidatos candidatos= list( set( [candidato[2] for candidato in csvreader ] )) #Creo un diccionario for candidato in candidatos: cand[str(candidato)]=0 #Me muevo al principio del archivo csv_file.seek(0) #Desecho la fila de los headers csv_header = next(csvreader) #Itero dentro del archivo for row in csvreader: num_votos = num_votos +1 cand[row[2]] += 1 print("Election Results") print("----------------------------") print(f"Total Votes: {num_votos}") print("----------------------------") mensajes =[ candidato+": "+ str(int(round(cand[candidato]*100/num_votos)))+"% " +"("+str(cand[candidato])+")" for candidato in candidatos] for mensaje in mensajes: print(mensaje) print("----------------------------") ganador = max(cand,key=cand.get) print(f"Winner: {ganador}") print("----------------------------") with open("output_file.csv","w") as csvfile: filewriter = csv.writer(csvfile,delimiter=",") filewriter.writerow(["Election Results"]) filewriter.writerow(["----------------------------"]) filewriter.writerow(["Total Votes:",num_votos]) filewriter.writerow(["----------------------------"]) for mensaje in mensajes: filewriter.writerow([mensaje]) filewriter.writerow(["----------------------------"]) filewriter.writerow(["Winner",ganador]) filewriter.writerow(["----------------------------"])
09795245970efd7c64f5a2b158d621d93a0fa5d8
vivekpapnai/Python-DSA-Questions
/Binary Search Tree/NodetoRootPath.py
1,872
3.734375
4
import queue from sys import stdin class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def NodetoRootPath(root,x): if root is None: return None if root.data == x: li = list() li.append(root.data) return li leftpath = NodetoRootPath(root.left,x) if leftpath !=None: leftpath.append(root.data) return leftpath RightPath = NodetoRootPath(root.right,x) if RightPath != None: RightPath.append(root.data) return RightPath else: return None def PrintBinaryTree(root): if root is None: return None print(root.data, end=":") if root.left is not None: print("L", root.left.data, end=",") if root.right is not None: print("R", root.right.data, end=" ") print() PrintBinaryTree(root.left) PrintBinaryTree(root.right) def takeInput(): levelOrder = list(map(int, stdin.readline().strip().split(" "))) start = 0 length = len(levelOrder) root = BinaryTreeNode(levelOrder[start]) start += 1 q = queue.Queue() q.put(root) while not q.empty(): currentNode = q.get() leftChild = levelOrder[start] start += 1 if leftChild != -1: leftNode = BinaryTreeNode(leftChild) currentNode.left = leftNode q.put(leftNode) rightChild = levelOrder[start] start += 1 if rightChild != -1: rightNode = BinaryTreeNode(rightChild) currentNode.right = rightNode q.put(rightNode) return root root = takeInput() x = int(input()) # PrintBinaryTree(root) li = NodetoRootPath(root,x) print(li) # for i in li: # print(i ,end=" ")
6fb33625c14de399b441091ea7a154fa0053ccf3
kajj8808/DjangoStudy
/Arguments.py
706
3.703125
4
def plus(a , b): return a + b #์ข…์ข… ํŒŒ์ด์ฌ์—์„œ ํ•จ์ˆ˜์— ๋ฌด์ œํ•œ์œผ๋กœ arguments ๋ฅผ ๋„ฃ๊ณ ์‹ถ์„๋•Œ. #์ฒซ๋ฒˆ์งธ ๋ฐฉ๋ฒ•์€ *args ๋ฅผ ์จ๋†“๋Š”๊ฒƒ. # ์ด๋ ‡๊ฒŒํ•˜๋ฉด tuple ๋กœ return def plus_args(a , b , *args): print(args) return a + b #๋ฌดํ•œ์ •์œผ๋กœ keyword argument ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ ์‹ถ์„๋•Œ๋ฉด. ** ์€ ๊ผญ๋ถ™ํ˜€์•ผํ•จ. def plus_args_infinity(a , b , *args , **kwargs): print(args) print(kwargs) return a + b #positional argument => (1 ,2,3,4,5,6,7,8,9) keyword argument => {'gus'=True} #์ˆซ์ž๋ฅผ ์ „๋ถ€ ๋ฐ›์•„์„œ ๋”ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜. ex) (1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10) def infinity_plus_cal(*args): result = 0 for number in args: result += number print(result)
50cd97efa2821e47c68d34e32fab15c3fc629d45
danWalt/automate_the_boring_stuff_selfprojects
/CSV/excel2csv/excel2csv.py
1,502
3.609375
4
#! python3 # excel2csv.py filters a directory for excel files and saves each sheet in # an excel file as a separate CSV file import openpyxl, csv, os os.makedirs('csvFiles', exist_ok=True) for excelFile in os.listdir('.'): excel_file_name = excelFile[:len(excelFile) - 5] # Skip non-xlsx files, load the workbook object. if excelFile.endswith('.xlsx'): wb = openpyxl.load_workbook(excelFile) # Loop through every sheet in the workbook. for sheetName in wb.sheetnames: sheet = wb[sheetName] # Create the CSV filename from the Excel filename and sheet title. csvfilename = excel_file_name + '_' + sheetName + '.csv' csvFileObj = open(os.path.join('csvFiles', csvfilename), 'w', newline='') # Create the csv.writer object for this CSV file. csvWriter = csv.writer(csvFileObj) # Loop through every row in the sheet. for rowNum in range(1, sheet.max_row + 1): rowData = [] # append each cell to this list # Loop through each cell in the row. for columnNum in range(1, sheet.max_column + 1): # Append each cell's data to rowData. rowData.append( sheet.cell(row=rowNum, column=columnNum).value) # Write the rowData list to the CSV file. csvWriter.writerow(rowData) csvFileObj.close()
7154fbc21ae802534748bfbd47221cb772ccdaef
OlavBerg/Text_based_python_game
/help_functions.py
901
3.59375
4
import operator def reverseDirection(direction: str): if direction == "n": return "s" elif direction == "e": return "w" elif direction == "s": return "n" elif direction == "w": return "e" else: print("Error: Invalid direction.") return False def doubleRange(x_max: int, y_max: int): intPairList = [] for x in range(x_max): for y in range(y_max): intPairList.append([x, y]) return intPairList def listSubtraction(minuendList: list, subtrahendList: list): for subtrahend in subtrahendList: try: minuendList.remove(subtrahend) except: pass def listOfPairs(list1: list, list2: list): pairList = [] for list1Element in list1: for list2Element in list2: pairList.append([list1Element, list2Element]) return pairList
02e75b45374d35a2a8862dee62f817cc4850cedd
DKU-STUDY/Algorithm
/BOJ/solved.ac_class/Class02/11050. ์ดํ•ญ๊ณ„์ˆ˜/sAp00n.py
146
3.5
4
from math import factorial as f n, k = map(int, input().split()) if k < 0 or k > n: print(0) else: print(int(f(n) / (f(k) * f(n - k))))
6eba254ae9d58e9ed60dee2430a422150282bbe4
LeeDongGeon1996/co-te
/book/[๊ตฌํ˜„-pt1] ์ƒํ•˜์ขŒ์šฐ.py
662
3.5625
4
# solution: ์ƒํ•˜์ขŒ์šฐ๋ฅผ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด ์ˆœํšŒํ•˜๋ฉฐ ์ž…๋ ฅ๋œ ๊ฒฝ๋กœ์™€ ๋น„๊ตํ•œ๋‹ค. # time-complexity: O(N) - ์„ ํ˜•์‹œ๊ฐ„ direction = ['L', 'R', 'U', 'D'] move_x = [-1, 1, 0, 0] move_y = [0, 0, -1, 1] x_pos = 1 y_pos = 1 # start_input N = int(input()) path = input().split() # end_input for i in path: for j in range(len(direction)): if i == direction[j]: x_moved = x_pos + move_x[j] y_moved = y_pos + move_y[j] if x_moved < 1 or x_moved > N or y_moved < 1 or y_moved > N: continue x_pos = x_moved y_pos = y_moved # start_print print("(" + str(x_pos) + ", " + str(y_pos) + ")") # end_print
a25adbead415aad3d9c7d54c024912aa14844489
montaro/leetcode-python
/arrays_strings/2973_most_common_word.py
1,125
3.609375
4
from typing import List def clear_symbols(text: str) -> str: symbols = '!?\',;.' for symbol in symbols: text = text.replace(symbol, " ") return text s = clear_symbols("Ahmed ?and??Doaa!!").split() print(s) class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: banned = [word.lower() for word in banned] frequency = {} paragraph = clear_symbols(paragraph).split() paragraph = [word.lower() for word in paragraph] for word in paragraph: if word in banned: pass else: try: frequency[word] except KeyError: frequency[word] = 1 else: frequency[word] = frequency[word] + 1 print(frequency) result, best = '', 0 for k, v in frequency.items(): if v > best: result = k best = v return result s = Solution() print(s.mostCommonWord('Bob hit a ball, the hit BALL flew far after it was hit.', ['hit']))
323e9861a0389a1c50f1a16ccad97ace57037638
CoderTitan/PythonDemo
/PythonStudy/8-้“ถ่กŒ็ณป็ปŸๅ’Œthinter/1-้“ถ่กŒ่‡ชๅŠจๆๆฌพๆœบ็ณป็ปŸ/ATM.py
6,458
3.578125
4
from Users import Users from Card import Card import random class ATM(object): def __init__(self, allUsers): # ๆ‰€ๆœ‰็”จๆˆท self.allUsers = allUsers # 1.ๅผ€ๆˆท def creatUser(self): name = input('่ฏท่พ“ๅ…ฅๅง“ๅ:') idCard = input('่ฏท่พ“ๅ…ฅ่บซไปฝ่ฏๅท:') phoneNum = input('่ฏท่พ“ๅ…ฅๆ‰‹ๆœบๅท:') money = int(input('่ฏท่พ“ๅ…ฅๅญ˜ๆฌพ้‡‘้ข:')) if money < 0: print('้‡‘้ข่พ“ๅ…ฅๆœ‰่ฏฏ, ่ฏท้‡ๆ–ฐๆ“ไฝœ!') return -1 passwd = input('่ฏท่พ“ๅ…ฅๅฏ†็ :') # ๆฃ€ๆต‹ๅฏ†็ ๆ˜ฏๅฆ็ฌฆๅˆ่ง„ๅˆ™ if not self.checkPassword(passwd): print('ๅฏ†็ ่พ“ๅ…ฅ้”™่ฏฏ, ๆ“ไฝœๅคฑ่ดฅ!') return -1 # ๅˆฐ่ฟ™้‡Œ่ฏดๆ˜Žๆ‰€ๆœ‰ไฟกๆฏๅฐฑ้ƒฝๆญฃ็กฎไบ† cardStr = self.getRandomCardID() card = Card(cardStr, passwd, money) user = Users(name, idCard, phoneNum, card) # ๅญ˜ๅˆฐๅญ—ๅ…ธไธญ self.allUsers[cardStr] = user print('ๅผ€ๆˆทๆˆๅŠŸ, ่ฏท็‰ข่ฎฐๅกๅท: (%s)' % cardStr) # 2.ๆŸฅ่ฏข def searchUserInfo(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 print('่ดฆๅท: %s, ไฝ™้ข: %d' % (user.card.cardID, user.card.cardMoney)) # 3.ๅ–ๆฌพ def getAccountMoney(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 print('่ดฆๅท: %s, ไฝ™้ข: %d' % (user.card.cardID, user.card.cardMoney)) getMoney = int(input('่ฏท่พ“ๅ…ฅๅ–ๆฌพๆ•ฐ้ข:')) if getMoney < 0: print('้‡‘้ข่พ“ๅ…ฅๆœ‰่ฏฏ, ่ฏท้‡ๆ–ฐๆ“ไฝœ!') return -1 if getMoney > user.card.cardMoney: print('ๆ‰€ๅ–้‡‘้ข่ถ…่ฟ‡้“ถ่กŒๅกไฝ™้ข, ่ฏท้‡ๆ–ฐๆ“ไฝœ') return -1 user.card.cardMoney = user.card.cardMoney - getMoney print('ๅ–ๆฌพๆˆๅŠŸ, ไฝ™้ข: %d' % user.card.cardMoney) # 4.ๅญ˜ๆฌพ def saveMoney(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 print('่ดฆๅท: %s, ไฝ™้ข: %d' % (user.card.cardID, user.card.cardMoney)) secondMoney = int(input('่ฏท่พ“ๅ…ฅๅญ˜ๆฌพๆ•ฐ:')) if secondMoney < 0: print('้‡‘้ข่พ“ๅ…ฅๆœ‰่ฏฏ, ่ฏท้‡ๆ–ฐๆ“ไฝœ!') return -1 user.card.cardMoney = secondMoney + user.card.cardMoney print('ๅญ˜ๆฌพๆˆๅŠŸ, ไฝ™้ข: %d' % user.card.cardMoney) # 5. ่ฝฌ่ดฆ def transformAccountMoney(self): pass # 6.ๆ”นๅฏ†็  def reviseAccountPassword(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 newPass = input('่ฏท่พ“ๅ…ฅๆ–ฐๅฏ†็ :') if not self.checkPassword(newPass): print('ๅฏ†็ ่พ“ๅ…ฅ้”™่ฏฏ, ๆ“ไฝœๅคฑ่ดฅ!') return -1 user.card.passwd = newPass # 7.้”ๅฎš่ดฆๆˆท def lockAccount(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 tempIDCard = input('่ฏท่พ“ๅ…ฅ่บซไปฝ่ฏๅท็ :') if not tempIDCard == user.idCard: print('่บซไปฝ่ฏไฟกๆฏๆœ‰่ฏฏ, ้”ๅฎšๅคฑ่ดฅ') return -1 user.card.cardLock = True print('้”ๅฎšๆˆๅŠŸ') # 8.่งฃ้” def unlockAccount(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 # ่บซไปฝไฟกๆฏ tempIDCard = input('่ฏท่พ“ๅ…ฅ่บซไปฝ่ฏๅท็ :') if not tempIDCard == user.idCard: print('่บซไปฝ่ฏไฟกๆฏๆœ‰่ฏฏ, ้”ๅฎšๅคฑ่ดฅ') return -1 user.card.cardLock = False print('่งฃ้”ๆˆๅŠŸ') # 9.่กฅๅก def reserAccountCard(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 # ่บซไปฝไฟกๆฏ tempIDCard = input('่ฏท่พ“ๅ…ฅ่บซไปฝ่ฏๅท็ :') if not tempIDCard == user.idCard: print('่บซไปฝ่ฏไฟกๆฏๆœ‰่ฏฏ, ้”ๅฎšๅคฑ่ดฅ') return -1 user.card.cardID = self.getRandomCardID() # 0.้”€ๆˆท def removeAccount(self): cardNum = input('่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅกๅท: ') # ้ชŒ่ฏๆ˜ฏๅฆๅญ˜ๅœจ่ฏฅๅกๅท user = self.allUsers.get(cardNum) if self.checkAccountInfo(user): return -1 # ่บซไปฝไฟกๆฏ tempIDCard = input('่ฏท่พ“ๅ…ฅ่บซไปฝ่ฏๅท็ :') if not tempIDCard == user.idCard: print('่บซไปฝ่ฏไฟกๆฏๆœ‰่ฏฏ, ้”ๅฎšๅคฑ่ดฅ') return -1 del self.allUsers[cardNum] print(self.allUsers) # ๆฃ€ๆต‹ๅกๅทๆ˜ฏๅฆๅญ˜ๅœจ, ๆ˜ฏๅฆ้”ๅฎš, ้ชŒ่ฏๅฏ†็  def checkAccountInfo(self, user): if not user: print('่ฏฅๅกไธๅญ˜ๅœจ, ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ.') return -1 # ๅˆคๆ–ญๆ˜ฏๅฆ้”ๅฎš if user.card.cardLock: print('่ฏฅๅกๅทฒ้”ๅฎš, ่ฏทๅ…ˆ่งฃ้”ๅ†้‡ๆ–ฐๆ“ไฝœ') return -1 # ้ชŒ่ฏๅฏ†็  if not self.checkPassword(user.card.passwd): print("ๅฏ†็ ้”™่ฏฏ, ") user.card.cardLock = True return -1 # ๆฃ€ๆต‹ไธคๆฌก่พ“ๅ…ฅ็š„ๅฏ†็ ๆ˜ฏๅฆไธ€่‡ด def checkPassword(self, realPasswd): for i in range(3): tempPass = input('่ฏท่พ“ๅ…ฅๅฏ†็ :') if tempPass == realPasswd: return True print('ๅฏ†็ ้”™่ฏฏ, ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ') return False # ่Žทๅ–้“ถ่กŒๅกๅท(้šๆœบ) def getRandomCardID(self): while True: str = '' for i in range(10): # ord(x): ๅฐ†ไธ€ไธชๅญ—็ฌฆ่ฝฌๆขไธบๅฎƒ็š„ๆ•ดๆ•ฐๅ€ผ ch = chr(random.randrange(ord('0'), ord('9') + 1)) str += ch # ๅˆคๆ–ญๆ˜ฏๅฆ้‡ๅค if not self.allUsers.get(str): return str
97256e4594bbbe596db6783088527f3099bfdc86
nithinp300/subscription-tracker
/main.py
1,324
3.875
4
import subscription my_subs = subscription.Inventory() userChoices = "(a) add, (r) remove (t) total (p) print (e) exit" userInput = "" while userInput != "e": userInput = input(userChoices+"\n") if userInput == "a": subType = input("monthly(m), yearly(y) or one-time(ot) subscription?:") subName = input("What is name of subscription:") subCost = int(input("What is the cost:")) subDate = "none" if subType == "m" or subType == "y": subDate = input("When does it renew:") sub = subscription.Subscription(subName, subCost, subDate) if subType == "m": sub = subscription.Monthly(subName, subCost, subDate) elif subType == "y": sub = subscription.Yearly(subName, subCost, subDate) added = my_subs.add(sub) if added: print(subName + " Added") else: print(subName + " is already in your list") elif userInput == "r": subName = input("What subscription do you want to remove") removed = my_subs.remove(subName) if removed: print(subName + " Removed") else: print(subName + " is not in your list") elif userInput == "t": my_subs.get_total_cost() elif userInput == "p": my_subs.print_subs()
f7371997cadc5a88dceda9fc4ba4bb3d170b253a
calendula547/python_fundamentals_2020
/python_fund/list_advanced/next_version.py
343
3.609375
4
version = list(input().split(".")) def greater_num(num_list): int_version = int("".join(num_list)) next_version = int_version + 1 result_version = [int(x) for x in str(next_version)] return result_version next_version_result = (greater_num(version)) print('.'.join(str(el) for el in next_version_result))
1f62b8ecd51bb9b7bb696af7df264709fcc8d8d4
TengXu/CS-2015
/CS 111/ps9/ps9pr3.py
1,027
4.0625
4
# Name: Teng Xu # E-mail: [email protected] from ps9pr2 import Date def get_age_on(birthday, other): """ accepts two Date objects as parameters: one to represent a personโ€™s birthday, and one to represent an arbitrary date. The function should then return the personโ€™s age on that date as an integer """ new_date = Date(birthday.month, birthday.day, other.year) age = other.year - birthday.year - 1 if other.is_after(new_date): age += 1 return age def print_birthdays(filename): """ accepts a string filename as a parameter. The function should then open the file that corresponds to that filename, read through the file, and print some information derived from that file """ file = open(filename, 'r') for line in file: fields = line.split(',') mon = int(fields[1]) day = int(fields[2]) year = int(fields[3]) d = Date( mon, day, year) print (fields[0],'(' + str(d) + ')','(' + d.day_of_week() + ')')
2699efa3a987b4c20d54ab33ecd1a233597c7f6c
kjkjv/python
/์‹ค์Šต๋ฌธ์ œ.py
63,276
3.875
4
#1๋ฒˆ g = input("๊ฑฐ๋ฆฌ : ") s = input("์†๋„ : ") total = int(g) / int(s) print(total) #2๋ฒˆ g = input("๊ฑฐ๋ฆฌ : ") n = input("๋„ˆ๋น„ : ") m = int(g)*int(s) print(m) d = (int(g)*2) + (int(n)*2) print(d) #3๋ฒˆ h = input("ํ™”์”จ : ") s = (int(h)-32)/1.8 print(s) #4๋ฒˆ a = input("a : ") b = input("b : ") print(("๋ง์…ˆ :", int(a) + int(b)), ("๋บ„์…ˆ : ", int(a) - int(b)), ("๋‚˜๋ˆ—์…ˆ : ", int(a) * int(b)), ("๊ณฑ์…ˆ : ",int(a) / int(b))) #print(total) # eval() ๋ฌธ์ž์—ด์„ int๋กœ ์•ˆ๋ฐ”๊ฟ”๋„ ์ˆซ์ž๋กœ ๊ณ„์‚ฐํ•ด์ฃผ๋Š” ์‹. # =======================๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ===============================================# #numeric_ex.py #1๋ฒˆ print( '{0:=^50}'.format( '1๋ฒˆ' ) ) velocity = input( 'Input velocity : ' ) distance = input( 'Input distance : ' ) #time = eval( distance + '/' + velocity ) time = int(distance) / int(velocity) print() print( 'velocity : {0:<6.2f}'.format( float( velocity ) ) ) print( 'distance : {0:<6.2f}'.format( float( distance ) ) ) print( 'time : {0:<6.2f}'.format( time ) ) #2๋ฒˆ print( '{0:=^50}'.format( '2๋ฒˆ' ) ) length = input( 'Input length : ' ) width = input( 'Input width : ' ) #area = eval( length + '*' + width ) area = int(length) * int(width) #circumference = eval( length + '*' + '2' + '+' + width + '*' + '2' ) circumference = int(length) * 2 + int(width) *2 print() print( 'length : {0:<6.2f}\twidth : {1:<6.2f}'.format( float( length ), float( width ) ) ) print( 'area : {0:<6.2f}'.format( area ) ) print( 'circumference : {0:<6.2f}'.format( circumference ) ) #3๋ฒˆ print( '{0:=^50}'.format( '3๋ฒˆ' ) ) fahrenheit = float( input( 'Input fahrenheit : ' ) ) celsius = ( fahrenheit - 32 ) / 1.8 print() print( 'fahrenheit : {0:<6.2f} -> celsius : {1:<6.2f}'.format( fahrenheit, celsius ) ) #4๋ฒˆ print( '{0:=^50}'.format( '4๋ฒˆ' ) ) number1 = int( input( 'Input number1 : ' ) ) number2 = int( input( 'Input number2 : ' ) ) add = number1 + number2 subtract = number1 - number2 multiple = number1 * number2 divide = number1 / number2 print() print( '{0:^6} + {1:^6} = {2:<6}'.format( number1, number2, add ) ) print( '{0:^6} - {1:^6} = {2:<6}'.format( number1, number2, subtract ) ) print( '{0:^6} * {1:^6} = {2:<6}'.format( number1, number2, multiple ) ) print( '{0:^6} / {1:^6} = {2:<6.2f}'.format( number1, number2, divide ) ) # =========๋ฌธ์ž์—ด ์‹ค์Šต๊ณผ์ œ==============# # 1๋ฒˆ a = 'hong gil dong201912121623210' num = a.find('20191212') #13 name ='Name : '+ (a[:13]) birthday ='Birthday : ' + (a[13:17] + '/' + a[17:19] + '/' + a[19:21]) id_number ='ID Number : ' + (a[13:21] + '-' + a[21:28]) print(name) print(birthday) print(id_number) # 2๋ฒˆ a = 'PythonProgramming' s2 = (a[:6]) s1 = (a[6:]) s3 = s1 + s2 print(s3) # 3๋ฒˆ s = 'hello world' a = s.replace('hello', 'hi') print(a) # =========[ list ์‹ค์Šต๊ณผ์ œ ]==============# # 1๋ฒˆ a = input('a:') b = input('b:') list = ['+', '-', '*', '/'] op_select = int( input( 'Input operator( 1:+, 2:-, 3:*, 4:/ ) : ' ) ) c = list[op_select-1] #์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋˜ ๊ฐœ๋… eval(a+c+b) print(eval) # 2๋ฒˆ n = int(input('n :'))+1 a = range(1,n) #range๋Š” list๋กœ ํ•˜๋ฉด ์•ˆ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  n์€ ๋ฌธ์ž์—ด์ด๋ฏ€๋กœ ์ˆซ์ž์—ด๋กœ ๋ฐ”๊ฟ”์ค˜์•ผ ํ•œ๋‹ค. print(sum(a)) # 3๋ฒˆ # 1 ~ n๊นŒ์ง€ ์ง์ˆ˜ํ•ฉ๊ณผ ํ™€์ˆ˜ํ•ฉ์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ž‘์„ฑํ•˜์‹œ์˜ค. # (์ตœ๋Œ€๊ฐ’ n์„ input()ํ•จ์ˆ˜๋กœ ์ž…๋ ฅ ๋ฐ›์•„ ์‚ฌ์šฉํ•˜์„ธ์š”) n = int(input('n:'))+1 #์ˆซ์ž์—ด๊ณผ ๋ฌธ์ž์—ด์„ ๋ถ„๋ช…ํžˆ ๊ตฌ๋ถ„ํ•˜๊ธฐ a = range(1,int(n),2) print('ํ™€์ˆ˜ํ•ฉ',sum(a)) a = range(0,int(n),2) print('์ง์ˆ˜ํ•ฉ',sum(a)) # 4๋ฒˆ # 1 ~ n๊นŒ์ง€ 3์˜ ๋ฐฐ์ˆ˜์™€ 5์˜ ๋ฐฐ์ˆ˜๋ฅผ ์ œ์™ธํ•œ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๊ณ  ๊ทธ ํ•ฉ์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. # (์ตœ๋Œ€๊ฐ’ n์„ input()ํ•จ์ˆ˜๋กœ ์ž…๋ ฅ ๋ฐ›์•„ ์‚ฌ์šฉํ•˜์„ธ์š”) # ํ’€์ด 1๋ฒˆ์งธ n = input('n:') a = range(1,int(n)) # ํŒŒ์ด์ฌ์€ tab์œผ๋กœ ๋“ค์—ฌ์“ฐ๊ธฐ๊ฐ€ ์ค‘์š”. list=[] # ๋ฆฌ์ŠคํŠธ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ฌ. for b in a : # for ๋ณ€์ˆ˜ in ๋ฆฌ์ŠคํŠธ : if b%3!=0 and b%5!=0 : # if ์—์„œ true๋ฉด ๋ฐ”๋กœ ๋ฐ‘์— ์ค„๋กœ ์ด๋™. list.append(b) # .append๋กœ ์ถ”๊ฐ€ print(sum(list)) # ํ’€์ด 2๋ฒˆ์งธ n = int(input('n:'))+1 # n์˜ ๊ฐ’์„ ์ž…๋ ฅํ•˜๋Š”๋ฐ ์ˆซ์ž์—ด๋กœ ๋ฐ”๊ฟ”์ฃผ๊ณ  range๋ฅผ ์˜์‹ํ•ด์„œ +1๋กœ a = range(1,n) # range ๋ฒ”์œ„๋ฅผ ์„ค์ • c = 0 # ๋ฆฌ์ŠคํŠธ ๋Œ€์‹  ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค๊ณ  ์‹ถ์œผ๋ฉด 0์˜ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค for b in a: # for ๋ฌธ์€ in ๊ณผ ํ•จ๊ป˜ for ์ƒˆ๋กœ์šด ๋ณ€์ˆ˜ in ๋ฆฌ์ŠคํŠธ if b%3!=0 and b%5!=0 : # 3์˜ ๋ฐฐ์ˆ˜๊ฐ€ ์•„๋‹ˆ๊ณ  5์˜ ๋ฐฐ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฉด true, true๊ฐ€ ๋‚˜์˜ค๋ฉด ๋ฐ”๋กœ ๋ฐ‘์œผ๋กœ ๊ฐ„๋‹ค. ๋‚˜๋จธ์ง€๋Š” ๋ฒ„๋ฆผ c = c+b # ๋‚˜์˜ค๋Š” b๊ฐ’์— c๊ฐ’์„ ๊ณ„์†ํ•ด์„œ ์ถ”๊ฐ€ํ•˜์—ฌ ๋”ํ•œ๋‹ค. sum ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๊ดœ์ถ˜ print(c) print('5์˜ ๋ฐฐ์ˆ˜๊ฐ€ ์•„๋‹Œ ๊ฒƒ์˜ ํ•ฉ',sum(list_1)) # ========================LIST์‹ค์Šต๋ฌธ์ œ/๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ=========================================================== # 1๋ฒˆ ๋‹ต์•ˆ print( '{0:=^50}'.format( '4' ) ) op = [ '+', '-', '*', '/' ] number1 = input( 'Input number1 : ' ) number2 = input( 'Input number2 : ' ) op_select = int( input( 'Input operator( 1:+, 2:-, 3:*, 4:/ ) : ' ) ) index = op_select - 1 result = eval( number1 + op[ index ] + number2 ) print() print( 'number1 : {0:^8.2}'.format( number1 ) ) print( 'number2 : {0:^8.2}'.format( number2 ) ) print( '{0:^6} {2:^3} {1:^6} = {3:<.2f}'.format( number1, number2, op[ index ], result ) ) # 2๋ฒˆ ๋‹ต์•ˆ print( '{0:=^50}'.format( '5' ) ) max_number = int( input( 'Input max number : ' ) ) l = list( range( 1, max_number + 1 ) ) print() print( l ) print( '1 ~ {0:^6} = {1:<8}'.format(max_number, sum( l ))) # 3๋ฒˆ ๋‹ต์•ˆ print( '{0:=^50}'.format( '6' ) ) max_number = int( input( 'Input max number : ' ) ) even = list( range( 2, max_number + 1, 2 ) ) odd = list( range( 1, max_number + 1, 2 ) ) print() print( 'even number : ', even ) print( '1 ~ {0:^6} = {1:<8}\n'.format( max_number, sum( even ) ) ) print( 'odd number : ', odd ) print( '1 ~ {0:^6} = {1:<8}'.format( max_number, sum( odd ) ) ) # 4๋ฒˆ ๋‹ต์•ˆ print( '{0:=^50}'.format( '7' ) ) max_number = int( input( 'Input max number : ' ) ) l3 = [ x for x in range( 1, max_number + 1 ) if x % 3 == 0 ] l5 = [ x for x in range( 1, max_number + 1 ) if x % 5 == 0 ] l = [ x for x in range( 1, max_number + 1 ) if x % 3 != 0 and x % 5 != 0 ] print() print( 'Multiple of 3 : ', l3, '\n' ) print( 'Multiple of 5 : ', l5, '\n' ) print( 'Excluding Multiple of 3 and 5 : ', l ) print( 'sum = {0:<6}'.format( sum( l ) ) ) # ====================ํŠœํ”Œ๋ฌธ์ œ========================= # 1๋ฒˆ a=('a1','a2','a3','a4') b=('b1','b2','b3','b4') # (1) q, w, e, r ๋ณ€์ˆ˜์— ํŠœํ”Œ a์˜ ๊ตฌ์„ฑ์š”์†Œ๋“ค์„ ์ฐจ๋ก€๋Œ€๋กœ ํ•˜๋‚˜์”ฉ ๋„ฃ์œผ์‹œ์˜ค.(ex) q='a1' q = a[0] print(q) w = a[1] print(w) e = a[2] print(e) r = a[3] print(r) # 1 q, w, e, r = ('a1','a2','a3','a4') print(q,w,e,r) # (2) a์™€ b๋ฅผ ๋”ํ•œ ๊ฐ’์„ c์— ๋„ฃ์–ด๋ณด์„ธ์š” c = (a+b) print(c) # (3) c์˜ 3๋ฒˆ์งธ ์ž๋ฆฌ์˜ ๊ตฌ์„ฑ์š”์†Œ๋Š” ๋ฌด์—‡์ธ๊ฐ€? print(c[2]) # (4) 6๋ฒˆ์งธ ๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ๊ตฌ์„ฑ์š”์†Œ๋Š” ๋ฌด์—‡์ธ๊ฐ€? print(c[5:]) # (5) ์ฒ˜์Œ๋ถ€ํ„ฐ 3๋ฒˆ์งธ์˜ ๊ตฌ์„ฑ์š”์†Œ๋Š” ๋ฌด์—‡์ธ๊ฐ€? print(c[:3]) # (6) 4๋ฒˆ์งธ ๊ตฌ์„ฑ์š”์†Œ ์ œ๊ฑฐํ•ด ๋ณด์„ธ์š” ==>์—๋Ÿฌ ๋ฐœ์ƒ del a[3] # (7) 5๋ฒˆ์งธ ๊ตฌ์„ฑ์š”์†Œ์˜ ๊ฐ’์„ 'c1'๋กœ ์ˆ˜์ •ํ•ด๋ณด์„ธ์š” ==>์—๋Ÿฌ ๋ฐœ์ƒ c[4] = 'c1' c.replace(c[4], 'c1') #======================= ํŠœํ”Œ์‹ค์Šต๋ฌธ์ œ.๊ฐ•์‚ฌ๋‹˜ ์ •๋‹ต ============================== a=('a1','a2','a3','a4') b=('b1','b2','b3','b4') # 1,์–ธํŒจํ‚น q, w, e, r = ('a1','a2','a3','a4') print(q,w,e,r) # 2, + ์—ฐ์‚ฐ c = a + b print(c) # 3, ์ธ๋ฑ์‹ฑ print(c[2]) # 4, ์Šฌ๋ผ์ด์‹ฑ print(c[5:]) # 5, ์Šฌ๋ผ์ด์‹ฑ print(c[:3]) # 6 del a[3] # TypeError: 'tuple' object doesn't support item deletion #7, c[4] = 'c1' # TypeError: 'tuple' object does not support item assignment # ======dic ์—ฐ์Šต๋ฌธ์ œ============== srp={'๊ฐ€์œ„':'๋ณด','๋ฐ”์œ„':'๊ฐ€์œ„','๋ณด':'๋ฐ”์œ„'} # (1) srp์˜ key list ์ƒ์„ฑ x = srp.keys() # (2) srp์˜ value list ์ƒ์„ฑ y= srp.values() # (3) srp์˜ key์™€ value ์˜ ํ•œ์Œ์œผ๋กœ๋œ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ srp.items() # (4) srp์˜ key '๊ฐ€์œ„'์— ํ•ด๋‹นํ•˜๋Š” value ์ถœ๋ ฅ srp.get('๊ฐ€์œ„') # (5) srp์˜ value '๋ฐ”์œ„'์— ํ•ด๋‹นํ•˜๋Š” key ์ถœ๋ ฅ for key, value in srp.items(): if value == '๋ฐ”์œ„': print(key) type(key) # <class 'str'> x = [key for key, value in srp.items() if value == '๋ฐ”์œ„'] # pop() ์‚ฌ์šฉ print(x) type(x) # (6) srp์— '์ฐŒ':'๋น ', '๋ฌต':'์ฐŒ', '๋น ':'๋ฌต' ์ถ”๊ฐ€ x = {'์ฐŒ':'๋น ', '๋ฌต':'์ฐŒ', '๋น ':'๋ฌต'} srp.update(x) print(srp) # (7) srp ๋ณด์ž๊ธฐ ๋ผ๋Š” ํ‚ค๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ '๋ณด์ž๊ธฐ' in srp # False # (8) srp์˜ key ์™€ value๋ฅผ ์„œ๋กœ ๋ฐ”๊พธ์–ด์„œ ์ƒˆ๋กœ์šด ์‚ฌ์ „ srp2๋ฅผ ์ƒ์„ฑ srp2 = {y:x for x,y in zip(x,y)} # dic={}, ๋‚ด์žฅํ•จ์ˆ˜๊ฐ€ ์ž๋ฃŒํ˜•์— ๊ฐ์‹ธ์žˆ์–ด์•ผ ์ œ๊ธฐ๋Šฅ ๊ฐ€๋Šฅ. print(srp2) # ๋ณ€์ˆ˜ ์ด๋ฆ„์„ ๋‹ค๋ฅด๊ฒŒ type(srp2) # <class 'dict'> # comprehension ์€ list, dic์— ๋”ฐ๋ผ ๊ด„ํ˜ธ๊ฐ€ ๋‹ฌ๋ผ์ง„๋‹ค. list=[], dic={} # ๋‚ด์žฅํ•จ์ˆ˜๋Š” ๊ธฐ์กด์˜ for ๋ฌธ ๋“ฑ๊ณผ ๋น„๊ตํ•˜์—ฌ ์ฒ˜๋ฆฌ ์†๋„๊ฐ€ ๋น„๊ต๊ฐ€ ์•ˆ๋œ๋‹ค. #===================== DICT์‹ค์Šต๋ฌธ์ œ_๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ========================================== # srp = {'๊ฐ€์œ„':'๋ณด','๋ฐ”์œ„':'๊ฐ€์œ„','๋ณด':'๋ฐ”์œ„'} # 1 print(list(srp.keys())) # 2 print(list(srp.values())) # 3 print(list(srp.items())) # 4 print(srp['๊ฐ€์œ„']) # 5 # ํŒŒ์ด์„  ์Šคํƒ€์ผ ๋ฐฉ์‹ a = [x for x,y in srp.items() if y == '๋ฐ”์œ„'] print(a[0]) # ์ „ํ†ต์ ์ธ ์–ธ์–ด์˜ ๋ฐฉ์‹ for x,y in srp.items(): if y == '๋ฐ”์œ„': a = x print('key =',a) # 6 b = {'์ฐŒ':'๋น ', '๋ฌต':'์ฐŒ', '๋น ':'๋ฌต'} srp.update(b) print(srp) # 7 print('๋ณด์ž๊ธฐ' in srp) # 8 # ํŒŒ์ด์„  ์Šคํƒ€์ผ ๋ฐฉ์‹ #srp = {1: '๋ณด',2:'๋ฐ”์œ„', 3:'๊ฐ€์œ„', 4:'๋ฌต', 5:'์ฐŒ', 6:"๋น "} srp2 = { y:x for x,y in srp.items() } print(srp2) # ์ „ํ†ต์ ์ธ ์–ธ์–ด์˜ ๋ฐฉ์‹ srp2 = {} for x,y in srp.items(): srp2.update({y:x}) print('srp2 =',srp2) # =================[์ง‘ํ•ฉ์‹ค์Šต]============================ # (1) a = [1,2,3,4] ๋กœ set s1์„ ์ƒ์„ฑํ•˜์‹œ์˜ค. b = "aabbccddeeff"๋กœ set s2๋ฅผ ์ƒ์„ฑํ•˜์‹œ์˜ค. s1 = {1,2,3,4} s2 = {'aabbccddeeff'} type(s2) # (2) s1 ์— a,b,c ๋ฅผ ์ถ”๊ฐ€ํ•˜์‹œ์˜ค. s1.update({'a,b,c'}) print(s1) # (3) s2 ์— 1,2๋ฅผ ์ถ”๊ฐ€ํ•˜์‹œ์˜ค. s2.update({1,2}) print(s2) # (4) s1๊ณผ s2์˜ ๊ต์ง‘ํ•ฉ์„ ๊ตฌํ•˜์‹œ์˜ค.(2๊ฐ€์ง€ ๋ฐฉ๋ฒ• ๋ชจ๋‘ ) s1 & s2 s1.intersection(s2) # (5) s1๊ณผ s2์˜ ํ•ฉ์ง‘ํ•ฉ์„ ๊ตฌํ•˜์‹œ์˜ค.(2๊ฐ€์ง€ ๋ฐฉ๋ฒ• ๋ชจ๋‘) s1.union(s2) s1 | s2 # (6) s1๊ณผ s2์˜ ์ฐจ์ง‘ํ•ฉ์„ ๊ตฌํ•˜์‹œ์˜ค.(๊ธฐํ˜ธ) s1 - s2 # (7) s2์™€ s1์˜ ์ฐจ์ง‘ํ•ฉ์„ ๊ตฌํ•˜์‹œ์˜ค.(ํ•จ์ˆ˜) s1.difference(s2) # (8) s2์—์„œ 1์„ ๋นผ๋ณด์„ธ์š”. s2.remove(1) print(s2) # (9) s1๊ณผ s2์˜ ๋Œ€์นญ ์ฐจ์ง‘ํ•ฉ์„ ๊ตฌํ•˜์‹œ์˜ค. s1.symmetric_difference(s2) # =======์—ฐ์Šต๋ฌธ์ œ_112p============================ # ๋ฌธ์ œ 1๋ฒˆ # ํ™๊ธธ๋™ ์”จ์˜ ํ‰๊ท  ์ ์ˆ˜๋Š”? k = 80 e = 75 m = 55 mean = (k+e+m)/3 print(mean) # ๋ฌธ์ œ 2๋ฒˆ # ์ž์—ฐ์ˆ˜ 13์ด ํ™€์ˆ˜์ธ์ง€ ์ง์ˆ˜์ธ์ง€ ํŒ๋ณ„ํ•˜๋ผ a = 13 if a % 2 == 0: print('์ง์ˆ˜') else : print('ํ™€์ˆ˜') # ๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ num = 13 even_odd = ['์ง์ˆ˜', 'ํ™€์ˆ˜'] print("%d : %s"%(num,even_odd[num%2])) # ์ธ๋ฑ์Šค๋กœ ์ถœ๋ ฅ print("%d ์€ %s ์ž…๋‹ˆ๋‹ค."%(num,even_odd[num%2])) # ๋ฌธ์ œ 3๋ฒˆ # ํ™๊ธธ๋™ ์ฃผ๋ฏผ 881120-1068234 ๋‚˜๋ˆ„์–ด ๋ณด์ž pin = '8811201068234' yyyymmdd=pin[:6] print(yyyymmdd) num = pin[6:] print(num) # ๋ฌธ์ œ 4๋ฒˆ # ์ฃผ๋ฏผ ์„ฑ๋ณ„์„ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆซ์ž ์ถœ๋ ฅ g = ['๋‚จ์ž','์—ฌ์ž'] pin = '8811202068234' print(g[int(pin[6])-1]) # ๋ฌธ์ œ 5๋ฒˆ # replace๋ฅผ ์จ์„œ ๋ฐ”๊ฟ”๋ณด์ž! a = "a:b:c:d" b = a.replace(':','#') print(b) # ๋ฌธ์ œ 6๋ฒˆ # ๋ฆฌ์ŠคํŠธ ๋ณ€ํ™˜! a = [1,3,5,4,2] a.sort() print(a) a.reverse() print(a) # ๋ฌธ์ œ 7๋ฒˆ # ๋ฌธ์ž์—ด๋กœ ์ถœ๋ ฅ! a = ['life', 'is', 'too', 'short'] result = ' '.join(a) print(result) # ๋ฌธ์ œ 8๋ฒˆ # ํŠœํ”Œ ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜์ž! a = (1,2,3) a1 = (4,) a3 = a.__add__(a1) print(a3) # ๋ฌธ์ œ 9๋ฒˆ # ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์ด์œ ๋ฅผ ์ฐพ์ž a = dict() a type(a) a[[1]] = 'python' # ๋ฌธ์ œ 10๋ฒˆ # B๊ฐ’ ์ถ”์ถœ a = {'A':90, 'B':80, 'C':70} result = a.pop('B') print(a) print(result) # ๋ฌธ์ œ 11๋ฒˆ # ์ค‘๋ณต ์ œ๊ฑฐ a = [1,1,1,2,2,3,3,3,4,4,5] x = set(a) b = list(x) print(b) # ๋ฌธ์ œ 12๋ฒˆ # ๊ฒฐ๊ณผ ์ด์œ  ์„ค๋ช… a = b = [1,2,3] a[1] = 4 print(b) # ์ฐธ์กฐ ์ฃผ์†Œ๊ฐ€ ์„œ๋กœ ๊ฐ™๋‹ค. ํ‚ค๋งŒ ์„œ๋กœ ๋ณต์‚ฌ # ์„œ๋กœ ๊ฐ€์ ธ๋‹ค ์“ด๋‹ค # ๏ปฟ[ ์ œ์–ด๋ฌธ ์‹ค์Šต๊ณผ์ œ ] =========================================== # 1 ๋ฒˆ # 1-1 for x in range(1,101): if x%10 != 0: print(x, end =',') else : print(x) # 1-2_์ผ๋‹จ ํŒจ์Šค l = list(range(1,101)) x = [a for a in l if l%10 != 0] print(x, end =',') # 2๋ฒˆ n = input('n=') a = range(1, int(n)+1) list = [] for b in a: list.append(b) print('์ดํ•ฉ=',sum(list)) # 3๋ฒˆ n = input('n=') a = range(1,int(n)+1) list1=[] # ๋ฌด์Šจ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์ง€ ๋จผ์ € ์ƒ๊ฐ, ์ œ์–ด๋ฌธ ์•ˆ์— ๋“ค์–ด๊ฐ€๋ฉด ์‚ญ์ œ๋˜๋‹ˆ๊นŒ ๊ทธ ๋ฐ–์— ๋‘”๋‹ค. list2=[] for b in a: if b%2==0 : list1.append(b) else : b%2!=0 list2.append(b) print('์ง์ˆ˜์˜ ํ•ฉ=',sum(list1)) print('ํ™€์ˆ˜์˜ ํ•ฉ=',sum(list2)) # ์žฌ๋ฏผ's ๋‹ต n = input('n=') a = range(1,int(n)+1) n = input('n=') a = range(1,int(n)+1) ak = 0 bk = 0 count = 0 for b in a: if b%2==0 : ak = ak + b count = count +1 else : b%2!=0 list2.append(b) print('์ง์ˆ˜์˜ ํ•ฉ=',ak) print('ํ™€์ˆ˜์˜ ํ•ฉ=',sum(list2)) # 4๋ฒˆ n = input('n=') a = range(1,int(n)+1) list = [] for b in a: if b%3 != 0 and b%5 != 0: list.append(b) print(sum(list)) # 5๋ฒˆ # 5-1 for x in range(2,10): for y in range(1,10): print('{}*{}={} '.format(x,y,x*y)) # 6๋ฒˆ n = 0 count1 = 0 count2 = 0 count3 = 0 while n != -999: n = int(input('n=')) if n<0: count1 = count1 + 1 else : n>0 if n%2==0: count2 = count2 + 1 else : n%2!=0 count3 = count3 + 1 print('์Œ์ˆ˜์˜ ๊ฐœ์ˆ˜=',count1) print('์–‘์ˆ˜ ํ™€์ˆ˜์˜ ๊ฐœ์ˆ˜=',count2) print('์–‘์ˆ˜ ์ง์ˆ˜์˜ ๊ฐœ์ˆ˜=',count3) # ๋ฌธ์ œ 7๋ฒˆ dict = {1:'+', 2:'-', 3:'*', 4:'/'} type(dict) a = input('a=') b = input('b=') c = input(dict) result = eval(a+c+b) print(result) a = input('a:') b = input('b:') list = ['+', '-', '*', '/'] op_select = int( input( 'Input operator( 1:+, 2:-, 3:*, 4:/ ) : ' ) ) c = list[op_select-1] #์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋˜ ๊ฐœ๋… result = eval(a+c+b) print(result) # ==================================๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ================================================ # ์ œ์–ด๋ฌธ์‹ค์Šต.py # 1๋ฒˆ print('{0:=^50}'.format('1-1')) for x in range(1, 101): print('{:4}'.format(x), end='') if x % 10 == 0: print() print('{0:=^50}'.format('1-2')) l = [x for x in range(1, 101)] for x in l: print('{:4}'.format(x), end='') if x % 10 == 0: print() # 2๋ฒˆ print('{0:=^50}'.format('2')) max_number = int(input('Input max number : ')) total = 0 for x in range(1, max_number + 1): total = total + x print('1 ~ {0:^6} = {1:<8}'.format(max_number, total)) # 3๋ฒˆ print('{0:=^50}'.format('3')) max_number = int(input('Input max number : ')) even_list = [] odd_list = [] for x in range(1, max_number + 1): if x % 2 == 0: even_list.append(x) else: odd_list.append(x) print('even number : ', even_list) print('1 ~ {0:^6} = {1:<8d}\n'.format(max_number, sum(even_list))) print('odd number : ', odd_list) print('1 ~ {0:^6} = {1:<8d}'.format(max_number, sum(odd_list))) # 4๋ฒˆ print('{0:=^50}'.format('4')) max_number = int(input('Input max number : ')) Excluding_Multiple_of_3_5 = [] for x in range(1, max_number + 1): if x % 3 != 0 and x % 5 != 0: Excluding_Multiple_of_3_5.append(x) print('Excluding Multiple of 3 and 5 : ', Excluding_Multiple_of_3_5) print('sum = {0:<6}'.format(sum(Excluding_Multiple_of_3_5))) # 5๋ฒˆ print('{0:=^50}'.format('5-1')) for x in range(2, 10): for y in range(1, 10): print('{:3}'.format(x * y), end='') print() print('{0:=^50}'.format('5-2')) multiple_table = [x * y for x in range(2, 10) for y in range(1, 10)] count = 0 for x in range(8 * 9): count = count + 1 print('{:3}'.format(multiple_table[x]), end='') if count % 9 == 0: print() count = 0 print('{0:=^50}'.format('5-3')) multiple_table2 = [x * y for x in range(2, 10) for y in range(1, 10)] start = 0 for x in range(9, 81, 9): print('{0[0]:3}{0[1]:3}{0[2]:3}{0[3]:3}{0[4]:3}{0[5]:3}{0[6]:3}{0[7]:3}{0[8]:3}' \ .format(multiple_table2[start:x])) start = start + 9 # 6๋ฒˆ print('{0:=^50}'.format('6')) total_list = [0, 0, 0, 0] total_title = ('positive', 'negative', 'even', 'odd') while True: number = int(input('Input number : ')) if number == -999: break if number != 0: if number > 0: total_list[0] = total_list[0] + 1 if number % 2 == 0: total_list[2] = total_list[2] + 1 else: total_list[3] = total_list[3] + 1 else: total_list[1] = total_list[1] + 1 else: print('error : input not {}'.format(number)) print() for x in range(4): print('{0:<10} : {1:<5}'.format(total_title[x], total_list[x])) # 7๋ฒˆ print('{0:=^50}'.format('7')) op = {1: '+', 2: '-', 3: '*', 4: '/'} while True: number1 = input('Input number1 : ') number2 = input('Input number2 : ') op_select = int(input('Input operator( 1:+, 2:-, 3:*, 4:/, 0:end ) : ')) if op_select == 0: break; result = eval(number1 + op[op_select] + number2) print('number1 : {0:^8.2}'.format(number1)) print('number2 : {0:^8.2}'.format(number2)) print('{0:^6} {2:^3} {1:^6} = {3:<.2f}\n'.format(number1, number2, op[op_select], result)) # 8๋ฒˆ print('{0:=^50}'.format('8')) from collections import namedtuple Student = namedtuple('Student', 'name, subject1, subject2, subject3, total, average, grade') student_list = [] MAX = 10 SUBJECT = 3 count = 0 name = input('Input name : ') while name != 'end' and count < MAX: count = count + 1 subject = [] for x in range(SUBJECT): input_subject = int(input('Input subject' + str(x) + ':')) subject.append(input_subject) total = sum(subject) average = total / SUBJECT if average >= 90: grade = 'Excellent' elif average <= 50: grade = 'Fail' else: grade = ' ' student = Student(name, subject[0], subject[1], subject[2], total, average, grade) student_list.append(student) name = input('Input name : ') print() for x in student_list: print('{0:<10} {1:<3} {2:<3} {3:<3} {4:<5} {5:6.2f} {6:<10}'. \ format(x.name, x.subject1, x.subject2, x.subject3, x.total, x.average, x.grade)) # [ํ•จ์ˆ˜ ์‹ค์Šต๊ณผ์ œ]==================================================================================== # 1. ๋‘ ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ ๋ฐ›์•„ ํ‰๊ท ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ (์ฒซ ๋ฒˆ์งธ ์ˆ˜๊ฐ€ -1 ์ด๋ฉด ์ข…๋ฃŒ) a = int(input('a= ')) b = int(input('b= ')) def mean_0(a,b): if a != -1: c = (a + b)/2 return c print(mean_0(a,b)) # 2. ์ž…๋ ฅ ๋ฐ›์€ ๋‚ด์šฉ์„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ ํ›„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ „๋‹ฌ๋ฐ›์•„ ์ตœ๋Œ€๊ฐ’๊ณผ ์ตœ์†Œ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ ์ž‘์„ฑ # (-1์ด ์ž…๋ ฅ๋  ๋•Œ ๊นŒ์ง€ ์ž…๋ ฅ ๋ฐ›์•„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ) def worhkd_1(): l=[] while True: n = int(input('์ž…๋ ฅ = ')) if n == -1: break l.append(n) l.sort() print(l) return('์ตœ์†Ÿ๊ฐ’ = ', l[0]),('์ตœ๋Œ€๊ฐ’ = ', l[-1]) print(worhkd_1()) # ์ˆœ์„œ๋ฅผ ์ž˜ ์ƒ๊ฐํ•˜์ž # ํ•จ์ˆ˜ ์ด์šฉ ๋ฐฉ๋ฒ• def worhkd1(): l = [] while True: n = int(input('์ž…๋ ฅ=')) l.append(n) if n == -1: break return ('์ตœ์†Ÿ๊ฐ’=',min(l)),('์ตœ๋Œ€๊ฐ’=',max(l)) print(worhkd1()) # 3. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ์‹œ์ž‘๊ณผ ๋ ์ˆซ์ž๋ฅผ ๋ฐ›์•„ ์‹œ์ž‘๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ๋ชจ๋“  ์ •์ˆ˜๊ฐ’์˜ ํ•ฉ์„ # ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ(์‹œ์ž‘๊ฐ’๊ณผ ๋๊ฐ’์„ ํฌํ•จ). a = int(input('์‹œ์ž‘๊ฐ’=')) b = int(input('๋๊ฐ’=')) l = [] def worhkd2(): for c in range(a, b+1): l.append(c) d = sum(l) return d print(worhkd2()) # 4. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๋ฌธ์ž์—ด์„ ํฌํ•จํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ž…๋ ฅ๋  ๋•Œ ๊ฐ ๋ฌธ์ž์—ด์˜ ์ฒซ ์„ธ ๊ธ€์ž๋กœ๋งŒ # ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ. # ์˜ˆ๋ฅผ ๋“ค์–ด, ํ•จ์ˆ˜์˜ ์ž…๋ ฅ์œผ๋กœ ['Seoul', 'Daegu', 'Kwangju', 'Jeju']๊ฐ€ ์ž…๋ ฅ # ๋  ๋•Œ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์€ ['Seo', 'Dae', 'Kwa', 'Jej']('end' ์ž…๋ ฅ์‹œ ์ž…๋ ฅ ์ข…๋ฃŒ) dic = {'Seoul':'Seo' , 'Daegu' : 'Dae' , 'Kwangju' : 'Kwa' , 'Jeju': 'Jej'} def rhkd1(dic): while True: n = input('๋„์‹œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”') print(dic[n]) if n == 'end' : return '๋์ด ๋‚ฌ์Šต๋‹ˆ๋‹ค' break return dic[n] print(rhkd1(dic)) # 4๊ฐ€์ง€ ์œ ํ˜•์„ ๊ณต๋ถ€ # 5. range() ํ•จ์ˆ˜ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” myrange() ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ # (์ธ์ž๊ฐ€ 1,2,3๊ฐœ์ธ ๊ฒฝ์šฐ๋ฅผ ๋ชจ๋‘๊ตฌํ˜„ return ๊ฐ’์€ ํŠœํ”Œ ) # (range() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉ, ๋‹จ ์ธ์ž ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋Š” ๋ฐ˜๋“œ์‹œ ๊ตฌํ˜„) def myrange(*worhkd): if len(worhkd) == 1: range(0,worhkd[0]) a = tuple([a for a in range(worhkd[0])]) return a elif len(worhkd) == 2: range(worhkd[0],worhkd[-1]) b = tuple([b for b in range(worhkd[0],worhkd[-1])]) return b else: len(worhkd) == 3 range(worhkd[0],worhkd[1],worhkd[2]) c = tuple([c for c in range(worhkd[0],worhkd[1],worhkd[2])]) return c print(myrange(1,8,2)) # <๊ณ ๊ธ‰> # 6. ํ™”๋ฉด์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฉ”๋‰ด๋ฅผ ์ถœ๋ ฅํ•˜์—ฌ ์„ ํƒ๋œ # ๋ฉ”๋‰ด์˜ ๊ธฐ๋Šฅ(๋‘์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์—ฐ์‚ฐ)์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ # 1.add # 2.subtract # 3.multiply # 4.divide # 0.end # select : worhkd1 = {1:'add', 2:'subtract',3:'multiply',4:'divide',0:'end'} print(worhkd1) def worhkd0(): worhkd1 = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide', 0: 'end'} while True: print(worhkd1) a = int(input('์ˆซ์ž ์ž…๋ ฅ = ')) b = int(input('์ˆซ์ž ์ž…๋ ฅ = ')) worhkd2 = {1: a + b, 2: a - b, 3: a * b, 4: a / b, 0: 'end'} x = worhkd2[int(input('์—ฐ์‚ฐ์ž'))] print(x) print(worhkd0()) # <๊ธฐ๋ณธ> # 1. ๋‘ ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ ๋ฐ›์•„ ํ‰๊ท ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ # (์ฒซ ๋ฒˆ์งธ ์ˆ˜๊ฐ€ -1 ์ด๋ฉด ์ข…๋ฃŒ) a = int(input('a = ')) b = int(input('b = ')) def worhkdTm(a,b): c = (a+b)/2 return c print(worhkdTm(a,b)) # 2. ์ž…๋ ฅ ๋ฐ›์€ ๋‚ด์šฉ์„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ ํ›„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ „๋‹ฌ๋ฐ›์•„ # ์ตœ๋Œ€๊ฐ’๊ณผ ์ตœ์†Œ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ ์ž‘์„ฑ # (-1์ด ์ž…๋ ฅ๋  ๋•Œ ๊นŒ์ง€ ์ž…๋ ฅ ๋ฐ›์•„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ) # ๊ตณ์ด for ๋ฌธ์ด ํ•„์š”์—†๋‹ค๋ฉด ์“ฐ์ง€ ๋ง์ž def rhkdtm(): l = [] while True: n = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) if n == -1: break l.append(n) l.sort() return ('์ตœ์†Œ๊ฐ’ = ', l[0], '์ตœ๋Œ€๊ฐ’ = ', l[-1]) print(rhkdtm()) # 3. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ์‹œ์ž‘๊ณผ ๋ ์ˆซ์ž๋ฅผ ๋ฐ›์•„ ์‹œ์ž‘๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ # ๋ชจ๋“  ์ •์ˆ˜๊ฐ’์˜ ํ•ฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ # ์ž‘์„ฑ(์‹œ์ž‘๊ฐ’๊ณผ ๋๊ฐ’์„ ํฌํ•จ). (์‹œ์ž‘๊ฐ’์ด ๋๊ฐ’๋ณด๋‹ค ํด๋•Œ ์ž…๋ ฅ ์ข…๋ฃŒ) a = int(input('์‹œ์ž‘ = ')) b = int(input('๋ = ')) l = [] def rhkddl(): for c in range(a, b+1): l.append(c) d = sum(l) return d print (rhkddl()) # 4. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๋ฌธ์ž์—ด์„ ํฌํ•จํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ž…๋ ฅ๋  ๋•Œ # ๊ฐ ๋ฌธ์ž์—ด์˜ ์ฒซ ์„ธ ๊ธ€์ž๋กœ๋งŒ # ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ. # ์˜ˆ๋ฅผ ๋“ค์–ด, ํ•จ์ˆ˜์˜ ์ž…๋ ฅ์œผ๋กœ ['Seoul', 'Daegu', 'Kwangju', 'Jeju']๊ฐ€ ์ž…๋ ฅ # ๋  ๋•Œ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์€ ['Seo', 'Dae', 'Kwa', 'Jej']('end' ์ž…๋ ฅ์‹œ ์ž…๋ ฅ ์ข…๋ฃŒ) dic = {'Seoul':'Seo' , 'Daegu' : 'Dae' , 'Kwangju' : 'Kwa' , 'Jeju': 'Jej'} def goqhwk(dic): while True: n = input('๋„์‹œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.') print(dic[n]) if n == 'end': return('์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.') break return dic[n] print(goqhwk(dic)) # 1. ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋น„๋งŒ๋„๋ฅผ ๊ตฌํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ํ‘œ์ค€์ฒด์ค‘(kg)=(์‹ ์žฅ(cm)-100)ร—0.85 # ๋น„๋งŒ๋„(%)=ํ˜„์žฌ์ฒด์ค‘/ํ‘œ์ค€์ฒด์ค‘(%)ร—100 # ๋น„๋งŒ๋„๊ฐ€90%์ดํ•˜ -->์ €์ฒด์ค‘ # 90์ดˆ๊ณผ~110% --> ์ •์ƒ # 110์ดˆ๊ณผ~120% --> ๊ณผ์ฒด์ค‘ # 120%์ดˆ๊ณผ --> ๋น„๋งŒ a = int(input('ํ‚ค = ')) b = int(input('๋ชธ๋ฌด๊ฒŒ = ')) def bimando(a,b): while True: a = int(input('ํ‚ค = ')) b = int(input('๋ชธ๋ฌด๊ฒŒ = ')) l = (a-100)*0.85 x = b/l*100 if x <= 90: print('๋‹น์‹ ์€ ์ €์ฒด์ค‘์ž…๋‹ˆ๋‹ค.') elif 90 < x <=110: print('๋‹น์‹ ์€ ์ •์ƒ์ž…๋‹ˆ๋‹ค.') elif 110 < x <= 120: print('๋‹น์‹ ์€ ๊ณผ์ฒด์ค‘์ž…๋‹ˆ๋‹ค.') else: x>120 print('๋‹น์‹ ์€ ๋น„๋งŒ์ž…๋‹ˆ๋‹ค.') continue return x print(bimando(a,b)) # 2. ์—ฐ๋„๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ # 1) ์œค๋…„์—ฌ๋ถ€๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ์œค๋…„์˜ ์กฐ๊ฑด # 1-1) 4๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€์ง€๋งŒ 100์œผ๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค ๋˜๋Š” # 1-2) 400 ์œผ๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€๋ฉด ์œค๋…„์ž„ # 2) ๋‚˜์ด๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # 3) ๋ (12์ง€์‹ )๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ("์ฅ","์†Œ","ํ˜ธ๋ž‘์ด","ํ† ๋ผ","์šฉ","๋ฑ€","๋ง","์–‘","์›์ˆญ์ด","๋‹ญ","๊ฐœ","๋ผ์ง€",); # (์„œ๊ธฐ 4๋…„์€ ์ฅ๋ ์ด๋‹ค,2019๋…„ ๋ผ์ง€) def dbssus(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) if n%4 == 0 and n%100 != 0: print('์œค๋…„์ž…๋‹ˆ๋‹ค.') elif n%400 == 0 : print('์œค๋…„์ž…๋‹ˆ๋‹ค.') else : print('์œค๋…„์ด ์•„๋‹™๋‹ˆ๋‹ค.') continue dbssus() def El(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) x = 2019 - n + 1 print('๋‹น์‹ ์˜ ๋‚˜์ด๋Š” {}์ž…๋‹ˆ๋‹ค.'.format(x)) El() # ํ’€์ด 1๋ฒˆ def Elsms(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) if n%12 == 0: print('์›์ˆญ์ด๋ ') elif n%12 == 1: print('๋‹ญ๋ ') elif n%12 == 2: print('๊ฐœ๋ ') elif n%12 == 3: print('๋ผ์ง€๋ ') elif n%12 == 4: print('์ฅ๋ ') elif n%12 == 5: print('์†Œ๋ ') elif n%12 == 6: print('ํ˜ธ๋ž‘์ด๋ ') elif n%12 == 7: print('ํ† ๋ผ๋ ') elif n%12 == 8: print('์šฉ๋ ') elif n%12 == 9: print('๋ฑ€๋ ') elif n%12 == 10: print('๋ง๋ ') else: n%12 == 11 print('์–‘๋ ') continue Elsms() # ํ’€์ด 2๋ฒˆ def ektlgoqha(): a = ["์›์ˆญ์ด", "๋‹ญ", "๊ฐœ", "๋ผ์ง€", "์ฅ", "์†Œ", "ํ˜ธ๋ž‘์ด", "ํ† ๋ผ", "์šฉ", "๋ฑ€", "๋ง", "์–‘"] while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = a[n%12] print(x) return x print(ektlgoqha()) # 3. ์ ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ # 90~100 'A' # 80~89 'B' # 70~79 'C' # 60~69 'D' # ๋‚˜๋จธ์ง€ 'F' # ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) def wjatn(): dic = {range(90, 101): 'A', range(80, 90): 'B', range(70, 80): 'C', range(60, 70): 'D', range(0, 60): 'F'} while True: x = int(input('์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” = ')) if 90<= x <= 100: print([k for x,k in dic.items() if x == range(90,101)]) elif 80<= x <= 89: print([k for x,k in dic.items() if x == range(80, 90)]) elif 70 <= x <= 79: print([k for x,k in dic.items() if x == range(70, 80)]) elif 60 <= x <= 69: print([k for x,k in dic.items() if x == range(60, 70)]) else : x < 60 print([k for x, k in dic.items() if x == range(0, 60)]) wjatn() # srp={'๊ฐ€์œ„':'๋ณด','๋ฐ”์œ„':'๊ฐ€์œ„','๋ณด':'๋ฐ”์œ„'} # print([k for k,v in srp.items() if v == '๋ฐ”์œ„'].pop()) # 4. m(๋ฏธํ„ฐ) ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋งˆ์ผ๋กœ ๋ณ€ํ™˜ํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # (1 mile = 1.609 meter) def qusghks(): while True : n = int(input('m๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = n/1.609 print('{} mile ์ž…๋‹ˆ๋‹ค.'.format(x)) print(qusghks()) # 5. ํ™”์”จ ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์„ญ์”จ๋กœ ๋ณ€ํ™˜ํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # (celsius = ( fahrenheit - 32 ) / 1.8) def ghkTl(): while True: n = int(input('ํ™”์”จ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = (n-32)/1.8 print('{} ์„ญ์”จ ์ž…๋‹ˆ๋‹ค.'.format(x)) print(ghkTl()) # 6. ํ•˜๋‚˜์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์•ฝ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”. # (์–ด๋–ค ์ •์ˆ˜ n์„ ์ž์—ฐ์ˆ˜ k๋กœ ๋‚˜๋ˆ„์–ด ๋‚˜๋จธ์ง€๊ฐ€ 0 ์ผ๊ฒฝ์šฐ k๋Š” ์ •์ˆ˜ n์˜ ์•ฝ์ˆ˜์ด๋‹ค) def wjdtn(): n = int(input('์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) l = [] for k in range(1,n+1): if n%k == 0: l.append(k) print('{}๋Š” {}์˜ ์•ฝ์ˆ˜์ž…๋‹ˆ๋‹ค'.format(l,n)) print(wjdtn()) # 7. 2๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ ˆ๋Œ€๊ฐ’์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š” # ( abs()ํ•ฉ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๊ตฌํ˜„ํ•œ๋‹ค) def wjfeorkqt(): a = int(input('a =')) b = int(input('b =')) if a < 0 : a = -a if b < 0 : b = -b x = a+b return(x) print(wjfeorkqt()) # 8. map ํ•จ์ˆ˜์™€ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” mymap ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜์‹œ์š” # # <map()ํ•จ์ˆ˜์˜ ๊ธฐ๋Šฅ> # def multi_two(x): # return x*2 # result = map(multi_two,[1,2,3,4,5]) # print(list(result)) # ์ถœ๋ ฅ ๊ฒฐ๊ณผ :[2, 4, 6, 8, 10] # ===================๊ฐ•์‚ฌ ๋‹ต์•ˆ========================================== # ํ•จ์ˆ˜์ถ”๊ฐ€๊ณผ์ œ๋ฌธ์ œ.py # 1๋ฒˆ print('{0:=^50}'.format(' 1๋ฒˆ ')) def calc_fat_ratio(height,weight): std_weight = (height - 100) * 0.85 fat_ratio = (weight/std_weight)*100 if fat_ratio <= 90: fat_grade = '์ €์ฒด์ค‘' elif fat_ratio > 90 and fat_ratio <= 110: fat_grade = '์ •์ƒ' elif fat_ratio > 110 and fat_ratio <= 120: fat_grade = '๊ณผ์ฒด์ค‘' else: fat_grade = '๋น„๋งŒ' return fat_ratio,fat_grade def get_health_info(): height = int(input('Your Height(cm):')) weight = int(input('Your Weight(kg):')) fat_ratio,fat_grade = calc_fat_ratio(height,weight) print('ํ‚ค : {0:3}cm ๋ชธ๋ฌด๊ฒŒ: {1:3}kg'.format(height,weight)) print('๋น„๋งŒ๋„ : {0:>5.1f}% ({1})'.format(fat_ratio,fat_grade)) # get_health_info() # 2๋ฒˆ def get_leap_year(year): if (year % 4 == 0 and year % 100 !=0) \ or (year % 400 == 0): return '์œค๋…„' return 'ํ‰๋…„' def get_age(year,current_year): age = current_year - year + 1 return age # 12์ง€ # ๅญ(์ž/์ฅ) ไธ‘(์ถ•/์†Œ) ๅฏ…(์ธ/ํ˜ธ๋ž‘์ด) ๅฏ(๋ฌ˜/ํ† ๋ผ) # ่พฐ(์ง„/์šฉ) ๅทณ(์‚ฌ/๋ฑ€) ๅˆ(์˜ค/๋ง) ๆœช(๋ฏธ/์–‘) # ็”ณ(์‹ /์›์ˆญ์ด) ้…‰(์œ /๋‹ญ) ๆˆŒ(์ˆ /๊ฐœ) ไบฅ(ํ•ด/๋ผ์ง€). # ์„œ๊ธฐ 4๋…„ : ๅญ(์ž/์ฅ) def get_12_animals(year): animals = ['ๅญ(์ž/์ฅ)', 'ไธ‘(์ถ•/์†Œ)', 'ๅฏ…(์ธ/ํ˜ธ๋ž‘์ด)', 'ๅฏ(๋ฌ˜/ํ† ๋ผ)','่พฐ(์ง„/์šฉ)', 'ๅทณ(์‚ฌ/๋ฑ€)', 'ๅˆ(์˜ค/๋ง)', 'ๆœช(๋ฏธ/์–‘)', '็”ณ(์‹ /์›์ˆญ์ด)', '้…‰(์œ /๋‹ญ)', 'ๆˆŒ(์ˆ /๊ฐœ)', 'ไบฅ(ํ•ด/๋ผ์ง€)'] idx = (year - 4)%12 return animals[idx] def get_year_info(): while True: print('-'*30) current_year = 2019 year = int(input('year(0 to quit):')) if year == 0 : break if year < 0 : continue print(year,'year :',get_leap_year(year)) print('age :', get_age(year,current_year)) print('animal :', get_12_animals(year)) # get_year_info() # 3๋ฒˆ def get_grade(score): d = {'90~100':'A','80~89':'B','70~79':'C', '60~69':'D','0~59':'F'} if score >=90 and score <= 100: grade = d['90~100'] elif score >=80 and score < 90: grade = d['80~89'] elif score >=70 and score < 80: grade = d['70~79'] elif score >=60 and score < 70: grade = d['60~69'] else: grade = d['0~59'] return grade def get_score_grade(): while True: score = int(input('score(-1 to quit)=')) if score < 0 : break print(score,':',get_grade(score)) # get_score_grade() # 4๋ฒˆ def get_mile(meter): if meter < 0 : return mile = meter / 1.609 return mile def input_meter_to_mile(): while True: meter = float(input('meter(-1 to quit)=')) if meter < 0 : break print(meter,'meter:{:6.2f}'.format(get_mile(meter)),'miles') # input_meter_to_mile() # 5๋ฒˆ def get_celsius(fahrenheit): celsius = ( fahrenheit - 32 ) / 1.8 return celsius def input_fahrenheit_to_celsius(): fahrenheit = float( input( 'Input fahrenheit : ' ) ) celsius = get_celsius(fahrenheit) print( 'fahrenheit : {0:<6.2f} -> celsius : {1:<6.2f}'.format( fahrenheit, celsius ) ) # input_fahrenheit_to_celsius() # 6๋ฒˆ def get_divisor(number): result = [] for k in range(1,number + 1): remain = number % k if remain == 0: result.append(k) return result def input_number_for_divisor(): while True: number = int(input('number(0 to quit)=')) if number == 0 : break print(number,':',get_divisor(number), len(get_divisor(number)),'๊ฐœ') # input_number_for_divisor() # 7๋ฒˆ def sum_abs(a,b): if a < 0 : a = a * -1 if b < 0 : b = b * -1 return a + b def input_number_to_sum_abs(): while True: number1 = int(input('number1(0 to quit)=')) if number1 == 0 : break number2 = int(input('number20 to quit)=')) if number2 == 0 : break print(number1,'and',number2,'==>',sum_abs(number1,number2)) # input_number_to_sum_abs() # 8๋ฒˆ def mymap(func,var_list): result_list = [] for k in var_list: result_list.append(func(k)) return result_list def multi_two(x): return x*2 # print(mymap(multi_two,[1,2,3,4,5,6])) # =============================================================================== # 1. Car class๋ฅผ ๋งŒ๋“ค๊ณ  ๋‹ค์Œ ๋ฉค๋ฒ„์™€ ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  # ํ˜ธ์ถœํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๊ตฌํ˜„ํ•ด๋ณด์„ธ์š” # ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค ๊ฐ์ฒด sonata ๋ฅผ ๋งŒ๋“ ๋‹ค # ํด๋ž˜์Šค์˜ ๋ชจ๋“  ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์„œ ๋™์ž‘์„ ํ™•์ธํ•ด๋ณธ๋‹ค class Car: def __init__(self,name,drv,speed,direction,fuel,state): self.car_name = name self.car_drv = drv self.car_speed = speed self.car_direction = direction self.car_fuel = fuel self.car_state = state def set_car_name(self,name): self.name = name print('์ฐจ์ข…์ด [{}]๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค'.format(name)) def get_car_name(self): return car_name def set_car_drv(self): self.drv = drv print('์ฐจ์˜ ๊ตฌ๋™๋ฐฉ์‹์ด {}์œผ๋กœ ๋ฐ”๋€Œ์—ˆ์Šต๋‹ˆ๋‹ค.'.format(drv)) def get_car_drv(self): return drv def set_car_fuel(self,fuel): self.fuel = fuel print("์ฐจ์˜ ์—ฐ๋ฃŒ ๋ฐฉ์‹์ด [ ์ „๊ธฐ ]๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_fuel(self): return fuel # =========================================================================== class Car: def __init__(self, name = 'sonata', drv = '์ „๋ฅœ', speed = 0, direction = '์•ž์ชฝ', fuel = 'ํœ˜๋ฐœ์œ ', state = '์ •์ƒ'): print('์ƒ์„ฑ์ž ํ˜ธ์ถœ') self.car_name = name self.car_drv = drv self.car_speed = speed self.car_direction = direction self.car_fuel = fuel self.car_state = state def set_car_name(self, name): self.car_name = name print('{0} [{1}]{2}'.format("์ฐจ์ข…์ด", name, "์œผ(๋กœ) ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")) def get_car_name(self): return self.car_name def set_car_drv(self, drv): self.car_drv = drv print('{0} [{1}]{2}'.format("์ฐจ์˜ ๊ตฌ๋™ ๋ฐฉ์‹์ด", drv, "์œผ(๋กœ) ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")) def get_car_drv(self): return self.car_drv def set_car_fuel(self, fuel): self.car_fuel = fuel print('{0} [{1}]{2}'.format("์ฐจ์˜ ์—ฐ๋ฃŒ ๋ฐฉ์‹์ด", fuel, "์œผ(๋กœ) ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")) def get_car_fuel(self): return self.car_fuel def set_car_state(self, state): self.car_state = state print('{0} [{1}]{2}'.format("์ฐจ์˜ ์ƒํƒœ๊ฐ€", state, "์œผ(๋กœ) ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")) def get_car_state(self): return self.car_state def set_car_speed(self, speed): self.car_speed = speed print('{0} [{1}]{2}'.format("์ฐจ์˜ ์†๋ ฅ์ด ์‹œ์†", speed, "km ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")) def get_car_speed(self): return self.car_speed def turn(self, direction): self.car_direction = direction print("์ž๋™์ฐจ์˜ ๋ฐฉํ–ฅ์ด ", direction, "์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") def stop(self): self.car_direction = '[ ์ •์ง€ ]' print("์ž๋™์ฐจ๊ฐ€ ์ •์ง€ ํ•˜์˜€์Šต๋‹ˆ๋‹ค.") return self.car_direction def start(self): self.car_direction = '[ ์‹œ๋™ ]' print("์ž๋™์ฐจ๊ฐ€ ์‹œ๋™์ด ๊ฑธ๋ ธ์Šต๋‹ˆ๋‹ค.") def move_forward(self, speed): self.car_speed = speed self.car_direction = '์•ž์ชฝ' direction = '์ „์ง„' print('{0} [{1}]{2} [{3}]{4}'.format("์ž๋™์ฐจ๊ฐ€", direction, "ํ•ฉ๋‹ˆ๋‹ค. ์†๋„๋Š”", speed, "km ์ž…๋‹ˆ๋‹ค.")) def move_backward(self, speed): self.car_speed = speed self.car_direction = '๋’ค์ชฝ' direction = 'ํ›„์ง„' print('{0} [{1}]{2} [{3}]{4}'.format("์ž๋™์ฐจ๊ฐ€", direction, "ํ•ฉ๋‹ˆ๋‹ค. ์†๋„๋Š”", speed, "km ์ž…๋‹ˆ๋‹ค.")) def __del__(self): print(self.car_name, '์ž๋™์ฐจ๊ฐ€ ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.') # ============================================================================= class Car: def __init__(self, name='์†Œ๋‚˜ํƒ€', drv='์ „๋ฅœ', speed=0, direction='์•ž์ชฝ', fuel='ํœ˜๋ฐœ์œ ', state='์ •์ƒ'): print('์ƒ์„ฑ์ž ํ˜ธ์ถœ') self.car_name = name self.car_drv = drv self.car_speed = speed self.car_direction = direction self.car_fuel = fuel self.car_state = state def set_car_name(self,name): # set ์ž…๋ ฅ self.car_name = name print('์ฐจ์ข…์ด [{}]์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(name)) def get_car_name(self,name): # ๊ฐ’์„ ๋ฐ›์„ ๋•Œ๋Š” ์ธ์ž๋ฅผ ๋„ฃ์„ ํ•„์š”๊ฐ€ ์—†๋‹ค return self.car_name def set_car_drv(self,drv): self.car_drv = drv print('์ฐจ์˜ ๊ตฌ๋™๋ฐฉ์‹์ด {}์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(drv)) def get_car_drv(self): return self.car_drv def set_car_fuel(self,fuel): self.car_fuel = fuel print("์ฐจ์˜ ์—ฐ๋ฃŒ ๋ฐฉ์‹์ด [ {} ]๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค".format(fuel)) def get_car_fuel(self,fuel): return self.car_fuel def set_car_state(self,state): self.car_state = state print("์ฐจ์˜ ์ƒํƒœ๊ฐ€ [ {} ]์œผ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค".format(state)) def get_car_state(self,state): return self.car_state def set_speed(self,speed): self.car_speed = speed print(" ์ž๋™์ฐจ์˜ ์†๋ ฅ์ด ์‹œ์† [{}] km ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค".format(speed)) def get_speed(self,speed): return self.car_speed def turn(self,direction): self.car_direction = direction print(" ์ž๋™์ฐจ์˜ ๋ฐฉํ–ฅ์ด [ {} ]์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค".format(direction)) def stop(self): self.car_direction = '[ ์ •์ง€ ]' print("์ž๋™์ฐจ๊ฐ€ ์ •์ง€ํ•˜์˜€์Šต๋‹ˆ๋‹ค.") return self.car_direction def start(self): self.car_direction = '[์‹œ๋™]' print('์ž๋™์ฐจ๊ฐ€ ์‹œ๋™์ด ๊ฑธ๋ ธ์Šต๋‹ˆ๋‹ค.') return self.car_direction def move_forward(self,direction,speed): self.car_direction = '์•ž์ชฝ' self.car_speed = speed print('์ž๋™์ฐจ๊ฐ€ {}ํ•ฉ๋‹ˆ๋‹ค. ์†๋„๋Š” {}์ž…๋‹ˆ๋‹ค.'.format(direction,speed)) def move_backward(self,direction, speed): self.car_direction = '๋’ค์ชฝ' self.car_speed = speed print('์ž๋™์ฐจ๊ฐ€ {}ํ•ฉ๋‹ˆ๋‹ค. ์†๋„๋Š” {}์ž…๋‹ˆ๋‹ค.'.format(direction,speed)) def __del__(self,name): self.car_name = name print(self.car_name, '{} ์ž๋™์ฐจ๊ฐ€ ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(name)) # ====================================2๋ฒˆ<๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ>====================================== # 2๋ฒˆ class CarCenter: price = {'์ •์ƒ': 10, '๋ธŒ๋ ˆ์ดํฌ๊ณ ์žฅ': 1000, '์ „์กฐ๋“ฑ๊ณ ์žฅ': 2000, 'ํ›„๋ฏธ๋“ฑ๊ณ ์žฅ': 3000, '์—ฐ๋ฃŒ๋ถ€์กฑ': 4000, 'ํƒ€์ด์–ดํŽ‘ํฌ': 5000, '์—”์ง„์˜ค์ผ๋ถ€์กฑ': 6000, '๋ƒ‰๊ฐ์ˆ˜๋ถ€์กฑ': 7000, 'ํ์ฐจ์ฒ˜๋ฆฌ': 9000} def __init__(self): self.fix_cost = 0 self.fixed_list = {} self.accent = Car() # ์ด๋ฒˆ ๊ณผ์ œ ํ•ต์‹ฌ def fix_car(self,car): self.fix_cost = CarCenter.price[car.car_state] self.fixed_list[car.car_name] = car.car_state print('[',car.car_name,']์˜ [',car.car_state, '] ์ˆ˜๋ฆฌ ์™„๋ฃŒ, ๋น„์šฉ์€ [',self.fix_cost,'] ์› ์ž…๋‹ˆ๋‹ค') def set_car_drv(self,car, drv): car.car_drv = drv self.accent.car_drv = drv print("์ฐจ์˜ ๊ตฌ๋™ ๋ฐฉ์‹์ด [", car.car_drv ,"]์œผ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_drv(self,car): return car.car_drv def set_car_fuel(self,car,fuel): car.car_fuel = fuel print("์ฐจ์˜ ์—ฐ๋ฃŒ ๋ฐฉ์‹์ด [", car.car_fuel,"]๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_fuel(self,car): return car.car_fuel def get_fixed_list(self,car): fixed_item = self.fixed_list[car.car_name] cost = CarCenter.price[fixed_item] return '[' + fixed_item + '] : [' + str(cost) + ']์›' def __del__(self): pass def test_carcenter(car): sonata = car ct1 = CarCenter() ct1.fix_car(sonata) ct1.set_car_drv(sonata,'ํ›„๋ฅœ') print(ct1.get_car_drv(sonata)) ct1.set_car_fuel(sonata, '์ „๊ธฐ') print(ct1.get_car_fuel(sonata)) print(ct1.get_fixed_list(sonata)) # test_carcenter(sonata) # ๋ณ„๋„์˜ ํŒŒ์ผ๋กœ ์ž‘์„ฑํ•œ๋‹ค import ํด๋ž˜์Šค๊ธฐ์ดˆ์‹ค์Šต๋ฌธ์ œ as car avante = car.Car() avante.set_car_name('์•„๋ฐ˜ํ…Œ') print(avante.get_car_name()) avante.set_car_state('์ „์กฐ๋“ฑ๊ณ ์žฅ') print(avante.car_state) print('-'*30) ct1 = car.CarCenter() ct1.fix_car(avante) ct1.set_car_drv(avante, 'ํ›„๋ฅœ') print(ct1.get_car_drv(avante)) ct1.set_car_fuel(avante, '์ˆ˜์†Œ') print(ct1.get_car_fuel(avante)) print(ct1.get_fixed_list(avante)) sorento = car.Car() sorento.set_car_name('์†Œ๋ Œํ† ') sorento.set_car_state('ํƒ€์ด์–ดํŽ‘ํฌ') ct1.fix_car(sorento) print(ct1.get_fixed_list(sorento)) pride = car.Car() pride.set_car_name('ํ”„๋ผ์ด๋“œ') pride.set_car_state('์—”์ง„์˜ค์ผ๋ถ€์กฑ') ct1.fix_car(pride) print(ct1.get_fixed_list(pride)) pride.set_car_state('ํƒ€์ด์–ดํŽ‘ํฌ') ct1.fix_car(pride) print(ct1.get_fixed_list(pride)) print(ct1.fixed_list) # {'์•„๋ฐ˜ํ…Œ': '์ „์กฐ๋“ฑ๊ณ ์žฅ', '์†Œ๋ Œํ† ': 'ํƒ€์ด์–ดํŽ‘ํฌ', # 'ํ”„๋ผ์ด๋“œ': '์—”์ง„์˜ค์ผ๋ถ€์กฑ'} # ====================1. ๊ณ„์‚ฐ๊ธฐ ํ”„๋กœ๊ทธ๋žจ=============================== class Calculator(): def calculate(self,a,b,c): self.a = a self.b = b self.c = c x = { 1:'+', 2:'-', 3:'*', 4:'/' } result = eval(str(a) + x[c] + str(b)) return result a = Calculator() a.calculate(1,2,3) # eval ๋ฌธ์ž์—ด์„ ์ •์ˆ˜ํ˜•์œผ๋กœ, int๋Š” str๋กœ ๋ฐ”๊พธ๊ณ  ์‹œ์ž‘ # () ์“ฐ๊ธฐ class ControlCalculator: def __init__(self): self.rhkd = Calculator() # ๋ชฐ๋ž๋˜ ๊ฐœ๋…, ๋ณ€์ˆ˜๋Š” ํ• ๋‹น x ํด๋ž˜์Šค ์ธ์Šคํ„ดํŠธ ๊ฐ์ฒด๋ฅผ ๋ฉค๋ฒ„๋กœ ๊ฐ€์ ธ์˜จ๋‹ค๋Š” ๊ฒƒ์€ # ๊ทธ ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ์™€์„œ ๋‚ด๊ฐ€ ์ƒˆ๋กœ ๋งŒ๋“  ๋ณ€์ˆ˜์— ์ž…๋ ฅํ•œ๋‹ค๋Š” ๋œป. # ๊ทธ๋Ÿผ ๋‚˜๋Š” ๊ฐ๊ฐ์˜ ๋‹ค๋ฅธ ๊ฐ์ฒด์˜ ์„ฑ๊ฒฉ์„ ๊ฐ–์„ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค. def calculate(self): Calculator.calculate() class ViewCalculator: def __init__(self): self.rhkdTm = ControlCalculator() def DisplayCalculator(self): while True : n = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด์šฉ')) continue ControlCalculator.calculate(n) print(DisplayCalculator(n)) # ====================1. ๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ=============================== # ====================2. ํ•™์ƒ ํด๋ž˜์Šค=============================== class Student: def calculate(self,q,w,e): self.q = q self.w = w self.e = e sum_hong = q+w+e sum_kim = q+w+e sum_nam = q+w+e return sum_hong, sum_kim, sum_nam # ==================================================================== class Airplane(Car): def __init__(self, name ='KAL147', height = 0, speed = 0, direction = '์ •์ง€', state = '์ •์ƒ'): self.air_name = name self.air_height = height self.air_speed = speed self.air_direction = direction self.air_state = state def set_air_name(self,name): self.air_name = name print('๊ธฐ์ข…์ด {} ์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.'.format(self.air_name)) def get_air_name(self): return self.air_name def set_air_height(self,height): self.air_height = height print('๋น„ํ–‰ ๊ณ ๋„๋ฅผ {} km ๋กœ ์„ค์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค'.format(self.air_height)) def get_air_height(self): return self.air_height def land_to_ground(self,direction): self.air_direction = direction print('๋น„ํ–‰๊ธฐ๊ฐ€ {}ํ•˜์˜€์Šต๋‹ˆ๋‹ค'.format(self.air_direction)) def set_speed(self,speed): self.air_speed = speed print (" ๋น„ํ–‰๊ธฐ์˜ ์†๋ ฅ์ด ์‹œ์† {} km ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค".format(self.air_speed)) def get_speed(self): return self.air_speed def move_forward(self,direction,speed): self.air_speed = speed self.air_direction = direction print("๋น„ํ–‰๊ธฐ๊ฐ€ {}์œผ๋กœ ์ „์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” {}km์ž…๋‹ˆ๋‹ค".format(self.air_direction, self.air_speed)) def move_backward(self,direction,speed): self.air_speed = speed self.air_direction = direction print("๋น„ํ–‰๊ธฐ๊ฐ€ {}์œผ๋กœ ํ›„์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” {} km ์ž…๋‹ˆ๋‹ค".format(self.air_direction, self.air_speed )) a = Airplane() print(a.get_speed()) print(a.set_speed(200)) print(a.get_speed()) print(a.land_to_ground('์ฐฉ๋ฅ™')) print(a.move_forward('์•ž์ชฝ',151)) # ์ดˆ๊ธฐ๊ฐ’์„ ์„ค์ •ํ•œ ๋ณ€์ˆ˜๋ช…์œผ๋กœ self.๋ณ€์ˆ˜๋ช…์„ ๋™์ผํ•˜๊ฒŒ ์„ค์ • # print ๊ฐ’์—๋„ ๋ณ€์ˆ˜๋ช…์„ ์ž…๋ ฅํ•  ๊ฒƒ. # def move_backward(self, direction, speed): # # self.air_speed = speed # ์œ„์˜ self.air_speed = speed ์—์„œ # ์•ž์˜ ๋ณ€์ˆ˜๋ช…์€ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ •๊ณผ ๊ฐ™์ด ํ•ด์ค˜์•ผ ํ•˜๊ณ , # ๋’ค์˜ speed๋Š” ์–ด๋– ํ•œ ๊ฐ’์ด ์•„๋‹ˆ๋ผ ์ž…๋ ฅ๋  ์ธ์ž๋ฅผ ๋งํ•ด์ค€๋‹ค. ์ธ์ž๊ฐ’์„ ๋ฐ›๊ฒ ๋‹ค # ๋งจ ์œ„์˜ speed๋Š” ์ธ์ž๋กœ ์ž…๋ ฅ๋  ๊ฐ’์˜ ์œ„์น˜๋ฅผ ๋งํ•œ๋‹ค. # def ๋ฉ”์†Œ๋“œ ๋ณ€์ˆ˜ (self, ์ธ์ž๊ฐ’1, ์ธ์ž๊ฐ’2): # self. <์„ค์ •๋œ ๋ณ€์ˆ˜1> = ์ธ์ž๊ฐ’1 # self. <์„ค์ •๋œ ๋ณ€์ˆ˜2> = ์ธ์ž๊ฐ’2 # ๋ฉ”ํƒ€๋ชฝ์€ ์–ด๋–ค ์„ค์ •๋œ ๋ณ€์ˆ˜์—์„œ ์ž…๋ ฅ๋  ์ธ์ž๊ฐ’์„ ๋ฐ›๊ฒ ์Šต๋‹ˆ๋‹ค. # =============================๊ฐ•์‚ฌ๋‹˜ ๋‹ต์•ˆ============================================================= # ํด๋ž˜์Šค์ƒ์†์‹ค์Šต๊ณผ์ œ.py class Car: def __init__(self): print('Car ์ƒ์„ฑ์ž') self.car_name = '์†Œ๋‚˜ํƒ€' self.car_drv = '์ „๋ฅœ' self.car_speed = 0 self.car_direction = '์•ž์ชฝ' self.car_fuel = 'ํœ˜๋ฐœ์œ ' self.car_state = '์ •์ƒ' def set_car_name(self, name): self.car_name = name print("์ฐจ์ข…์ด [",self.car_name,"]์œผ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_name(self): return self.car_name def set_car_drv(self, drv): self.car_drv = drv print("์ฐจ์˜ ๊ตฌ๋™ ๋ฐฉ์‹์ด [", self.car_drv ,"]์œผ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_drv(self): return self.car_drv def set_car_fuel(self, fuel): self.car_fuel = fuel print("์ฐจ์˜ ์—ฐ๋ฃŒ ๋ฐฉ์‹์ด [", self.car_fuel,"]๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_fuel(self): return self.car_fuel def set_car_state(self,state): self.car_state = state print("์ฐจ์˜ ์ƒํƒœ๊ฐ€ [",self.car_state, "]์œผ๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_car_state(self): return self.car_state def set_speed(self,speed): self.car_speed = speed print("์ž๋™์ฐจ์˜ ์†๋ ฅ์ด ์‹œ์† [",self.car_speed,"]km ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def get_speed(self): return self.car_speed def turn(self,direction): self.car_direction = direction print("์ž๋™์ฐจ์˜ ๋ฐฉํ–ฅ์ด [",self.car_direction ,"]์œผ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") def stop(self): self.car_direction = '์ •์ง€' print("์ž๋™์ฐจ๊ฐ€ ์ •์ง€ ํ•˜์˜€์Šต๋‹ˆ๋‹ค") def start(self): print("์ž๋™์ฐจ๊ฐ€ ์‹œ๋™์ด ๊ฑธ๋ ธ์Šต๋‹ˆ๋‹ค") def move_forward(self): self.car_direction = '์•ž์ชฝ' print("์ž๋™์ฐจ๊ฐ€ ์ „์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” ",self.car_speed,"km์ž…๋‹ˆ๋‹ค") def move_backward(self): self.car_direction = '๋’ค์ชฝ' print("์ž๋™์ฐจ๊ฐ€ ํ›„์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” ",self.car_speed,"km์ž…๋‹ˆ๋‹ค") def __del__(self): print('[', self.car_name, "] ์ž๋™์ฐจ๊ฐ€ ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") class Airplane(Car): def __init__(self): print('Airplane ์ƒ์„ฑ์ž') # < ์ถ”๊ฐ€ ์ธ์Šคํ„ด์Šค ๋ฉค๋ฒ„ > self.air_name = 'KAL147' self.air_height = 0 self.air_speed = 0 self.air_direction = '์ •์ง€' self.air_state = '์ •์ƒ' self.car = Car() # < ์ถ”๊ฐ€ ๋ฉ”์„œ๋“œ > def set_air_name(self, name): self.air_name = name print('๋น„ํ–‰๊ธฐ ๊ธฐ์ข…์ด [', self.air_name, ']๋กœ ๋ณ€๊ฒฝ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค') def get_air_name(self): return self.air_name def set_height(self,height): self.air_height = height print('๋น„ํ–‰ ๊ณ ๋„๋ฅผ [',self.air_height,'] km ๋กœ ์„ค์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค') def get_height(self): return self.air_height def land_to_ground(self): self.air_direction = '์ •์ง€' print('๋น„ํ–‰๊ธฐ๊ฐ€ ์ฐฉ๋ฅ™ํ•˜์˜€์Šต๋‹ˆ๋‹ค') # < ๋ฉ”์„œ๋“œ ์˜ค๋ฒ„๋ผ์ด๋”ฉ๊ตฌํ˜„ > def set_speed(self,speed): self.air_speed = speed print('๋น„ํ–‰๊ธฐ์˜ ์†๋ ฅ์ด ์‹œ์† [',self.air_speed,'] km ๋กœ ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค') def get_speed(self): return self.air_speed def move_forward(self): self.air_direction = '์•ž์ชฝ' print('๋น„ํ–‰๊ธฐ๊ฐ€ ์ „์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” [',self.air_speed, ']km์ž…๋‹ˆ๋‹ค') def move_backward(self): self.air_direction = '๋’ค์ชฝ' print('๋น„ํ–‰๊ธฐ๊ฐ€ ํ›„์ง„ํ•ฉ๋‹ˆ๋‹ค ์†๋„๋Š” [',self.air_speed, '] km ์ž…๋‹ˆ๋‹ค') def __del__(self): print('[', self.air_name, "] ๋น„ํ–‰๊ธฐ๊ฐ€ ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") if __name__ == '__main__': kal = Airplane() kal.set_air_name('์•„์‹œ์•„๋‚˜104') print(kal.get_air_name()) kal.set_height(1000) print(kal.get_height()) kal.land_to_ground() kal.set_speed(100) print(kal.get_speed()) kal.move_forward() kal.move_backward() print(kal.car.car_name) # =======================ํŒŒ์ผ ์‹ค์Šต ๋ฌธ์ œ======================================== f = open('items.txt','w') f.write('ํ’ˆ๋ชฉ๋ช…,๋‹จ๊ฐ€') f.close() f = open('items.txt','r') f.close() # ============================================================================ # [ํ•จ์ˆ˜ ์‹ค์Šต๊ณผ์ œ]==================================================================================== # 1. ๋‘ ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ ๋ฐ›์•„ ํ‰๊ท ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ (์ฒซ ๋ฒˆ์งธ ์ˆ˜๊ฐ€ -1 ์ด๋ฉด ์ข…๋ฃŒ) a = int(input('a= ')) b = int(input('b= ')) def mean_0(a,b): if a != -1: c = (a + b)/2 return c print(mean_0(a,b)) # 2. ์ž…๋ ฅ ๋ฐ›์€ ๋‚ด์šฉ์„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ ํ›„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ „๋‹ฌ๋ฐ›์•„ ์ตœ๋Œ€๊ฐ’๊ณผ ์ตœ์†Œ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ ์ž‘์„ฑ # (-1์ด ์ž…๋ ฅ๋  ๋•Œ ๊นŒ์ง€ ์ž…๋ ฅ ๋ฐ›์•„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ) def worhkd_1(): l=[] while True: n = int(input('์ž…๋ ฅ = ')) if n == -1: break l.append(n) l.sort() print(l) return('์ตœ์†Ÿ๊ฐ’ = ', l[0]),('์ตœ๋Œ€๊ฐ’ = ', l[-1]) print(worhkd_1()) # ์ˆœ์„œ๋ฅผ ์ž˜ ์ƒ๊ฐํ•˜์ž # ํ•จ์ˆ˜ ์ด์šฉ ๋ฐฉ๋ฒ• def worhkd1(): l = [] while True: n = int(input('์ž…๋ ฅ=')) l.append(n) if n == -1: break return ('์ตœ์†Ÿ๊ฐ’=',min(l)),('์ตœ๋Œ€๊ฐ’=',max(l)) print(worhkd1()) # 3. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ์‹œ์ž‘๊ณผ ๋ ์ˆซ์ž๋ฅผ ๋ฐ›์•„ ์‹œ์ž‘๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ๋ชจ๋“  ์ •์ˆ˜๊ฐ’์˜ ํ•ฉ์„ # ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ(์‹œ์ž‘๊ฐ’๊ณผ ๋๊ฐ’์„ ํฌํ•จ). a = int(input('์‹œ์ž‘๊ฐ’=')) b = int(input('๋๊ฐ’=')) l = [] def worhkd2(): for c in range(a, b+1): l.append(c) d = sum(l) return d print(worhkd2()) # 4. ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๋ฌธ์ž์—ด์„ ํฌํ•จํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ž…๋ ฅ๋  ๋•Œ ๊ฐ ๋ฌธ์ž์—ด์˜ ์ฒซ ์„ธ ๊ธ€์ž๋กœ๋งŒ # ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ. # ์˜ˆ๋ฅผ ๋“ค์–ด, ํ•จ์ˆ˜์˜ ์ž…๋ ฅ์œผ๋กœ ['Seoul', 'Daegu', 'Kwangju', 'Jeju']๊ฐ€ ์ž…๋ ฅ # ๋  ๋•Œ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์€ ['Seo', 'Dae', 'Kwa', 'Jej']('end' ์ž…๋ ฅ์‹œ ์ž…๋ ฅ ์ข…๋ฃŒ) dic = {'Seoul':'Seo' , 'Daegu' : 'Dae' , 'Kwangju' : 'Kwa' , 'Jeju': 'Jej'} def rhkd1(dic): while True: n = input('๋„์‹œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”') print(dic[n]) if n == 'end' : return '๋์ด ๋‚ฌ์Šต๋‹ˆ๋‹ค' break return dic[n] print(rhkd1(dic)) # 4๊ฐ€์ง€ ์œ ํ˜•์„ ๊ณต๋ถ€ # 5. range() ํ•จ์ˆ˜ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” myrange() ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑ # (์ธ์ž๊ฐ€ 1,2,3๊ฐœ์ธ ๊ฒฝ์šฐ๋ฅผ ๋ชจ๋‘๊ตฌํ˜„ return ๊ฐ’์€ ํŠœํ”Œ ) # (range() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉ, ๋‹จ ์ธ์ž ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋Š” ๋ฐ˜๋“œ์‹œ ๊ตฌํ˜„) def myrange(*worhkd): if len(worhkd) == 1: range(0,worhkd[0]) a = tuple([a for a in range(worhkd[0])]) return a elif len(worhkd) == 2: range(worhkd[0],worhkd[-1]) b = tuple([b for b in range(worhkd[0],worhkd[-1])]) return b else: len(worhkd) == 3 range(worhkd[0],worhkd[1],worhkd[2]) c = tuple([c for c in range(worhkd[0],worhkd[1],worhkd[2])]) return c print(myrange(1,8,2)) # <๊ณ ๊ธ‰> # 6. ํ™”๋ฉด์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฉ”๋‰ด๋ฅผ ์ถœ๋ ฅํ•˜์—ฌ ์„ ํƒ๋œ # ๋ฉ”๋‰ด์˜ ๊ธฐ๋Šฅ(๋‘์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์—ฐ์‚ฐ)์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ # 1.add # 2.subtract # 3.multiply # 4.divide # 0.end # select : worhkd1 = {1:'add', 2:'subtract',3:'multiply',4:'divide',0:'end'} print(worhkd1) def worhkd0(): worhkd1 = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide', 0: 'end'} while True: print(worhkd1) a = int(input('์ˆซ์ž ์ž…๋ ฅ = ')) b = int(input('์ˆซ์ž ์ž…๋ ฅ = ')) worhkd2 = {1: a + b, 2: a - b, 3: a * b, 4: a / b, 0: 'end'} x = worhkd2[int(input('์—ฐ์‚ฐ์ž'))] print(x) print(worhkd0()) # 1. ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋น„๋งŒ๋„๋ฅผ ๊ตฌํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ํ‘œ์ค€์ฒด์ค‘(kg)=(์‹ ์žฅ(cm)-100)ร—0.85 # ๋น„๋งŒ๋„(%)=ํ˜„์žฌ์ฒด์ค‘/ํ‘œ์ค€์ฒด์ค‘(%)ร—100 # ๋น„๋งŒ๋„๊ฐ€90%์ดํ•˜ -->์ €์ฒด์ค‘ # 90์ดˆ๊ณผ~110% --> ์ •์ƒ # 110์ดˆ๊ณผ~120% --> ๊ณผ์ฒด์ค‘ # 120%์ดˆ๊ณผ --> ๋น„๋งŒ a = int(input('ํ‚ค = ')) b = int(input('๋ชธ๋ฌด๊ฒŒ = ')) def bimando(a,b): while True: a = int(input('ํ‚ค = ')) b = int(input('๋ชธ๋ฌด๊ฒŒ = ')) l = (a-100)*0.85 x = b/l*100 if x <= 90: print('๋‹น์‹ ์€ ์ €์ฒด์ค‘์ž…๋‹ˆ๋‹ค.') elif 90 < x <=110: print('๋‹น์‹ ์€ ์ •์ƒ์ž…๋‹ˆ๋‹ค.') elif 110 < x <= 120: print('๋‹น์‹ ์€ ๊ณผ์ฒด์ค‘์ž…๋‹ˆ๋‹ค.') else: x>120 print('๋‹น์‹ ์€ ๋น„๋งŒ์ž…๋‹ˆ๋‹ค.') continue return x print(bimando(a,b)) # 2. ์—ฐ๋„๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ # 1) ์œค๋…„์—ฌ๋ถ€๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ์œค๋…„์˜ ์กฐ๊ฑด # 1-1) 4๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€์ง€๋งŒ 100์œผ๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค ๋˜๋Š” # 1-2) 400 ์œผ๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง€๋ฉด ์œค๋…„์ž„ # 2) ๋‚˜์ด๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # 3) ๋ (12์ง€์‹ )๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # ("์ฅ","์†Œ","ํ˜ธ๋ž‘์ด","ํ† ๋ผ","์šฉ","๋ฑ€","๋ง","์–‘","์›์ˆญ์ด","๋‹ญ","๊ฐœ","๋ผ์ง€",); # (์„œ๊ธฐ 4๋…„์€ ์ฅ๋ ์ด๋‹ค,2019๋…„ ๋ผ์ง€) def dbssus(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) if n%4 == 0 and n%100 != 0: print('์œค๋…„์ž…๋‹ˆ๋‹ค.') elif n%400 == 0 : print('์œค๋…„์ž…๋‹ˆ๋‹ค.') else : print('์œค๋…„์ด ์•„๋‹™๋‹ˆ๋‹ค.') continue dbssus() def El(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) x = 2019 - n + 1 print('๋‹น์‹ ์˜ ๋‚˜์ด๋Š” {}์ž…๋‹ˆ๋‹ค.'.format(x)) El() # ํ’€์ด 1๋ฒˆ def Elsms(): while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค')) if n%12 == 0: print('์›์ˆญ์ด๋ ') elif n%12 == 1: print('๋‹ญ๋ ') elif n%12 == 2: print('๊ฐœ๋ ') elif n%12 == 3: print('๋ผ์ง€๋ ') elif n%12 == 4: print('์ฅ๋ ') elif n%12 == 5: print('์†Œ๋ ') elif n%12 == 6: print('ํ˜ธ๋ž‘์ด๋ ') elif n%12 == 7: print('ํ† ๋ผ๋ ') elif n%12 == 8: print('์šฉ๋ ') elif n%12 == 9: print('๋ฑ€๋ ') elif n%12 == 10: print('๋ง๋ ') else: n%12 == 11 print('์–‘๋ ') continue Elsms() # ํ’€์ด 2๋ฒˆ def ektlgoqha(): a = ["์›์ˆญ์ด", "๋‹ญ", "๊ฐœ", "๋ผ์ง€", "์ฅ", "์†Œ", "ํ˜ธ๋ž‘์ด", "ํ† ๋ผ", "์šฉ", "๋ฑ€", "๋ง", "์–‘"] while True: n = int(input('์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = a[n%12] print(x) return x print(ektlgoqha()) # 3. ์ ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ # 90~100 'A' # 80~89 'B' # 70~79 'C' # 60~69 'D' # ๋‚˜๋จธ์ง€ 'F' # ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) def wjatn(): dic = {range(90, 101): 'A', range(80, 90): 'B', range(70, 80): 'C', range(60, 70): 'D', range(0, 60): 'F'} while True: x = int(input('์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” = ')) if 90<= x <= 100: print([k for x,k in dic.items() if x == range(90,101)]) elif 80<= x <= 89: print([k for x,k in dic.items() if x == range(80, 90)]) elif 70 <= x <= 79: print([k for x,k in dic.items() if x == range(70, 80)]) elif 60 <= x <= 69: print([k for x,k in dic.items() if x == range(60, 70)]) else : x < 60 print([k for x, k in dic.items() if x == range(0, 60)]) wjatn() # srp={'๊ฐ€์œ„':'๋ณด','๋ฐ”์œ„':'๊ฐ€์œ„','๋ณด':'๋ฐ”์œ„'} # print([k for k,v in srp.items() if v == '๋ฐ”์œ„'].pop()) # 4. m(๋ฏธํ„ฐ) ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋งˆ์ผ๋กœ ๋ณ€ํ™˜ํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # (1 mile = 1.609 meter) def qusghks(): while True : n = int(input('m๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = n/1.609 print('{} mile ์ž…๋‹ˆ๋‹ค.'.format(x)) print(qusghks()) # 5. ํ™”์”จ ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์„ญ์”จ๋กœ ๋ณ€ํ™˜ํ•˜์‹œ์š”(ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”) # (celsius = ( fahrenheit - 32 ) / 1.8) def ghkTl(): while True: n = int(input('ํ™”์”จ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) x = (n-32)/1.8 print('{} ์„ญ์”จ ์ž…๋‹ˆ๋‹ค.'.format(x)) print(ghkTl()) # 6. ํ•˜๋‚˜์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์•ฝ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š”. # (์–ด๋–ค ์ •์ˆ˜ n์„ ์ž์—ฐ์ˆ˜ k๋กœ ๋‚˜๋ˆ„์–ด ๋‚˜๋จธ์ง€๊ฐ€ 0 ์ผ๊ฒฝ์šฐ k๋Š” ์ •์ˆ˜ n์˜ ์•ฝ์ˆ˜์ด๋‹ค) def wjdtn(): n = int(input('์ •์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”')) l = [] for k in range(1,n+1): if n%k == 0: l.append(k) print('{}๋Š” {}์˜ ์•ฝ์ˆ˜์ž…๋‹ˆ๋‹ค'.format(l,n)) print(wjdtn()) # 7. 2๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ ˆ๋Œ€๊ฐ’์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์‹œ์š” # ( abs()ํ•ฉ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๊ตฌํ˜„ํ•œ๋‹ค) def wjfeorkqt(): a = int(input('a =')) b = int(input('b =')) if a < 0 : a = -a if b < 0 : b = -b x = a+b return(x) print(wjfeorkqt()) # 8. map ํ•จ์ˆ˜์™€ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” mymap ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜์‹œ์š” # # <map()ํ•จ์ˆ˜์˜ ๊ธฐ๋Šฅ> # def multi_two(x): # return x*2 # result = map(multi_two,[1,2,3,4,5]) # print(list(result)) # ์ถœ๋ ฅ ๊ฒฐ๊ณผ :[2, 4, 6, 8, 10]
873bea103c835e6909ec9e92350d7693c4d7bbb0
nadineo/python
/ex9/RLEString.py
1,588
4.03125
4
import re from re import sub class RLEString(object): def __init__(self, string): #check if the string is valid if not re.match('^[a-zA-Z]+$',string): raise ValueError("Text has to consist of alphabetic characters (a-zA-Z))") else: self.__mystring = string self.__iscompressed = False def compress(self): #compress internal string #substitute function of regular expression in python #the (.)\1* is the syntax for finding backreferences -> finding all equal charactes in a row #the sub() function substitutes for example: EEEEE -> 5E if self.__iscompressed: raise RuntimeError("Mystring is already compressed!") else: self.__mystring = sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), self.__mystring) self.__iscompressed = True return self.__mystring def decompress(self): #substitute function of regular expression in python #the caputuring groups (\d+ = decimal digit group(1) and (\D = any non digit character group(2)) has #to be placed in the resulting "new" mystring. group(0) would result in any kind of: (5E), group(1): 5, group(2): E #decompressed is the result: EEEEE #the sub() function, substitutes 5E with E*(int)5 -> EEEEE if not self.__iscompressed: raise RuntimeError("Mystring is already decompressed!") else: self.__mystring = sub(r'(\d+)(\D)', lambda m: m.group(2) * int(m.group(1)), self.__mystring) self.__iscompressed = False return self.__mystring def iscompressed(self): if self.__iscompressed: return self.__iscompressed def __str__(self): return self.__mystring
2ca35001b54ed6ce402290382394f628d35b25f3
Aternumm/python_tasks
/hw4_tsk2.py
291
4.0625
4
x = int(input("ะ’ะฒะตะดะธั‚ะต ะฅ ")) y = int(input("ะ’ะฒะตะดะธั‚ะต ะฃ")) if x >= 0 and y >= 0: print("ะ’ 1 ั‡ะตั‚ะฒะตั€ั‚ะธ") elif x >= 0 and y <= 0: print("ะ’ 4 ั‡ะตั‚ะฒะตั€ั‚ะธ") elif x <= 0 and y <= 0: print("ะฒ 3 ั‡ะตั‚ะฒะตั€ั‚ะธ") else: print("ะ’ะพ 2 ั‡ะตั‚ะฒะตั€ั‚ะธ")
60390ca3dd4ef0e199ec902a23f499caf787c461
bananasfourscale/Journal_Assistant
/Journal/JournalEntry.py
1,766
3.546875
4
#!/usr/bin/env python """Base Class representing all types of Journal Entires that can be added to the journal""" class JournalEntry: """ Represents a journal entry which is the base class used by many other types of entires that can be added to the Journal Attributes: name(str): string which gives a characteristic name to help the user identify the entry updated(bool): boolean indicator for determining if the entry has been updated recently and should be saved upon exit or call to save. """ def __init__(self, name): """ Initialize a class instance and set up any default instance variables """ self.name = name self.updated = True def update_entry(self): """ Function meant to be overwritten by the inheriting classes, which will take in characteristic info and use that to update the specific entry data. :return: None """ self.updated = True def save_entry(self): """ Function meant to be overwritten by inheriting classes, which will collect all important entry details and place them into a dictionary so that they can be saved. Will also set the updated flag to false to inform the journal that this entry has been saved. :return: dict - dictionary mapping named entry characteristics with details about the set characteristic """ self.updated = False def read_entry_log(self, log): """ :param log: dictionary mapping entry details with the data structure used to hold that detail type. Logs are read for each entry upon opening a saved Journal. :return: None """
b6403443d057dfc2448e6338781c60f346c4a21e
yannhamdi/n.projet7
/p7app/parsing.py
2,113
3.640625
4
#!/usr/bin/python3 # -*- coding: Utf-8 -* """module that will parses the sentence""" from p7app.stopword import stop_words class SentenceParse: """our class that will creates all the methods needed for parsing the sentence""" def __init__(self): "we initialize the attribute stop words" self.uncleaned_sentence = [] self.sentence = " " self.new_sentence = " " def in_lower_case(self, sentence): "function that put the strings in lower case" self.sentence = str(sentence) self.sentence = self.sentence.lower() return self.sentence def deleting_stop_words(self, sentence): """function that deletes the stop words""" self.sentence = str(sentence) for word in self.sentence.split(): if word in stop_words: pass else: self.uncleaned_sentence.append(word) self.new_sentence = " ".join(self.uncleaned_sentence) return self.new_sentence def deleting_special(self, sentence): """function that deletes the special character""" self.sentence = str(sentence) intab = ",:?;.-" outtab = " " trantab = str.maketrans(intab, outtab) self.sentence = self.sentence.translate(trantab) return self.sentence def deleting_several_spaces(self, sentence): """function that deletes spaces in case of double spaces""" self.sentence = str(sentence) self.sentence = self.sentence.replace(" ", " ") return self.sentence def returning_cleaned_sentence(self, sentence): """fucntion that return the sentence cleaned""" self.sentence = str(sentence) self.sentence = self.in_lower_case(self.sentence) self.sentence = self.deleting_special(self.sentence) self.sentence = self.deleting_stop_words(self.sentence) self.sentence = self.deleting_several_spaces(self.sentence) return self.sentence def main(): """initialize main function""" if __name__ == "__main__": main()
952188160ab25e04a7cdd349eded56bf07318d24
mathans1695/Python-Practice
/codeforces problem/petyaandstrings.py
126
3.765625
4
first, second = input().lower(), input().lower() if first < second: print(-1) elif second < first: print(1) else: print(0)
2f42978e87807665a4ad38900fda393c715a2316
knu2xs/setup-course-event
/setupClass.py
3,298
3.609375
4
''' Name: setupClass Purpose: Copies all class materials from a location storing all materials for a specific class to C:/student/<class>. In this directory the script will create three directories. ./<class>_dataStudent ./<class>_dataDemo ./<class>_slides Author: Joel McCune Created: 21May2013 Copyright: (c) Joel McCune 2013 Licence: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' # import modules import os import shutil import time class Course(object): ''' Represents a course, specifically the materials for a course and provides a method to move all the resources into a date stamped target directory for teaching a class. ''' def __init__(self, name, source): # set variables self.name = name self.source = source # create target path with current date YYYYMMDD self.nameDate = name + '_' + time.strftime('%Y%m%d') # the name of the resource directories to be copied self.resources = [] self.resources.append(name + '_dataDemo') self.resources.append(name + '_dataStudent') self.resources.append(name + '_slides') def copyResources(self): ''' Copies everything from a source directory to a new directory named the class plus a timestamp in C:\Student. ''' # output to console print 'Starting to copy resources for {0}'.format(name) for resource in self.resources: # create source resource path source = os.path.join(self.source, resource) # create destination path destination = os.path.join('C:', 'Student', self.nameDate ,resource) # attempt to copy resources try: print '\nStarting to copy {0}'.format(resource) shutil.copytree(source, destination) print 'Successfully copied {0}'.format(resource) # when it does not work except: print 'Could not copy {0}'.format(resource) print 'Please check to ensure the target\n directory does not already exist.' if __name__ == '__main__': # get name of parent directory where script is located source = os.path.dirname(os.path.realpath(__file__)) # the name of the parent directory is the name of the course name = os.path.basename(source) thisClass = Course(name, source) thisClass.copyResources() # pause for input before exiting lastline = raw_input('\nPlease press Enter to exit...')
a11531e47d76e0e89fd77ca184d5bc49d84968d2
dpedu/advent2018
/1/b.py
376
3.640625
4
#!/usr/bin/env python3 def main(): total = 0 seen = {} with open("input.txt") as f: numbers = [int(i) for i in f.readlines()] while True: for number in numbers: total += number if total in seen: print(total) return seen[total] = None if __name__ == '__main__': main()
1720dff055b265a6e6a3d3934860e7c66bb566e8
Prakashchater/Daily-Practice-questions
/Arrays/Remove elements.py
257
3.78125
4
def removeElement(nums): count=0 for i in range(len(nums)): if nums[i] != val: nums[count] = nums[i] count+=1 return count if __name__ == '__main__': nums=[3,2,2,3] val= 3 print(removeElement(nums))
e1d8758ec9831152337e1cbb98cbe3f3cd413e1c
PyRPy/stats_py
/math_py/Ch01_polygons_turtle.py
283
4.3125
4
# chapter 1 drawing polygons with the turtle module # import module from turtle import * # moving turtle # forward(100) # shape('turtle') # changing directions # right(45) # forward(150) # square dance shape('turtle') for i in range(4): forward(100) right(90)
34fe75ff0de6fe6df5f9edde343119a0b4460687
rajesh-cric/pythonchallenges.py
/code1.py
136
4
4
first=input("enter your first name: ") last=input("enter your last name: ") print('NAME: '+first.capitalize()+' '+last.capitalize())
b1652db2d60742f33af54d057fb26c4aefe0505c
msGenDev/Python-SiteMap-Generator
/crawler.py
2,872
3.578125
4
from BeautifulSoup import BeautifulSoup, SoupStrainer import re import urllib2 website = input('Enter full website domain as quoted string: ') uniqueURLS = [] #Return list of clean string urls from given clean string website url def getLinks(website): hierarchy = [website] uniqueURLS.append(website) linklist = [] links = BeautifulSoup(urllib2.urlopen(website)).findAll('a') for l in links: """ #Filter link results to only specific things if 'specific' in l['href']: linklist.append(l) """ linklist.append(l['href']) #Clean up the results for item in linklist: #Clean up the results to only external webpages if '.' in str(item) and (item not in uniqueURLS): print "Got one!" + item hierarchy.append(str(item)) uniqueURLS.append(str(item)) print hierarchy return hierarchy #Recursively go through list and generate hierarchy of urls as lists def getLinksOfLinks(webList): for sub1 in range(len(webList)): print "working on " if type(webList[sub1]) == list: webList[sub1] = getLinksOfLinks(webList[sub1]) elif type(webList[sub1]) == str: print "Hit a url" if website in webList[sub1]: if website == webList[sub1] or (webList[sub1] in uniqueURLS): print "Skipping this one: " + webList[sub1] continue else: print "In an intenal link. Following... " + webList[sub1] webList[sub1] = [webList[sub1]] webList[sub1].extend(getLinks(webList[sub1][0])) else: print "External link. Continuing" + webList[sub1] continue else: print "Error" print "**** UPDATED WEB LIST ****" prettyprint(webList) print "**** END UPDATED ****" return webList #Helper def listify(linklist): if type(linklist) == list: for x in range(len(linklist)): linklist[x] = [linklist[x]] elif type(linklist) == str: return [linklist] else: print "Error: Parse Listify Error" def prettyprint(siteMap, order = 0): level = order for i in range(len(siteMap)): if type(siteMap[i]) == str: print "-" * (level + 1) + "> " + siteMap[i] elif type(siteMap[i]) == list: prettyprint(siteMap[i], level + 1 ) #A slow implemtation that makes a list unique by removing dupliate elements def makeUnique(siteList): for i in range(len(siteList)): if type(siteList[i]) == str: if siteList[i] in uniqueURLS: siteList.pop[i] else: uniqueURLS.append(siteList[i]) #Process print getLinksOfLinks(getLinks(website))
193513f098e82cc77a1cf6b2fb4366c65138173f
wang10517/Algorithms
/leetcode/easy/083 - delete duplicate list.py
553
3.671875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head is None: return None result = ListNode(head.val) cur = result temp = head while temp.next != None: temp = temp.next if temp.val != cur.val: cur.next = ListNode(temp.val) cur = cur.next return result
bfb739f13dba710201f1d0ab23f4ba81299ef1dd
iglidraci/functional-programming
/monads/maybe.py
1,213
3.671875
4
class Maybe(object): def __init__(self, value): self.value = value @classmethod def unit(cls, value): return cls(value) def map(self, f): if self.value is None: return self # forward the empty box new_value = f(self.value) return Maybe.unit(new_value) def first_value(values): if len(values) > 0: return values[0] return None class User: def __init__(self, name: str, friends: []): self.name = name self.friends: [User] = friends class Request: def __init__(self, user: User): self.user = user if __name__ == '__main__': me = User("Igli", None) gosha = User("Gosha", None) kimbo = User("Kimbo", None) sogga = User("Sogga", [me, gosha]) floppa = User("Gosha Kerr", [sogga, kimbo]) request = Request(user=floppa) friends_of_first_friends = ( Maybe.unit(request) .map(lambda request: request.user) .map(lambda user: user.friends) .map(lambda friends: friends[0] if len(friends) > 0 else None) .map(lambda first_friend: first_friend.friends) ) print(list(map(lambda user: user.name, friends_of_first_friends.value)))
67568b08aaa35cbc39915fd06fb6cedbb9b75979
gv1010/Algorithms-and-Data-Structures-Leetcode-
/Recursion/CountWays.py
145
3.796875
4
def countingWays(M,N): if M == 1 or N == 1: return 1 return countingWays(M-1, N) + countingWays(M, N-1) M = 3 N = 3 print(countingWays(M,N))
74876883128a3d8059ab1909fab6dfcd09975d42
estherica/wonderland
/Lessons/targil3.py
554
3.71875
4
a="estherica" b=32 c="belleshamharoth" print("Full name: estherica \nMy age: 32 \nMy nickname: belleshamharoth") print("Full name: " + a + "\nMy age: " + str(b+2) + "\nMy nickname: " + c) d=''' My name is Estherica I love art Follow me on instagram esthericas ''' print(d) print("p1={},p2={},p3={},p4={red}".format(1, 1.0, "estherica", red='BBFD')) print("estherica" in "estherica surkis") a="estherica surkis" print("estherica" in a) s1="JERUSALEM" print(s1) print(s1[0]) print(s1[-1]) print(s1[2:-4]) print(s1[3:-3]) print(s1[: :2]) print(s1[::-1])
45189e613a591f5ffdd8820f255ccb3e812313fb
ChJL/LeetCode
/easy/225. Implement Stack using Queues.py
1,858
4.03125
4
#Tag: Stack ''' Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Example 1: Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False SOL: just a implementation... could take a look at the "pop" part. ''' class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = collections.deque([]) def push(self, x: int) -> None: """ Push element x onto stack. """ self.stack.append(x) return self.stack def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ tmp = self.stack[-1] for i in range(len(self.stack)-1): self.stack.append(self.stack.popleft()) self.stack.popleft() return tmp def top(self) -> int: """ Get the top element. """ return self.stack[-1] def empty(self) -> bool: """ Returns whether the stack is empty. """ return 1 if not self.stack else 0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
9ca446357382f2cf4d1b60efa7795cc883c47b93
AparaV/project-euler
/Problem 065/Problem_065.py
551
3.59375
4
''' Problem 065: Convergents of e Author: Aparajithan Venkateswaran ''' from time import time ''' By writing out the fractions, we can deduce the following pattern: n(k+1) = a(k) * n(k-1) + n(k-2) ''' def answer(): d = 1 n = 2 for i in range(2, 101): temp = d c = 1 if i % 3 == 0: c = 2 * int(i / 3) d = n n = c * d + temp return sum(int(i) for i in str(n)) if __name__ == "__main__": begin = float(time()) * 1000 solution = answer() elapsed = float(time()) * 1000 - begin print "The answer is", solution print "It took", elapsed, "ms"
25eced7cd1a1ca2f4858cd02c0ba625f0c45788c
text007/learngit
/15.ๅ‡ฝๆ•ฐ็ป“ๆž„/5.้ๅކๆŠ€ๅทง.py
902
3.671875
4
# items() ๆ–นๆณ•ๅฏไปฅๅŒๆ—ถ่งฃ่ฏปๅญ—ๅ…ธ้ๅކไธญๅ…ณ้”ฎๅญ—ๅ’Œๅฏนๅบ”็š„ๅ€ผ knig = {'a':'1', 'b':'2'} for k, v in knig.items(): print(k, v) print('---------------------') # enumerate() ๆ–นๆณ•ๅฏไปฅๅŒๆ—ถ่งฃ่ฏปๅบๅˆ—้ๅކไธญๅ…ณ้”ฎๅญ—ๅ’Œๅฏนๅบ”็š„ๅ€ผ for i, v in enumerate(['a','b','c']): print(i, v) print('---------------------') # zip() ๅŒๆ—ถ้ๅކไธคไธชๆˆ–ๆ›ดๅคš็š„ๅบๅˆ— que = ['a','b','c','d'] ans = ['1','2','3','4'] for q, a in zip(que,ans): print('ๅญ—ๆฏๆ˜ฏ{0}๏ผŒๆ•ฐๅญ—ๆ˜ฏ{1}ใ€‚'.format(q, a)) # str.format() ๆ ผๅผๅŒ–ๅ‡ฝๆ•ฐ, {} ๆฅไปฃๆ›ฟไปฅๅ‰็š„ % print('---------------------') # reversed() ๅๅ‘้ๅކไธ€ไธชๅบๅˆ— for i in reversed(range(1, 10, 2)): print(i) print('---------------------') # sorted() ่ฟ”ๅ›žไธ€ไธชๅทฒๆŽ’ๅบ็š„ๅบๅˆ—๏ผŒๅนถไธไฟฎๆ”นๅŽŸๅ€ผ bas = ['a', 'b', 'c', '1', '2', '3'] for f in sorted(set(bas)): print(f) print('---------------------')
abed592990fbb7f7d23c7afa1b1c6b523a4fec40
igortereshchenko/amis_python
/km73/Zviahin_Mykyta/5/task2.py
342
3.828125
4
massive = [] n = int(input("Lenght of the massive: ")) for i in range(n): new_element = int(input("Enter an element: ")) massive.append(new_element) massive.sort() counter = 0 for i in range(len(massive)-1): if massive[i] == massive[i+1]: counter += 1 print("Number of pairs: ", counter) input()
35597c251cb9f8f6642ccb52a95c60d44493ae41
CameronMBrown/Pirple-Python-Course
/fizzbuzz.py
791
4.21875
4
#Pirple Assignment 5 - loops # classic fizzbuzz problem with the addition of finding prime numbers # isPrime is not maximally optimized def isPrime(num): if num > 1: for i in range(2, num): if num % i == 0 : # mod = 0 implies this is not a prime return False return True #if we have exited the loop, we found no devisor with mod = 0, so this is prime else: return False def FizzBuzz(max): for i in range(1, max + 1): # do not exclude passed "max" number if isPrime(i): print("PRIME ", i) elif i % 15 == 0 : # %3 and %5 can be simplified to %15 print("FizzBuzz ", i) elif i % 5 == 0 : print("Buzz ", i) elif i % 3 == 0 : print("Fizz ", i) else: print(i) FizzBuzz(100)