blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
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: xt@bu.edu
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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.