blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e32febfa49cea38997e6df377228ec52ddbda590
wslxko/LeetCode
/tencentSelect/number4.py
1,322
3.59375
4
''' 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum-closest 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def threeSumClosest(self, nums, target): value_list = [] for i in range(len(nums)): for j in range(i + 1, len(nums)): for k in range(j + 1, len(nums)): value = nums[i] + nums[j] + nums[k] value_list.append(value) result_list = [] for result in value_list: if result >= 0: a = result - target result_list.append(a) elif result < 0: a = target - result result_list.append(a) min_result = min(result_list) index = result_list.index(min_result) return value_list[index] a = Solution() b = [-1, 2, 1, -4] print(a.threeSumClosest(b, 1))
b1b801fbdc5cb7c8580a982fd8a8123bec9ab486
wslxko/LeetCode
/hot100/39. 组合总和.py
1,615
3.84375
4
""" 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。  示例 1: 输入:candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ] 示例 2: 输入:candidates = [2,3,5], target = 8, 所求解集为: [   [2,2,2,2],   [2,3,3],   [3,5] ]   来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combination-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import itertools class Solution: def combinationSum(self, candidates, target): cls = [] for index in range(len(candidates)): result = list(itertools.combinations_with_replacement(candidates, index + 1)) for i in result: if sum(i) == target: cls.append(list(i)) for j in candidates: cls_1 = [] num = j index = 1 if target % j == 0: while j*index < target: num += num index += 1 for k in range(index): cls_1.append(j) if cls_1 not in cls: cls.append(cls_1) return cls if __name__ == "__main__": a = Solution() candidates = [2, 3, 6, 7] target = 7 print(a.combinationSum(candidates, target))
ef279c9c3dec603177e2b5aa1c3761485a4e8aa0
wslxko/LeetCode
/array/number10.py
826
3.984375
4
''' 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotate-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' def rightMove(nums, num): need_move = nums[0:num] for i in need_move: nums.remove(i) nums.append(i) return nums a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(rightMove(a, 3))
a9e63fc2b7fa731fee03d8f568d984ca70131ae0
wslxko/LeetCode
/array/number16.py
1,391
3.71875
4
''' 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 示例 2: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def maxProfit(self, prices): min_prices = min(prices) new_prices = [] max_prices = [] for i in range(len(prices)): if prices[i] == min_prices: new_prices = prices[i:] for i in range(len(new_prices)): price = new_prices[i] - new_prices[0] max_prices.append(price) return max(max_prices) prices = [7, 1, 5, 3, 6, 4] if __name__ == "__main__": a = Solution() print(a.maxProfit(prices))
b6eaf79ef1feab0836e037ed670d833feed41812
wslxko/LeetCode
/hot100/31.下一个排列.py
1,272
3.96875
4
""" 实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 必须 原地 修改,只允许使用额外常数空间。 示例 1: 输入:nums = [1,2,3] 输出:[1,3,2] 示例 2: 输入:nums = [3,2,1] 输出:[1,2,3] 示例 3: 输入:nums = [1,1,5] 输出:[1,5,1] 示例 4: 输入:nums = [1] 输出:[1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/next-permutation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import itertools class Solution: def nextPermutation(self, nums): set_nums = tuple(nums) all_permu = list(itertools.permutations(nums)) all_permu.sort() for index in range(len(all_permu)): if all_permu[index] == set_nums and index == len(all_permu) - 1: nums.sort() return nums elif all_permu[index] == set_nums: return list(all_permu[index + 1]) if __name__ == "__main__": a = Solution() nums = [1, 2, 3] print(a.nextPermutation(nums))
803fa874360ac82951c3f7949b55178c3746169f
StampedPassp0rt/courses
/lphw/ex8.py
572
3.75
4
#Exercise 8 #variable that force prints four inputs with %r, kind of a debugger too. formatter = "%r %r %r %r" #printing out 1 through 4 print formatter % (1,2,3,4) #printing out one through four as strings. print formatter % ("one", "two", "three", "four") #forcing the print of Boolean values print formatter % (True, False, True, False) # Will just print the string with the %r's. print formatter % (formatter, formatter, formatter, formatter) print formatter % ("I had this thing.", "That you could type up right.",\ "But it didn't sing.", "So I said goodnight.")
4b294061e1d73407e814d6ffa93063d72d2d4122
StampedPassp0rt/courses
/mit-6.00.2x/unit-02/rolldie-example.py
343
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 16 11:37:31 2017 @author: ameetrawtani """ import random def RollDie(): return random.choice([1,2,3,4,5,6]) def testRoll(n=10): result = '' for i in range(n): result = result + 'Roll ' + str(i+1) + ': ' + str(RollDie()) + '\n' print (result)
2cbeee807c751597f8145ec26bf8c0b3e5a52810
data-engineering-lon-1/Alexia
/src/guites.py
8,068
3.546875
4
import tkinter as tk from tkinter import * import mysql.connector as connector import mysql.connector.errors as errors host = "localhost" user = "root" password = "password123" port = "33066" def mysqlconnect(database="app"): try: db_connection = connector.connect( host=host, user=user, password=password, port=port, database=database ) except: print("Can't connect to database") exit() print("Connected") return db_connection def prettyprintpeople(): my_w = tk.Tk() my_w.geometry("300x200+10+10") my_w.title("List Of People") db = mysqlconnect() cursor = db.cursor() sql_faves = "SELECT people.id, people.first_name, people.last_name, drinks.drink_name from people LEFT JOIN drinks ON people.drink_id = drinks.id" cursor.execute(sql_faves) i = 0 for people in cursor: for j in range(len(people)): e = Entry(my_w, width=10, fg="pink") e.grid(row=i, column=j) e.insert(END, people[j]) i = i + 1 my_w.mainloop() def prettyprintdrinks(): my_w = tk.Tk() my_w.geometry("300x200+10+10") my_w.title("List of Drinks") db = mysqlconnect() cursor = db.cursor() sql_faves = "SELECT * FROM drinks" cursor.execute(sql_faves) i = 0 for people in cursor: for j in range(len(people)): e = Entry(my_w, width=10, fg="pink") e.grid(row=i, column=j) e.insert(END, people[j]) i = i + 1 my_w.mainloop() def prettyprintpref(): my_w = tk.Tk() my_w.geometry("300x200+10+10") my_w.title("List of Preferences") db = mysqlconnect() cursor = db.cursor() sql_faves = "SELECT people.id, people.first_name, people.last_name, drinks.drink_name from people LEFT JOIN drinks ON people.drink_id = drinks.id" cursor.execute(sql_faves) i = 0 for people in cursor: for j in range(len(people)): e = Entry(my_w, width=10, fg="pink") e.grid(row=i, column=j) e.insert(END, people[j]) i = i + 1 my_w.mainloop() def create_person(): my_w = tk.Tk() my_w.geometry("400x300+10+10") my_w.title("Create Person") # label l0 = tk.Label( my_w, text="Create Person", font=("Helvetica", 16), width=30, anchor="c" ) l0.grid(row=1, column=1, columnspan=4) l1 = tk.Label(my_w, text="First Name: ", width=10, anchor="c") l1.grid(row=3, column=1) # text box 1 t1 = tk.Text(my_w, height=1, width=10, bg="white") t1.grid(row=3, column=2) l2 = tk.Label(my_w, text="Class: ", width=10) l2.grid(row=4, column=1) # text box 2 t2 = tk.Text(my_w, height=1, width=10, bg="white") t2.grid(row=4, column=2) l3 = tk.Label(my_w, text="Last Name: ", width=10) l3.grid(row=4, column=1) # add record button b1 = tk.Button(my_w, text="Add Record", width=10, command=lambda: add_data()) b1.grid(row=7, column=2) my_str = tk.StringVar() l4 = tk.Label(my_w, textvariable=my_str, width=10) l4.grid(row=3, column=3) my_str.set("Output") def add_data(): flag_validation = True # set the flag first_name = t1.get("1.0", END) # read first name last_name = t2.get("1.0", END) # read last name if len(first_name) < 2 and len(last_name) < 2: print("1") flag_validation = False print(type(first_name)) print(type(last_name)) try: _ = str(first_name) _ = str(last_name) except: print("2") flag_validation = False if flag_validation: my_str.set("Adding data...") try: db = mysqlconnect() cursor = db.cursor() query = "INSERT INTO people (first_name,last_name) VALUES (%s,%s)" my_data = (first_name, last_name) cursor.execute(query, my_data) # insert data db.commit() cursor.close() db.close() t1.delete("1.0", END) # reset the text entry box t2.delete("1.0", END) # reset the text entry box l4.grid() l4.config(fg="green") # foreground color l4.config(bg="white") # background color my_str.set("id:" + str(id.lastrowid)) l4.after(3000, lambda: l4.grid_remove()) except Exception as e: error = str(e.__dict__["orig"]) l4.grid() #return error l4.config(fg="red") # foreground color l4.config(bg="yellow") # background color print(error) my_str.set(error) finally: l4.grid() l4.config(fg="red") # foreground color l4.config(bg="yellow") # background color my_str.set("check inputs.") l4.after(3000, lambda: l4.grid_remove()) my_w.mainloop() def create_drinks(): my_w = tk.Tk() my_w.geometry("400x300+10+10") my_w.title("Creprice") my_w.config(bg='pink') # label l0 = tk.Label( my_w, text="Create Drink", font=("Helvetica", 16), width=30, anchor="c" ) l0.grid(row=1, column=1, columnspan=4) l0.config(bg='pink') l1 = tk.Label(my_w, text="Drink Name: ", width=10, anchor="c") l1.grid(row=3, column=1) l1.config(bg="LightPink1") # text box 1 t1 = tk.Text(my_w, height=1, width=10, bg="white") t1.grid(row=3, column=2) l2 = tk.Label(my_w, text="Class: ", width=10) l2.grid(row=4, column=1) # text box 2 t2 = tk.Text(my_w, height=1, width=10, bg="white") t2.grid(row=4, column=2) l3 = tk.Label(my_w, text="Drink Price: ", width=10) l3.grid(row=4, column=1) l3.config(bg="LightPink1") # add record button b1 = tk.Button(my_w, text="Add Record", width=10, command=lambda: add_data()) b1.grid(row=7, column=2) my_str = tk.StringVar() l4 = tk.Label(my_w, textvariable=my_str, width=10) l4.grid(row=3, column=3) my_str.set("Output") def add_data(): flag_validation = True # set the flag first_name = t1.get("1.0", END) # read first name price = t2.get("1.0", END) # read last name if len(first_name) < 2 and len(price) < 1: print("1") flag_validation = False try: _ = str(first_name) _ = float(price) except: print("2") flag_validation = False if flag_validation: my_str.set("Adding data...") try: db = mysqlconnect() cursor = db.cursor() query = "INSERT INTO drinks (drink_name,price) VALUES (%s,%s)" my_data = (first_name, price) id = cursor.execute(query, my_data) # insert data db.commit() cursor.close() db.close() t1.delete("1.0", END) # reset the text entry box t2.delete("1.0", END) # reset the text entry box l4.grid() l4.config(fg="green") # foreground color l4.config(bg="white") # background color #my_str.set("id:" + str(id.lastrowid)) #l4.after(3000, lambda: l4.grid_remove()) except Exception as e: #error = str(e.__dict__["orig"]) l4.grid() #return error l4.config(fg="red") # foreground color l4.config(bg="yellow") # background color print(e) my_str.set(str(e)) finally: l4.grid() l4.config(fg="red") # foreground color l4.config(bg="yellow") # background color my_str.set("check inputs.") l4.after(3000, lambda: l4.grid_remove()) my_w.mainloop()
6af6f8c09de179180408d6ed5ec89fa157fc4742
Lyonmwangi/learn_python
/elif_practice.py
231
3.625
4
a=50 if a==40: print("1-got a true expression value",a) elif a==30: print("2-got a true expression value",a) elif a==50: print("3-got a true expression value",a) else: print("4-got a true expression value",a) print ("goodbye")
114718898f19da87850e0baa1d09c6d2023e00b1
manim-kindergarten/manim_sandbox
/utils/mobjects/angle.py
3,399
3.71875
4
# from @pdcxs from manimlib.imports import * # Usage: Angle(p1, p2, p3) # p1, p2, p3 should be in counterclock order # p2 is the vertex of the angle # is_right: make the angle always be a right angle # not_right: the angle is always NOT a right angle # if is_right and not_right are both false, the angle # will be drawed according to the value class Angle(Arc): CONFIG = { "radius": 0.5, "color": WHITE, "show_edge": False, "is_right": False, "not_right": False, } def __init__(self, p1, p2, p3, **kwargs): self.p1 = p1 self.p2 = p2 self.p3 = p3 self.arc_center = p2.get_center() Arc.__init__(self, start_angle=self.get_start_angle(), angle = self.get_angle(), **kwargs) def get_start(self): pos1 = self.p1.get_center() pos2 = self.p2.get_center() vec = pos1 - pos2 return pos2 + normalize(vec) * self.radius def get_end(self): pos3 = self.p3.get_center() pos2 = self.p2.get_center() vec = pos3 - pos2 return pos2 + normalize(vec) * self.radius def get_start_angle(self): pos1 = self.p1.get_center() pos2 = self.p2.get_center() vec = pos1 - pos2 x = vec[0] y = vec[1] return math.atan2(y, x) def get_angle(self): pos1 = self.p3.get_center() pos2 = self.p2.get_center() vec = pos1 - pos2 x = vec[0] y = vec[1] angle = math.atan2(y, x) -\ self.get_start_angle() if angle < 0: angle += TAU return angle def make_angle_dynamic(self): self.add_updater(lambda m: m.generate_points()) def get_label_loc(self, buff=SMALL_BUFF): s_angle = self.get_start_angle() e_angle = self.get_angle() angle = s_angle + e_angle / 2 x = np.cos(angle) * (self.radius + buff) * RIGHT y = np.sin(angle) * (self.radius + buff) * UP return x + y + self.p2.get_center() def add_label(self, label, buff=SMALL_BUFF): label.add_updater(lambda m:\ m.move_to(self.get_label_loc(buff))) def generate_points(self): o = self.p2.get_center() if self.is_right or\ (not self.not_right and\ abs(self.get_angle() - PI/2) < 1e-6): self.clear_points() vec = self.get_end() - o if self.show_edge: self.append_points([o]) self.add_line_to(self.get_start()) self.append_points([self.get_start()]) self.add_line_to(self.get_start() + vec) self.append_points([self.get_start() + vec]) self.add_line_to(self.get_end()) self.append_points([self.get_end()]) if self.show_edge: self.add_line_to(o) self.append_points([o]) else: arc = Arc( radius = self.radius, start_angle = self.get_start_angle(), angle = self.get_angle(), arc_center = o ) self.clear_points() self.append_points(arc.points) if (self.show_edge): self.add_line_to(o) self.append_points([o]) self.add_line_to(arc.points[0])
72a8594df8fdad92e259e9745822ee9d43a54de4
cjfoster10/realpython
/sql/homework_2.py
680
3.84375
4
import sqlite3 with sqlite3.connect('cars.db') as connection: c = connection.cursor() newCars = [ ('Ford', 'Explorer', 15), ('Ford', 'Focus', 20), ('Ford', 'Mustang', 25), ('Honda', 'Accord', 20), ('Honda', 'Civic', 15) ] # c.executemany("INSERT INTO inventory(Make, Model, Quantity)\ # values (?,?,?)", newCars) # c.execute("UPDATE inventory SET Quantity=? WHERE Quantity=?", (1, 20)) c.execute("SELECT * FROM inventory") c.execute("SELECT * FROM inventory WHERE Make='Ford'") rows = c.fetchall() for row in rows: print(row)
46d32c84fe3d08e24a7522e55723fdd683025792
tongramt/SoftAppsGroup
/Script1.py
3,136
4.1875
4
# The code for part 1: Script 1 # The below code is adapted from code found here: https://www.geeksforgeeks.org/file-explorer-in-python-using-tkinter/ # Python program to create # a file explorer in Tkinter # import all components # from the tkinter library from tkinter import * from tkinter import filedialog import pandas as pd from pyjstat import pyjstat import json import openpyxl # Function for opening the # file explorer window def browse_files(): global filepath filepath = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("csv Files", ".csv"), ("json Files", ".json"),)) # Close the window once file is chosen window.destroy() filepath = None # Create the root window window = Tk() # Set window title window.title('File Explorer') # Set window size window.geometry("600x500") # Set window background color window.config(background="white") # Create a File Explorer label label_file_explorer = Label(window, text="File Explorer using Tkinter", width=100, height=4, fg="blue") button_explore = Button(window, text="Browse Files", command=browse_files) button_exit = Button(window, text="Exit", command=exit) # Grid method is chosen for placing # the widgets at respective positions # in a table like structure by # specifying rows and columns label_file_explorer.pack() button_explore.pack() button_exit.pack() # Let the window wait for any events window.mainloop() if filepath is not None: # Reading in regular csv files try: dataframe = pd.read_csv(filepath) except: pass # Reading in json files try: f = open(filepath) file = f.read() data = json.loads(file) dataframe = pd.json_normalize(data['results']) except: pass try: dataframe = pd.read_json(filepath, orient='index') except: pass # reading in differently formatted json try: dataframe = pd.read_json(filepath, orient='columns') except: pass # reading in json stat files try: file = open(filepath) dataset = pyjstat.Dataset.read(file) # write to dataframe dataframe = dataset.write('dataframe') except: pass try: # create a name for an excel file datatoexcel = pd.ExcelWriter('exported_data.xlsx') # write DataFrame to excel dataframe.to_excel(datatoexcel) # save the excel datatoexcel.save() print(dataframe.head(), '\nAbove are the first 5 rows of the Data.\n' 'The Data has been written to an Excel File successfully.\n' 'The file is named "exported_data.xlxs"\n' 'The Data has', dataframe.shape[1], 'columns and', dataframe.shape[0], 'rows.') except: print('Sorry this dataset could not be opened')
2e9974e68d38a212e138cbd41eb2dc8996757d6e
rajmohd123-cell/PythonFDP
/basic.py
913
3.78125
4
class LLNode: def __init__(self, val, next=None): self.val = val self.next = next def create_linked_list(nums): """ Assumes the list has atleast one element """ head = LLNode(nums[0]) current = head for i in range(1, len(nums)): new_node = LLNode(nums[i]) current.next = new_node current = new_node return head def print_all_integers(head): while head != None: if type(head.val).__name__ == "int": print(head.val) head = head.next def print_all_integers(head): # # terminating condition if head == None: return # breaking the problem into smaller sub-problems # solving the first node and calling for the remaining problem if type(head.val).__name__ == "int": print(head.val) elements = [55, 33, 22, 11] ll = create_linked_list(elements)
e5b35bb71eb2561eb28e786654209579564c7f5f
piredins/homework
/homework lecture 2.5.py
613
3.71875
4
from contextlib import contextmanager from datetime import datetime @contextmanager def open_file(file_path, encoding='utf8'): try: time1 = (datetime.now()) print('Время запуска кода в менеджере контекста:', time1) file = open(file_path) yield file finally: file.close time2 = (datetime.now()) print('Время окончания работы кода:', time2) print('Время работы кода:', time2 - time1) with open_file('test_homework.txt') as file: for line in file: string = line print(string)
1b68f58a36594c14385ff3e3faf8569659ba0532
derekcollins84/myProjectEulerSolutions
/problem0001/problem1.py
521
4.34375
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' returnedValues = [] sumOfReturnedValues = 0 for testNum in range(1, 1000): if testNum % 3 == 0 or \ testNum % 5 == 0: returnedValues.append(testNum) for i in range(len(returnedValues)): sumOfReturnedValues = \ sumOfReturnedValues \ + returnedValues[i] print(sumOfReturnedValues)
5ac9d7093e418997e00e843fd40a47289a2d7d89
derekcollins84/myProjectEulerSolutions
/problem0022/problem22.py
1,177
3.9375
4
''' Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? ''' import csv nameArray = [] sortedNameArray = [] nameValue = 0 runningTotal = 0 with open('problem0022/p022_names.txt') as csvfile: names = csv.reader(csvfile, delimiter=',') for line in names: for name in line: nameArray.append(name) for name in sorted(nameArray): sortedNameArray.append(name) for namePosition in range(len(sortedNameArray)): for i in range(len(sortedNameArray[namePosition])): nameValue += ord(sortedNameArray[namePosition][i]) - 64 nameValue = nameValue * (namePosition + 1) runningTotal += nameValue nameValue = 0 print(runningTotal)
9670dc592f9feb66155096df8e905f5c3bd29057
lov2cod/my_playground
/cs50/dict_challenge.py
877
3.671875
4
import csv sub_data = {} def size_of_data(): return len(sub_data) def update_data(sub_id,new_value): if sub_id in sub_data: sub_data[sub_id] = new_value return sub_data def add_data(sub_id, value): if sub_id not in sub_data: sub_data[sub_id] = value print(f"Sub ID:{sub_id} appended") return sub_data else: print(f"Sub ID:{sub_id} is already present , so updating the value") return update_data(sub_id, value) def print_data(): for key, value in sub_data.items(): print(f"{key} {value}") if value == "Num_trees": print("___________________________") def main(): with open("treeorder.csv",'r') as data: reader = csv.reader(data) for row in reader: sub_data[row[0]] = row[1] print_data() if __name__ == "__main__": main()
fa46678e891f0ab1d1dbbe8a9ca77b83532180d6
Biruk-gebru/acc-projects
/guess game with whie loop.py
344
4.03125
4
import random x=random.randint(1,10) print("guess the value of x.") answer=0 while answer!=x: answer=eval(input("enter your guess:")) if answer > x: print("your guess is too high,guess again:") elif answer==x: print ("YOU got the number:",x) else: print("your guess is too low,try again:")
d7cece82c421a65e9d1c5e1f41d392180aa24505
iadel93/TestRepo101
/test.py
92
3.53125
4
print('Hello World') for i in range(10): print(i) l = [5,6,7] for x in l: print(x)
70cbe08e7ab2ccb89bf2eaf80d344dde051e1ab6
whitewolf23/computer-science
/03_oop/oop_example/person.py
791
3.984375
4
# 공통 속성을 뽑아서 부모 클래스 class Person: def __init__(self, name, age, money): self.name = name self.age = age self.money = money def give_money(self, other, how_much): if self.money > how_much: self.money -= how_much other.money += how_much else: print('돈이 없어서 못줘') def __str__(self): return ''' My name is {} I am {} years old I have {} won'''.format(self.name, self.age, self.money) if __name__=='__main__': # 너가 메인 실행 파일이라면 아래 명령을 실행한다. p1 = Person('greg', 18, 5000) p2 = Person('kim', 22, 1000) print(p1) print(p2) p1.give_money(p2, 500) print(p1) print(p2)
f37a238f5e9698233992dcda9b44d5b32d537a6a
Emp923/junk-drawer
/python/guesser.py
661
4.0625
4
#!/usr/bin/python3 # Number guesser program by Eric Penrod import random def intro(): print("This program generates a random integer.") print("You must try to guess that integer.") print("You will be given hints after each guess.") def main(): found = False ranNum = random.randint(1,100) # ranNum = 35 # for debugging use only userGuess = int(input("What is your guess? ")) while not found: if userGuess == ranNum: print("That is correct!") found = True elif userGuess > ranNum: userGuess = int(input("Incorrect. Guess lower: ")) else: userGuess = int(input("Incorrect. Guess Higher: ")) intro() main() # end of program
59609427d2e62f29bb7388f7bd320cb2cf927da3
Sohom-chatterjee2002/Python-for-Begineers
/Assignment-1-Python Basics/Problem 3.py
423
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 2 14:23:03 2020 @author: Sohom Chatterjee_CSE1_T25 """ def append_middle(s1,s2): middleIndex=int(len(s1)/2) print("Original strings are: ",s1,s2) middleThree=s1[:middleIndex]+s2+s1[middleIndex:] print("After appending new string in middle: ",middleThree) s1=input("Enter your first string: ") s2=input("Enter your seccond string: ") append_middle(s1,s2)
c162faab7cf2c9b1a0ece7786f1c0dfe195b8265
Sohom-chatterjee2002/Python-for-Begineers
/Assignment-1-Python Basics/Problem 19.py
497
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 12 15:49:43 2020 @author: Sohom Chatterjee_CSE1_T25 """ #Given a Python dictionary, Change Brad’s salary to 8500 #sampleDict = { 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma','salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 6500}} sampleDict = { 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma','salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 6500}} sampleDict['emp3']['salary']=8500 print(sampleDict)
8e8e1b63125ecf7c15ebb4c7fae1322025e2b143
Sohom-chatterjee2002/Python-for-Begineers
/Assignment-1-Python Basics/Problem 10.py
242
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 9 15:43:07 2020 @author: Sohom Chatterjee_CSE1_T25 """ #Unpack the following tuple into 4 variables.Tuple=(10,20,30,40) Tuple=(10,20,30,40) a,b,c,d=Tuple print(a) print(b) print(c) print(d)
8b29ca12d190975f7b957645e9a18b4291e662a1
Sohom-chatterjee2002/Python-for-Begineers
/Assignment 2 -Control statements in Python/Problem 6.py
556
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 23 14:25:28 2020 @author: Sohom Chatterjee_CSE1_T25 """ #The set of input is given as ages. then print the status according to rules. def age_status(age): if(age<=1): print("in_born") elif(age>=2 and age<=10): print("child") elif(age>=11 and age<=17): print("young") elif(age>=18 and age<=49): print("adult") elif(age>=50 and age<=79): print("old") else: print("very_old") age=int(input("Enter your age: ")) age_status(age)
972cc1139d479cd8a369ef66201b5ccb2a326ef0
nipapad/python-experiments
/edabit/puzzlePieces.py
267
3.625
4
list1 = [1,2,3,4,5,6] list2 = [6,5,4,3,2,1] # Holds an iterator object zipped = zip(list1, list2) result = map(sum,zipped) result_list = list(result) if result_list.count(result_list[0]) != len(result_list): print(False) else: print(True)
74955265dcd03ac302245f7176cf464b8ef82ffc
ayushchaudhari/Hacker-Rank
/Coding Challenges/April Code Challenge organized By VIMEET/Day 5 Laurene's new trouble problem/solution.py
116
3.578125
4
m=int(input()) a_list=[] for n in range(m): a_list.append(int(input())) for n in a_list: print(n-1,1)
ea8c192a63775e80e6ce8f9e4821f57059261a57
alison-medeiro/html-para-o-git
/idade.py
84
3.6875
4
idade = int(input("Qual é a sua idade? ")) print("Você tem {} anos".format(idade))
3587ee44ae9bc32009c33cd4c4526e5f63fbce8b
nkmashaev/Courses
/homework4/task05.py
634
4.0625
4
def fizzbuzz(n: int): """ fizzbuzz function takes a number N as an input and returns a generator that yields N FizzBuzz numbers. :param int: size of fizzbuzz sequence :return: generator of fizzbuzz sequence :raise: ValueError """ if not isinstance(n, int): raise ValueError("Error: Expected integer number!") fizzbuzz_dict = {} last_el = n + 1 for i in range(3, last_el, 3): fizzbuzz_dict[i] = "Fizz" for i in range(5, last_el, 5): fizzbuzz_dict[i] = fizzbuzz_dict.get(i, "") + "Buzz" for i in range(1, last_el): yield fizzbuzz_dict.get(i, str(i))
42259b902e9518309c4bcf2a5ff4360fe58ba62c
nkmashaev/Courses
/homework7/task02.py
420
3.5
4
from collections import defaultdict from itertools import zip_longest def string_constructor(string: str) -> str: str_list = [] for a in string: if a != "#": str_list.append(a) elif len(str_list) > 0: str_list.pop() return "".join(str_list) def backspace_compare(first: str, second: str) -> True: return string_constructor(first) == string_constructor(second)
d6f384f67d2ba4e090b948c68056a24cb785427b
nkmashaev/Courses
/homework7/task01.py
1,025
3.671875
4
from collections import defaultdict from typing import Any example_tree = { "first": ["RED", "BLUE"], "second": { "simple_key": ["simple", "list", "of", "RED", "valued"], }, "third": { "abc": "BLUE", "jhl": "RED", "complex_key": { "key1": "value1", "key2": "RED", "key3": ["a", "lot", "of", "values", {"nested_key": "RED"}], }, }, "fourth": "RED", } def find_occurences(tree: dict, element: Any) -> int: elements_dict = defaultdict(int) def rec_counter(storage): if isinstance(storage, (int, str, bool)): elements_dict[storage] += 1 elif isinstance(storage, dict): for key, val in storage.items(): rec_counter(key) rec_counter(val) else: for i in storage: rec_counter(i) rec_counter(tree) return elements_dict[element] if __name__ == "__main__": print(find_occurances(example_tree, "RED"))
abb1f71c980a72bd23442c1f820d030626742929
nkmashaev/Courses
/homework2/task01.py
5,125
3.9375
4
""" The implementation of the first task. The first task consists of next problems^ 1) Find of 10 longest words consisting from largest amount of unique symbols 2) Find rarest symbol for document 3) Count every punctuation char 4) Count every non ascii char 5) Find most common non ascii char for document """ import os import string import unicodedata from collections import defaultdict from functools import cmp_to_key from typing import Iterator, List, TextIO, Tuple def compare(word1: str, word2: str) -> int: """ Comparator for the first step solution. Accepts two words and compare it according to properties which is described in the first point of the assingment :param word1: first word to compare :param word2: second word to compare :return: the result of comparison """ uniq_char_numb1 = len(set(word1)) uniq_char_numb2 = len(set(word2)) if uniq_char_numb1 > uniq_char_numb2: return -1 elif uniq_char_numb1 < uniq_char_numb2: return 1 else: if len(word1) > len(word2): return -1 elif len(word1) < len(word2): return 1 else: return 0 def tokenize(in_file: TextIO) -> Iterator[Tuple[str, int]]: """ Function tokenize split file data into tokens. Current implementation recognizes "word", "whitespace" and "punctuation" ones. Each token consists of type of token and toked data :param in_file: file for tokenization :return: Iterator of tokens. """ buff = "" char = "" while True: char = in_file.read(1) if not char: break if unicodedata.category(char).startswith("P"): if buff: yield ("word", buff) buff = "" yield ("punctuation", char) continue if char in string.whitespace: if buff: yield ("word", buff) buff = "" yield ("whitespace", char) continue buff += char if buff: yield ("word", buff) def read_char(in_file: TextIO) -> Iterator[str]: """ Accepts in_file and read it one by one :return: Iterator of file chars """ while True: char = in_file.read(1) if not char: break yield char def get_longest_diverse_words(file_path: str) -> List[str]: """ This function is designed to search ten longest words consisting from largest amount of unique symbols :param file_path: Data file name :return: list of words """ word_set = set() with open(file_path, "r", encoding="unicode_escape") as in_file: for token in tokenize(in_file): if token[0] == "word": word_set.add(token[1]) word_list = sorted(list(word_set)) word_list.sort(key=cmp_to_key(compare)) return word_list[:10] def get_rarest_char(file_path: str) -> str: """ Find rarest symbol for document :param file_path: Data file name :return: rarest symbol """ freq_dict = defaultdict(int) with open(file_path, "r", encoding="unicode_escape") as in_file: for char in read_char(in_file): freq_dict[char] += 1 rarest, freq = None, 0 for key, val in freq_dict.items(): if rarest is None or freq > val: freq = val rarest = key is_first = False return rarest def count_punctuation_char(file_path: str) -> int: """ Count number of punctuation chars :param file_path: Data file name :return: number of punctuation chars """ numb = 0 with open(file_path, "r", encoding="unicode_escape") as in_file: for token in tokenize(in_file): if token[0] == "punctuation": numb += 1 return numb def count_non_ascii_chars(file_path: str) -> int: """ Count every non ascii char :param file_path: Data file name :return: number of non ascii char """ non_ascii_numb = 0 with open(file_path, "r", encoding="unicode_escape") as in_file: for char in read_char(in_file): if char not in string.printable: non_ascii_numb += 1 return non_ascii_numb def get_most_common_non_ascii_char(file_path: str) -> str: """ Find most common non ascii char for document :param file_path: Data file name :return: non ascii char """ freq_dict = defaultdict(int) with open(file_path, "r", encoding="unicode_escape") as in_file: for char in read_char(in_file): if not char in string.printable: freq_dict[char] += 1 common, freq = None, 0 for key, val in freq_dict.items(): if freq < val: freq, common = val, key return common if __name__ == "__main__": file_path = os.path.join("test_data_files", "data.txt") print(get_longest_diverse_words(file_path)) print(get_rarest_char(file_path)) print(count_punctuation_char(file_path)) print(count_non_ascii_chars(file_path)) print(get_most_common_non_ascii_char(file_path))
7df003f67d880346929f62d80864f345a0efcbcf
natasyaoktv/Tugas-1
/Soal-2.py
175
3.765625
4
r = int(input("Masukkan jari-jari lingkaran: ")) phi = float(3.14) circle = phi * (r * r) print("Luas lingkaran dengan jari jari {} cm adalah {} cm\u00b2".format(r, circle))
553dce7c36bae7bb5b372a4050df7fe2c2a8ed1c
ctir006/Python-and-C-code-submitted-in-HackerRank-contests
/Class_Work_Assignments/DP/Recursive_change..py
277
3.640625
4
import math def recurse_change(money,coins): if money==0: return 0 min_coins=math.inf for i in coins: if money>=i: min=1+recurse_change(money-i,coins) if min_coins>min: min_coins=min return min_coins coins=[6,5,1] print(recurse_change(40,coins))
d06e5dbe79392823f0bac4a3329d2f2a60ac0655
ctir006/Python-and-C-code-submitted-in-HackerRank-contests
/Camel_case.py
96
3.734375
4
str=input() count=1 for i in range(len(str)): if str[i].isupper(): count+=1 print(count)
fccacd3a4799ab9b23a34b5c60f007afd54f7f73
tejaswisunitha/python
/power.py
348
4.28125
4
def power(a,b): if a==0: return 0 elif b==0: return 1 elif b==1: return a elif b%2 == 0: res_even = power(a,b/2) return res_even*res_even else : b=(b-1)/2 res_odd= power(a,b) return a*res_odd*res_odd pow = power(2,3) print(pow)
df364017661771317a83300130834d9eb85332b8
ChornaOlga/pdp-php-1
/pdphelper/test_box.py
13,960
3.8125
4
from unittest import TestCase from box import Box __author__ = 'Alex Baranov' class TestBox(TestCase): """ Set of test for the Box class """ def test_create(self): """ Verify that Box can be created """ rect = Box((1, 2, 3)) self.assertIsNotNone(rect) self.assertEqual(rect.size, (1, 2, 3)) # check the default bottom left property was set self.assertEqual(rect.polus, (0, 0, 0)) # check non-default polus position rect2 = Box((1, 2, 3), [-1, 2, 0]) self.assertEqual(rect2.polus, [-1, 2, 0]) def test_create_invalid(self): """ Verify invalid scenarios of the rect creation. """ self.assertRaises(ValueError, Box, (1, 2, 3), (4, 5)) self.assertRaises(ValueError, Box, (1, 2), (1, 4, 5)) self.assertRaises(ValueError, Box, (1, 2), (1, )) def test_diagonal_polus_calculation(self): """ Tests the calculation of the opposite to polus corner """ rect = Box((1, 2, 3)) self.assertEqual(rect.diagonal_polus, [1, 2, 3]) # change polus position rect.polus = (3, 0, 2) self.assertEqual(rect.diagonal_polus, [4, 2, 5]) # change size position rect.size = (3, 2, 1) self.assertEqual(rect.diagonal_polus, [6, 2, 3]) def test_center_calculation(self): """ Verify calculation of the center position. """ rect = Box((2, 3, 4)) self.assertEqual(rect.center, [1, 1.5, 2]) # change polus rect.polus = (2, 10, -3) self.assertEqual(rect.center, [3, 11.5, -1]) # change size rect.size = (4, 2, 4) self.assertEqual(rect.center, [4, 11, -1]) def test_area_calculation(self): """ Verify calculation of the box calculation. """ p = Box(size=(2, 3, 4)) self.assertEqual(p.get_area(), 24) # change size p.size = (4, 3, 1, 4) self.assertEqual(p.get_area(), 48) def test_point_including_check_valid(self): """ Verify check whether the point is within the box. """ p = Box(size=(2, 3, 4)) valid_test_points = [(1, 1, 1), (0, 0, 0), (2, 3, 4), (1, 2, 3)] for pnt in valid_test_points: self.assertTrue(p.includes_point(pnt)) # change position p.polus = 5, 1, 3 self.assertTrue(p.includes_point((7, 4, 6))) def test_point_including_check_invalid(self): """ Verify check whether the point is within the box. """ p = Box(size=(2, 3, 4), bottom_left=(1, 2, 3)) invalid_test_points = [(1, 1, 1), (0, 0, 0), (0, 3, 4), (1, 12, 3)] for pnt in invalid_test_points: self.assertFalse(p.includes_point(pnt), "Checking point '{0}'".format(pnt)) def test_touch_valid(self): """ Verify touch check works correctly. """ p = Box(size=(2, 3, 4), bottom_left=(1, 2, 3)) touched_boxes = (Box(size=(1, 2, 3)), Box(size=(1, 2, 3), bottom_left=(3, 5, 7)), Box(size=(1, 2, 3), bottom_left=(1, 5, 3)), Box(size=(1, 2, 3), bottom_left=(1, 2, 7)), Box(size=(1, 10, 30), bottom_left=(0, 1, 1)),) for par in touched_boxes: self.assertTrue(p.touches(par)) def test_touch_invalid(self): """ Verify touch invalid scenarios. """ p = Box(size=(2, 2, 2), bottom_left=(3, 2, 4)) touched_boxes = (Box(size=(1, 2, 3)), Box(size=(1, 2, 3), bottom_left=(1, 1, 1)), Box(size=(2, 2, 2), bottom_left=(6, 5, 3))) for par in touched_boxes: self.assertFalse(p.touches(par)) def test_intersect_valid(self): """ Verify intersect valid scenarios. """ p = Box(size=(2, 2, 2), bottom_left=(1, 1, 1)) valid_boxes = (Box(size=(2, 3, 3)), Box(size=(6, 2, 3))) for par in valid_boxes: self.assertTrue(p.intersects(par), "Checking p: {}".format(par)) def test_intersect_invalid(self): """ Verify intersect invalid scenarios. """ p = Box(size=(2, 3, 4), bottom_left=(1, 2, 3)) invalid_boxes = (Box(size=(1, 2, 3)), Box(size=(0.5, 0, 0)), Box(size=(1, 2, 3), bottom_left=(3, 5, 7)), Box(size=(1, 2, 3), bottom_left=(1, 5, 3)),) for par in invalid_boxes: self.assertFalse(p.intersects(par), "Checking p: {}".format(par)) def test_can_accept(self): """ Check the can_accept method, """ test_list = (Box(size=(4, 4, 4), bottom_left=(0, 0, 0)), Box(size=(4, 2, 2), bottom_left=(-10, -10, -10)),) test_list2 = (Box(size=(2, 2, 2), bottom_left=(10, 10, 10)), Box(size=(1, 2, 2), bottom_left=(1, 2, 2)),) for p1, p2 in zip(test_list, test_list2): self.assertTrue(p1.can_accept(p2), "Checking : {}, {}".format(p1, p2)) def test_includes_valid(self): """ Verify the box include check. """ p = Box(size=(2, 2, 2), bottom_left=(1, 1, 1)) valid_boxes = (Box(size=(2, 2, 2), bottom_left=(1, 1, 1)), Box(size=(1, 1, 1), bottom_left=(1, 1, 1)), Box(size=(1, 1, 1), bottom_left=(2, 2, 2))) for par in valid_boxes: self.assertTrue(p.includes(par), "Checking p: {}".format(par)) # check 2d b1 = Box(size=(1, 3), bottom_left=(1, 0)) b2 = Box(size=(1, 1), bottom_left=(1, 2)) self.assertTrue(b1.includes(b2), "Checking p: {}".format(b1)) def test_includes_invalid(self): """ Verify the box include check (invalid scenarios). """ p = Box(size=(2, 2, 2), bottom_left=(1, 1, 1)) invalid_boxes = (Box(size=(2, 2.1, 2), bottom_left=(1, 1, 1)), Box(size=(1, 1, 1), bottom_left=(0, 0, 1)), Box(size=(1, 1, 1), bottom_left=(3, 3, 3))) for par in invalid_boxes: self.assertFalse(p.includes(par), "Checking p: {}".format(par)) def test_free_box_list(self): """ Verify calculation of the free containers. """ p1 = Box(size=(4, 3)) p2 = Box(size=(2, 1)) free_containers = p1.find_free_containers(p2) self.assertEqual(len(free_containers), 2, "Check that only 2 containers were generated") # check first container self.assertEqual(free_containers[0].size, (2, 3)) self.assertEqual(free_containers[0].polus, (2, 0)) # check second container self.assertEqual(free_containers[1].size, (4, 2)) self.assertEqual(free_containers[1].polus, (0, 1)) def test_free_box_list2(self): """ Verify calculation of the free containers additional scenarios. """ c = Box(size=(2, 5), bottom_left=(0, 0)) p = Box(size=(1, 1), bottom_left=(1, 4)) free_containers = c.find_free_containers(p) self.assertEqual(len(free_containers), 2, "Check that only 2 containers were generated") # check first container self.assertEqual(free_containers[0].size, (1, 5)) self.assertEqual(free_containers[0].polus, (0, 0)) # check second container self.assertEqual(free_containers[1].size, (2, 4)) self.assertEqual(free_containers[1].polus, (0, 0)) def test_free_box_list3(self): """ Verify calculation of the free containers additional scenarios 3d. """ c = Box(size=(4, 5, 10), bottom_left=(0, 2, 0)) b = Box(size=(3, 3, 3), bottom_left=(0, 0, 2)) free_containers = c.find_free_containers(b) self.assertEqual(len(free_containers), 4) #1 self.assertEqual(free_containers[0].size, (1, 5, 10)) self.assertEqual(free_containers[0].polus, (3, 2, 0)) #2 self.assertEqual(free_containers[1].size, (4, 4, 10)) self.assertEqual(free_containers[1].polus, (0, 3, 0)) #3 self.assertEqual(free_containers[2].size, (4, 5, 5)) self.assertEqual(free_containers[2].polus, (0, 2, 5)) #4 self.assertEqual(free_containers[3].size, (4, 5, 2)) self.assertEqual(free_containers[3].polus, (0, 2, 0)) print free_containers def test_is_blocked_valid_2d(self): """ Verify is_blocked for 2d cases. """ c1 = Box(size=(2, 2), bottom_left=(0, 0)) check_boxes = [Box(size=(1, 1), bottom_left=(3, 1)), Box(size=(1, 1), bottom_left=(3, 1.5)), Box(size=(1, 1), bottom_left=(3, 0)), Box(size=(1, 1), bottom_left=(2, -0.5))] for box in check_boxes: check_result = c1.is_blocked(box) self.assertTrue(check_result) # check false scenarios check_boxes = [Box(size=(1, 1), bottom_left=(3, 2)), Box(size=(1, 1), bottom_left=(3, -1)), Box(size=(1, 1), bottom_left=(3, 3)), Box(size=(1, 1), bottom_left=(0, 2)), Box(size=(1, 1), bottom_left=(1, 2)), Box(size=(1, 1), bottom_left=(2, 2))] for box in check_boxes: check_result = c1.is_blocked(box) self.assertFalse(check_result) def test_is_blocked_valid_3d(self): """ Verify is_blocked for 3d cases. """ c1 = Box(size=(2, 2, 2), bottom_left=(0, 0, 0)) check_boxes = [Box(size=(1, 3, 1), bottom_left=(2, 0, 1))] for box in check_boxes: check_result = c1.is_blocked(box) self.assertTrue(check_result) def test_is_blocked_valid_2d_axes(self): """ Verify is_blocked for 2d cases. """ c1 = Box(size=(2, 2), bottom_left=(0, 0)) check_boxes = [Box(size=(1, 1), bottom_left=(3, 1)), Box(size=(1, 1), bottom_left=(3, 1.5)), Box(size=(1, 1), bottom_left=(3, 0)), Box(size=(1, 1), bottom_left=(0, 2)), Box(size=(1, 1), bottom_left=(1, 3)), Box(size=(1, 1), bottom_left=(2, -0.5))] for box in check_boxes: check_result = c1.is_blocked(box, axes=(1, 1)) self.assertTrue(check_result) # check false scenarios check_boxes = [Box(size=(1, 1), bottom_left=(2, 2)), Box(size=(1, 1), bottom_left=(2, 3)), Box(size=(1, 1), bottom_left=(3, 3)), Box(size=(1, 1), bottom_left=(3, 2))] for box in check_boxes: check_result = c1.is_blocked(box) self.assertFalse(check_result) def test_is_basis_valid_2d(self): """ Verify basis check for 2d cases. """ c1 = Box(size=(2, 2), bottom_left=(0, 0)) check_boxes = [Box(size=(1, 1), bottom_left=(1, 2)), Box(size=(2, 1), bottom_left=(0, 2)), Box(size=(1, 1), bottom_left=(0, 2))] for box in check_boxes: check_result = c1.is_basis_for(box) self.assertTrue(check_result) # check false scenarios check_boxes = [Box(size=(1, 1), bottom_left=(0, 2.1)), Box(size=(1, 1), bottom_left=(-0.1, 2)), Box(size=(1, 1), bottom_left=(2.1, 2)), Box(size=(2.2, 1), bottom_left=(0, 2)), Box(size=(2, 2), bottom_left=(3, 0)), Box(size=(2.2, 1), bottom_left=(-0.1, 2))] for box in check_boxes: check_result = c1.is_basis_for(box) self.assertFalse(check_result) def test_is_basis_valid_2d_axes(self): """ Verify basis check for 2d cases. """ c1 = Box(size=(2, 2), bottom_left=(0, 0)) check_boxes = [Box(size=(1, 1), bottom_left=(2, 0)), Box(size=(1, 2), bottom_left=(2, 0))] for box in check_boxes: check_result = c1.is_basis_for(box, axes=(1, 0)) self.assertTrue(check_result) # check false scenarios check_boxes = [Box(size=(1, 1), bottom_left=(2.1, 0)), Box(size=(1, 3), bottom_left=(2, 0)), Box(size=(1, 1), bottom_left=(2, 1.1))] for box in check_boxes: check_result = c1.is_basis_for(box, axes=(1, 0)) self.assertFalse(check_result) def test_equal(self): """ Verify box comparing. """ b1 = Box(size=(2, 2), bottom_left=(0, 0)) b2 = Box(size=(2, 2), bottom_left=(0, 1)) self.assertEqual(b1, b2) # invalid scenarios check_boxes = [Box(size=(2, 2.1), bottom_left=(0, 0)), Box(size=(2, 3), bottom_left=(0, 0)), Box(size=(1, 1), bottom_left=(0, 0)), Box(size=(2, 2), bottom_left=(0, 0), name="test"), Box(size=(2, 2), bottom_left=(0, 0), kind="test")] for check_box in check_boxes: self.assertNotEqual(b1, check_box)
413524181632130eb94ef936ff18caecd4d47b06
nikhilroxtomar/Fully-Connected-Neural-Network-in-NumPy
/dnn/activation/sigmoid.py
341
4.1875
4
## Sigmoid activation function import numpy as np class Sigmoid: def __init__(self): """ ## This function is used to calculate the sigmoid and the derivative of a sigmoid """ def forward(self, x): return 1.0 / (1.0 + np.exp(-x)) def backward(self, x): return x * (1.0 - x)
d920445ab4b2d6572d12957b661e741be9187a1c
mitakaxqxq/BeloteDeclarations
/test_deck.py
1,552
3.671875
4
import unittest from deck import Deck from card import Card from magic_strings import * class TestDeck(unittest.TestCase): def test_deck_initialization_is_as_expected(self): expected_deck = [Card(seven, clubs), Card(seven, diamonds), Card(seven, hearts), Card(seven, spades), Card(eight, clubs), Card(eight, diamonds), Card(eight, hearts), Card(eight, spades), Card(nine, clubs), Card(nine, diamonds), Card(nine, hearts), Card(nine, spades), Card(ten, clubs), Card(ten, diamonds), Card(ten, hearts), Card(ten, spades), Card(jack, clubs), Card(jack, diamonds), Card(jack, hearts), Card(jack, spades), Card(queen, clubs), Card(queen, diamonds), Card(queen, hearts), Card(queen, spades), Card(king, clubs), Card(king, diamonds), Card(king, hearts), Card(king, spades), Card(ace, clubs), Card(ace, diamonds), Card(ace, hearts), Card(ace, spades)] test_deck = Deck() self.assertEqual(test_deck.get_cards(),expected_deck) def test_deck_str_is_as_expected(self): expected_string = '7c 7d 7h 7s 8c 8d 8h 8s 9c 9d 9h 9s 10c 10d 10h 10s Jc Jd Jh Js Qc Qd Qh Qs Kc Kd Kh Ks Ac Ad Ah As' test_deck = Deck() self.assertEqual(str(test_deck),expected_string) def test_deck_deal_method_returns_first_8_cards_from_deck_and_then_puts_them_in_its_end(self): test_deck = Deck() expected_list_of_cards = test_deck.get_cards()[:8] first_eight_cards_from_deck = test_deck.deal() self.assertEqual(first_eight_cards_from_deck,expected_list_of_cards) if __name__ == '__main__': unittest.main()
9b7d1f23ad1398410b77ab7e03a81cd582053866
jdegrave/Python
/Chap-11-Exercises/Chap11Exercise4.py
3,706
4.375
4
""" Chapter 11 Exercise 4 - Compute the weekly hours for each employee, order in descending order of hours Author: Jodi A De Grave Date: 4/15/2016 """ def get_hours(max_employees, max_days, week): """ Prompts the user to enter the hours for day for each employee, converts the entries to a float value so they can be summed later. :param max_employees: # each employee is a row in the matrix (defined in main) :param max_days: # each day is a column in the matrix (defined in main) :param week: list of weekday names :return: matrix (2-D list) populated with the each employees hours """ matrix = [] print("\nEnter the hours for each day the employee worked. Enter all hours worked for all employees.") print("Use a", max_days, "day work week.") for employee in range(max_employees): print() # blank row for formatting purposes matrix.append([]) for day in range(max_days): input_string = "Enter the hours for " + week[day]+ " for Employee " + str(employee) + ": " raw_hours = input(input_string).split() hours = [float(x) for x in raw_hours] matrix[employee].append(hours) return matrix def total_hours(m): """ Calculate the total hours for each employee, and store the total and the index (identifier) for the employee in a new 2-D matrix :param m: matrix with each employees hours for each day of the week :return: hours_totals - """ hours_totals = [] i = 0 # index to store employee ID number for emp in m: total = 0 hours_totals.append([]) for hours in emp: total += sum(hours) hours_totals[i].append(total) hours_totals[i].append(i) i += 1 return hours_totals def sort_desc(totals_matrix): """ Sorts the 2D array and then reverses it so employee with greatest number of hours is first in the list :param totals_matrix: 2D unsorted matrix of employee # and total hours for the week :return: totals_matrix sorted in descending order """ totals_matrix.sort() totals_matrix.reverse() return totals_matrix def print_results(final_matrix): """ Prints a table with headers, listing each employee's identifier and total hours for the week in descending order by hours :param final_matrix: sorted 2-D array (descending order by total hours) :return: None """ print((format("\nEmployee #", "20s")), (format("Total Hrs", "20s"))) for row in range(len(final_matrix)): column = 0 print((format(str(final_matrix[row][(column + 1)]), ">5s")), end="\t ") print(format(float(final_matrix[row][column]), ">20.1f")) def main(): """ Initializes: -- max # of week days in the week -- max # of employees -- a list called "WEEK" for the names of the week Main calls get_hours to create a 2D matrix of employees and their hours for each day of the week Main calls total_hours to create a 2D matrix with just the total hours for each employee and the employee ID # Main calls sort_desc to sort the total _hours matrix in descending order by total hours Main calls print_results to display a table showing each employee # and total hours for the week, descending order by total hours :return: None """ MAX_DAYS = 7 MAX_EMPLOYEES = 8 WEEK = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] matrix = get_hours(MAX_EMPLOYEES, MAX_DAYS, WEEK) total_emp_hours = total_hours(matrix) sort_desc(total_emp_hours) print_results(total_emp_hours) main()
eff5a19685ea9a69f0a1b897e0d57984db2eee05
jdegrave/Python
/Chap-07-Exercises/Chap7Exercise3.py
1,711
3.9375
4
class Account: def __init__(self, id : str = 0, balance = 100, annual_interest_rate = 0): """ The constructor that accepts values for the fields :param id: account identifier :param balance: account balance :param annual_interest_rate: annual interest rate; entered as a decimal (4.25% is 4.25) :return: None """ self.__id = id self.__balance = balance self.__annual_interest_rate = annual_interest_rate def get_id(self): return self.__id def get_balace(self): return self.__balance def get_annual_interest_rate(self): return self.__annual_interest_rate def get_monthly_interest_rate(self, annual_interest_rate): monthly_interst_rate = annual_interest_rate * 100/12 return monthly_interst_rate def get_monthly_interest(self): change_percent = (self.__previous_closing_price - self.__current_price) / self.__previous_closing_price if self.__previous_closing_price > self.__current_price: change_percent *= -1 return change_percent def withdraw (self, withdrawal_amount): if (withdrawal_amount > self.__balance): print ("Withdrawal Amount exceeds balance. Withdrawal not accepted.") else: self.__balance-=withdrawal_amount return(self.__balance) def deposit (self, deposit_amount): self.__balance += deposit_amount return self.__balance def main(): my_stock = Stock('INTC', 'Intel Corporation', 20.5, 20.35) print('The percent change in stock', my_stock.get_stock_symbol(), 'is', format(my_stock.get_change_percent(),".2f"), '%') main()
dc3150354777b7972b31880b827304414bce406b
RealityCtrl/QuickPython
/Modules/wo.py
939
3.9375
4
"""wo module. Contains function: words_occur()""" #interface functions def words_occur(): """words_occur: count the number of occurrences of words in a fil""" #prompt the user for the name of the file to use file_name = input("Enter the name of the file: ") #Open the file. read the file and store the words in the list. try: with open(file_name,"r") as file: word_list = file.read().split() #count the number of occurrences in the file occurs_dictionary = {} for words in word_list: occurs_dictionary[words] = occurs_dictionary.get(words, 0) + 1 print("file %s has %d words (%d are unique)" % (file_name, len(word_list), len(occurs_dictionary))) print(occurs_dictionary) except IOError as error: print("%s: could not be opened: %s" % (file_name, error.strerror)) if __name__ == '__main__': words_occur()
f05d5827d9a44c27034d6b64dd4b0d8106040d37
sm2774us/leetcode_hackerrank_codesignal_practice
/dynamic_programming/leetcode/python/leet_code_118.py
2,466
3.765625
4
from typing import List # Iterative Solution # TC: O(N^2) ; SC: O(N^2) class Solution: def generate(self, n: int) -> List[List[int]]: ans = [[1]*i for i in range(1, n+1)] # initialize triangle with all 1 for i in range(1, n): for j in range(1, i): ans[i][j] = ans[i-1][j] + ans[i-1][j-1] # update each as sum of two elements from above row return ans # Recursive Solution # TC: O(N^2) ; SC: O(N^2) class Solution: def generate(self, n: int) -> List[List[int]]: def helper(n): if n: helper(n-1) # generate above row first ans.append([1]*n) # insert current row into triangle for i in range(1, n-1): # update current row values using above row ans[n-1][i] = ans[n-2][i] + ans[n-2][i-1] ans = [] helper(n) return ans # Math-Based Solution: "n-choose-k formula for binomial coefficients" # We calculate C(n, k) by this relation: C(n, k) = C(n, k-1) * ((n+1-k) / k), and C(n, 0) = 1 # TC: O(N^2) ; SC: O(N^2) # # Note: itertools.accumulate() => Argument: p[,func] # Results : p0, p0+p1, p0+p1+p2, … # Example : accumulate([1,2,3,4,5]) --> 1 3 , 6 , 10 , 15 # 1, 1+2 , 1+2+3, 1+2+3+4, 1+2+3+4+5 from itertools import accumulate class Solution: # Source: https://stackoverflow.com/a/3025547 def bin_coeff(self, n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def generate(self, numRows: int) -> List[List[int]]: results = [] for row in range(0, numRows): next_row = [self.bin_coeff(row, i) for i in range(0, row + 1)] results.append(next_row) return results # # Only works w/ Python 3.8 and above # # the initial argument to itertools.accumulate() was only introduced in Python 3.8 # def generate(self, numRows: int) -> List[List[int]]: # return [[*accumulate(range(1, i), lambda s, j: s*(i-j)//j, initial=1)] for i in range(1, numRows+1)]
a5f84dc8b42d8603837e358733c49023625d63ea
LEllingwood/NCAA_bracket
/4_utility_functions.py
1,634
4.09375
4
from tabulate import tabulate import csv import matplotlib import matplotlib.pyplot as plt # This function allows user to pick a name and get the school's unique id and prints a table view of the complete list of teams. def return_school_info(): school_name = input("Enter a team name: ").title() with open('complete_list.csv') as information: data = csv.reader(information) data = list(data) print(tabulate(data, tablefmt='grid')) for line in data: if line[1] == school_name: print('School Name: ', school_name) print('School ID: ', line[0]) print('Conference: ', line[3]) print('Location: ', line[4]) print('Colors: ', line[6]) print('Mascot: ', line[8]) return {"school_name": line[1], "color1": line[6].split(", ")[0], "color2": line[6].split(", ")[1]} print("No such School! Check your spelling!") def show_color(school_info): fig = plt.figure() ax = fig.add_subplot(111) plt.text(2, 30, school_info["school_name"], fontsize=15, ha='left', color='white', va='top') rect1 = matplotlib.patches.Rectangle( (0, 0), 50, 50, color=school_info["color1"]) rect2 = matplotlib.patches.Rectangle( (55, 0), 50, 50, color=school_info["color2"]) print(school_info["color1"], school_info["color2"]) ax.add_patch(rect1) ax.add_patch(rect2) plt.xlim([-10, 120]) plt.ylim([-10, 60]) plt.show() if __name__ == "__main__": school_info = return_school_info() show_color(school_info)
8d0ef3714f25024d94063ced5ecb35798bb504a4
jgarcia525/sf-airbnb-optimizations
/price-estimator.py
1,740
3.59375
4
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style # makes a new list containing only floats, not lists that # contain lists with only one element/value def removeListComplexity(currentList): newList = list() for x in range(len(currentList)): value = currentList[x] value = value[0] newList.insert(x, value) return newList # Given the geo-location (latitude and longitude) of a new property, # estimates the weekly average income the homeowner can make with Airbnb. def calculatePriceEstimation(currentLat, currentLong, latitudeList, longitudeList, priceList): counter = 0 priceTotal = 0 for x in range(len(priceList)): if (currentLat + .005 >= latitudeList[x] and currentLat - .005 <= latitudeList[x]): if (currentLong + .005 >= longitudeList[x] and currentLong - .005 <= longitudeList[x]): counter += 1 priceTotal += priceList[x] return (priceTotal * 7) / counter latitudes = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[48]) latitudes = latitudes.astype(float) latitudeList = latitudes.values.tolist() latitudeList = removeListComplexity(latitudeList) longitudes = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[49]) longitudes = longitudes.astype(float) longitudeList = longitudes.values.tolist() longitudeList = removeListComplexity(longitudeList) prices = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[60]) prices= prices.replace('[\$,]', '',regex=True).astype(float) priceList = prices.values.tolist() priceList = removeListComplexity(priceList) currentLat = 37.7562881782509 currentLong = -122.408737659274 priceEstimate = calculatePriceEstimation(currentLat, currentLong, latitudeList, longitudeList, priceList) print(priceEstimate)
ded1bee452578116f312ac1b4556bc1f42493b15
viraj-kulkarni952/Country-Predictor-Dashboard-App
/dashboard.py
7,475
3.5625
4
import pandas as pd import streamlit as st import plotly.express as px import plotly.graph_objs as go def app(): st.write(""" # Dashboard """) #Sidebar for Year Filter year_choice=st.sidebar.slider("Choose a year:", 1990, 2015, 2015) country_df = pd.read_csv('Country Development Indicators_Visual.csv') country_df_no2016 = country_df.loc[country_df['Year'] !=2016] #Selectbox for Country selected_country=country_df_no2016['Country'].unique() selected_country_list=selected_country.tolist() selected_country_list.insert(0, "All") selected_countries = st.sidebar.multiselect('To select your choice of countries. Uncheck the "All" options then input your choice of countries', selected_country_list, default=selected_country_list[0]) if "All" in selected_countries: selected_countries = selected_country.tolist() #Prepare filtering of data filtered_data_le = country_df_no2016[(country_df_no2016['Year']==year_choice) & (country_df_no2016['Country'].isin(selected_countries))] filtered_data_fg = country_df_no2016[(country_df_no2016['Country'].isin(selected_countries))] filtered_data_aY = country_df_no2016[(country_df_no2016['Country'].isin(selected_countries))] filtered_data_ds = country_df_no2016[(country_df_no2016['Country'].isin(selected_countries))] #World Map of Life Expectancy lifeExpMap = go.Figure(data=go.Choropleth( locations = filtered_data_le['alpha-3'], z = filtered_data_le['Life expectancy'], text = filtered_data_le['Country'], colorscale = 'Bluered', reversescale = True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_title = 'Life Expectancy'),) lifeExpectancyTitle="Life Expectancy by country - {user_year}".format(user_year = year_choice) lifeExpMap.update_layout( title_text=lifeExpectancyTitle, height=600, width=1100, geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ) ) #Data Visuatlisation of gdp ppp per capita vs fertility if filtered_data_aY.empty: fertility_gdp_scatter = px.scatter(data_frame=country_df_no2016, x='GDP PPP Per Capita', y='Fertility rate, total (births per woman)', color='Child Mortality Rate (per 1,000 births)', color_continuous_scale = 'bluered', size='Population', hover_name='Country', size_max=45,range_x=[0, 100000], range_y=[-0.1, 8.5], height=700, width=1100, animation_frame='Year', animation_group="Country", title="Fertility Rate vs. GDP PPP Per Capita", template='none') else: fertility_gdp_scatter = px.scatter(data_frame=filtered_data_fg, x='GDP PPP Per Capita', y='Fertility rate, total (births per woman)', color='Child Mortality Rate (per 1,000 births)', color_continuous_scale = 'bluered', size='Population', hover_name='Country', size_max=45,range_x=[0, 100000], range_y=[-0.1, 8.5], height=700, width=1100, animation_frame='Year', animation_group="Country", title="Fertility Rate vs. GDP PPP Per Capita", template='none') #Data Visualisation of access to water, electricity and cooking fuel acc_elect_title="Access to Electricity (% of population) by Country: 1990-2015" acc_water_title="Access to Improved Water Source (% of population) by Country: 1990-2015" acc_fuel_title="Access to clean cooking fuels (% of population) by Country: 2000-2015" if filtered_data_aY.empty: acc_elect = px.line(country_df_no2016, x='Year', y='Access to electricity (% of population)', color=country_df_no2016['Country'] , hover_name=country_df_no2016['Country'], title=acc_elect_title, width=550) acc_water = px.line(country_df_no2016, x='Year', y='Access to improved water source (% of population)', color=country_df_no2016['Country'] , hover_name=country_df_no2016['Country'], title=acc_water_title, width=550) acc_fuel = px.line(country_df_no2016, x='Year', y='Access to clean fuels and technologies for cooking (% of population)', color=country_df_no2016['Country'] , hover_name=country_df_no2016['Country'], title=acc_fuel_title, width=1100) acc_fuel.update_layout(yaxis_title="Access to clean fuels for cooking (% of population)", showlegend=True) acc_fuel.update_xaxes(range=[2000, 2015]) else: acc_elect = px.line(filtered_data_aY, x='Year', y='Access to electricity (% of population)', color=filtered_data_aY['Country'] , hover_name=filtered_data_aY['Country'], title=acc_elect_title, width=550) acc_water = px.line(filtered_data_aY, x='Year', y='Access to improved water source (% of population)', color=filtered_data_aY['Country'] , hover_name=filtered_data_aY['Country'], title=acc_water_title, width=550) acc_fuel = px.line(filtered_data_aY, x='Year', y='Access to clean fuels and technologies for cooking (% of population)', color=filtered_data_aY['Country'] , hover_name=filtered_data_aY['Country'], title=acc_fuel_title, width=1100) acc_fuel.update_layout(yaxis_title="Access to clean fuels for cooking (% of population)", showlegend=False) acc_fuel.update_xaxes(range=[2000, 2015]) #Diseases related visualisations hiv_death_title="HIV/AIDS Deaths per 100,000" malaria_death_title="Malaria Deaths per 100,000" if filtered_data_ds.empty: hiv_death = px.line(country_df_no2016, x='Year', y='HIV/AIDS Deaths per 100,000', color=country_df_no2016['Country'] , hover_name=country_df_no2016['Country'], title=hiv_death_title, width=550) hiv_death.update_layout(showlegend=False) malaria_death = px.line(country_df_no2016, x='Year', y='Malaria Deaths per 100,000', color=country_df_no2016['Country'] , hover_name=country_df_no2016['Country'], title=malaria_death_title, width=550) malaria_death.update_layout(showlegend=False) else: hiv_death = px.line(filtered_data_ds, x='Year', y='HIV/AIDS Deaths per 100,000', color=filtered_data_aY['Country'] , hover_name=filtered_data_ds['Country'], title=hiv_death_title, width=550) hiv_death.update_layout(showlegend=True) malaria_death = px.line(filtered_data_ds, x='Year', y='Malaria Deaths per 100,000', color=filtered_data_aY['Country'] , hover_name=filtered_data_ds['Country'], title=malaria_death_title, width=550) malaria_death.update_layout(showlegend=True) #Display the visualisations st.plotly_chart(lifeExpMap) st.plotly_chart(fertility_gdp_scatter) acc1,acc2= st.beta_columns(2) acc1.plotly_chart(acc_elect) acc2.plotly_chart(acc_water) st.plotly_chart(acc_fuel) ds1,ds2= st.beta_columns(2) ds1.plotly_chart(hiv_death) ds2.plotly_chart(malaria_death)
16b7faf225937b50bfd8b12515cb45ce5f3f6512
Diana-Doe/homework
/modules/dataADT.py
7,835
3.546875
4
''' Module with ADT class. ''' import json from LinkedList import LinkedDict, LinkedList class DataADT: '''Represents data''' def __init__(self): ''' DataADT -> NoneType ''' self.list = LinkedList() self.categories = LinkedList() self.dates = LinkedList() self.newest = '' self.highestprice = 0 self.lowestprice = 10000 def insert(self, data): ''' DataADT, dict -> NoneType Take only specific data which you can get by using module for scraping. How parameter data should look :: {data} -> {date} -> [{device},..,{device}] ''' # in the first dictionary we have only one data = data['data'] # in second dictionary we have dates as keys and list with # items` dictionaries as values for date, data_list in data.items(): # add date into LinkedList which contains only dates self.dates.add(date) # go through each device in the list for item in data_list: # create LinkedDictionary for each device newDict = LinkedDict() newDict.add(date, 'date') for param, value in item.items(): # as some devices can belong to several categories # - we create the LinkedList for categories if param == 'category': catList = LinkedList() for i in value: catList.add(i) if i not in self.categories: self.categories.add(i) value = catList # convert price into int if param == 'price' and item['price'] != 'Pending': value = int(item['price'].replace(',', '').replace(' ','')) if value > self.highestprice: self.highestprice = value elif value < self.lowestprice: self.lowestprice = value # convert rate into int if param == 'rate': value = int(item['rate'].replace(',', '')) # convert customers into int if param == 'customers' and item['customers'] != "": value = int(item['customers'].replace(',', '').replace(' ','')) elif param == 'customers' and item['customers'] == "": value = 0 newDict.add(value, param) # add created dictionary to main LinkedList self.list.add(newDict) # write the newest date self.newest = date def __len__(self): ''' DataADT -> int Return length of DataADT ''' return len(self.list) def date_count(self): ''' DataADT -> LinkedDict() Counts the number of devices in each available date. Return linked dict whith date as key and number of devices as value. ''' diction = LinkedDict() for item in self.list: if item['date'] in diction: diction[item['date']] = diction[item['date']] + 1 else: diction.add(1, item['date']) return diction def date_count_avail(self): ''' DataADT -> LinkedDict() Counts the number of available devices in each available date. Return linked dict whith date as key and number of available devices as value. ''' diction = LinkedDict() for item in self.list: if item['price'] != 'Pending': if item['date'] in diction: diction[item['date']] = diction[item['date']] + 1 else: diction.add(1, item['date']) return diction def date_customers(self): ''' DataADT -> LinkedDict() Counts the number of available customers in each available date. Return linked dict whith date as key and number of customers as value. ''' diction = LinkedDict() for item in self.list: if item['date'] in diction: diction[item['date']] = diction[item['date']] + item['customers'] else: diction.add(item['customers'], item['date']) return diction def category_count(self,date=None): ''' DataADT, str -> LinkedDict() Counts the number of devices in each category. Return linked dict with catogory as key and number of devices as value. If you don`t enter date it will return data about newest date. Date should look like: 2020-04-20 ''' if date is None: date = self.newest diction = LinkedDict() for item in self.list: for category in item['category']: if item['date'] == date: if category in diction: diction[category] = diction[category] + 1 else: diction.add(1, category) return diction def category_count_avail(self, date=None): ''' DataADT, str -> LinkedDict() Counts the number of available devices in each category. Return linked dict with catogory as key and number of available devices as value. If you don`t enter date it will return data about newest date. Date should look like: 2020-04-20 ''' if date is None: date = self.newest assert date in self.dates, "Not available date." diction = LinkedDict() for category in self.categories: diction.add(0, category) for item in self.list: if item['price'] != 'Pending' and item['date'] == date: for category in item['category']: diction[category] = diction[category] + 1 return diction def price_range(self, lowest, highest, date=None): ''' DataADT, int, int -> LinkedDict() Take lowest and highest price and return all devices that are in range of these prices. If you don`t enter date it will return data about newest date. Date should look like: 2020-04-20 ''' assert lowest <= highest, "Lowest price should be smaller than highest!" assert lowest >= self.lowestprice and highest <= self.highestprice, 'PriceError' if date is None: date = self.newest assert date in self.dates, "Not available date." lst = LinkedList() for item in self.list: if item['price'] != 'Pending' and item['date'] == date: if int(item['price']) in range(lowest, highest+1): lst.add(item) return lst def rate_range(self, lowest, highest, date=None): ''' DataADT, int, int -> LinkedDict() Take lowest and highest rate and return all devices that are in range of these rates. If you don`t enter date it will return data about newest date. Rate should be between 0 and 100. ''' assert lowest <= highest, "Lowest rate should be smaller than highest!" assert lowest >= 0 and highest <= 100, 'RateError' if date is None: date = self.newest assert date in self.dates, "Not available date." lst = LinkedList() for item in self.list: if item['date'] == date: if int(item['rate']) in range(lowest, highest+1): lst.add(item) return lst
d4f033b157ca926c1ba215f9f031eb9c147e2546
hanxianzhao/leetcode--python
/从排序数组中删除重复项.py
1,354
3.734375
4
''' 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 你不需要考虑数组中超出新长度后面的元素。 ''' def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ # 先保留第一个数,后面开始循环。如果和开始的变量相同则删掉,继续查看此处的值 # 直到查看到此处的值不等于开始保留的值得时候,查看的数值加1 # 直到查看的索引大于长度的时候结束 if nums == []: return 0 if len(nums) == 1: return 1 a = 0 b = nums[0] while True: if a + 1 == len(nums): return a + 1 if nums[a + 1] == b: nums.pop(a+1) continue a += 1 b = nums[a] print(removeDuplicates([1,1,2]))
528fd699459c14fed86cdbf97cfbb9e0c9edde5e
hanxianzhao/leetcode--python
/层序遍历二叉树.py
1,182
3.5
4
''' 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] ''' ''' 超过70.25% ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] list2 = [] list2.append([root.val]) list3 = [root] while True: if list3: list4 = [] list1 = [] for i in list3: if i.left: list4.append(i.left) list1.append(i.left.val) if i.right: list4.append(i.right) list1.append(i.right.val) list3 = list4 list2.append(list1) else: break return list2[:-1]
36fc8d1cb13ce05e46b6f6116d94b4e48188a827
hanxianzhao/leetcode--python
/设计问题-最小栈.py
1,470
4.0625
4
''' 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) -- 将元素 x 推入栈中。 pop() -- 删除栈顶的元素。 top() -- 获取栈顶元素。 getMin() -- 检索栈中的最小元素。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2. ''' ''' 超过69.18% ''' class MinStack: def __init__(self): """ initialize your data structure here. """ self.list = [] self.len = 0 self.min = None def push(self, x): """ :type x: int :rtype: void """ self.list.append(x) self.len += 1 if self.min == None: self.min = x if self.min > x : self.min = x def pop(self): """ :rtype: void """ if self.len == 0: return False prev = self.list[-1] self.list.pop(self.len-1) self.len -= 1 if prev == self.min: if self.list == []: self.min = None else: self.min = min(self.list) def top(self): """ :rtype: int """ return self.list[self.len-1] def getMin(self): """ :rtype: int """ return self.min
6ea44bb3fbddd489882f20bdd392b13096a98760
hanxianzhao/leetcode--python
/K个一组翻转链表.py
1,436
3.828125
4
''' 给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。 示例 : 给定这个链表:1->2->3->4->5 当 k = 2 时,应当返回: 2->1->4->3->5 当 k = 3 时,应当返回: 3->2->1->4->5 说明 : 你的算法只能使用常数的额外空间。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 ''' ''' 执行用时: 68 ms, 在Reverse Nodes in k-Group的Python3提交中击败了98.79% 的用户 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ prev = None cur = head next = None check = head n = 0 count = 0 while n < k and check != None: check = check.next n += 1 if n == k: while count < k and cur != None: next = cur.next cur.next = prev prev = cur cur = next count += 1 if next != None: head.next = self.reverseKGroup(next, k) return prev else: return head
a567984ae73c6eb4a893dcf0a1ba5a9823d3776c
hanxianzhao/leetcode--python
/有效的山脉数组.py
824
3.859375
4
''' 给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。 让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组: A.length >= 3 在 0 < i < A.length - 1 条件下,存在 i 使得: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[B.length - 1] 示例 1: 输入:[2,1] 输出:false 示例 2: 输入:[3,5,5] 输出:false 示例 3: 输入:[0,3,2,1] 输出:true ''' ''' 超过78% ''' def func(A): a = -1 i = 0 while i < len(A): if A[i] > a: a = A[i] i += 1 else: break if i == 1 or i == len(A): return False while i < len(A): if A[i] < a: a = A[i] i += 1 else: return False return True
339ecc7f0d448b6079f4f61e1f2be9a05c25d565
lukasz-ortyl/16072019_1
/People.py
2,154
3.9375
4
class Person: def __init__(self, name): self.name = name @property def description(self): return "I am person. My name is {}.".format(self.name) class Student(Person): def __init__(self, name): super().__init__(name) class Doctor(Person): def __init__(self, name, salary): super(). __init__(name) self.salary = salary @property def description(self): return "I am doctor. My name is {}. I have {} zl salary.".format(self.name, self.salary) class Professor: def __init__(self, students): self.students = students #def f(person): # person.name = "Marcin" def f(person): new_person = person person = Student("Ignacy") new_person.name = "Marcin" def g(person): new_person = person person = None person = Student("Kamil") person.name = "Wojciech" new_person.name = ("Natalia") if __name__ == '__main__': p1 = Student("Piotr") p2 = Doctor("Ewa", 5000) p3 = Student("Marysia") p3 = p2 p2 = p1 p3 = p2 g(p3) print(p2.name) print(p3.name) # p2 = p1 #Piotr # f(p1) #Marcin dla p1 # print(p1.name) #Marcin # print(p2.name) #Marcin # student_list = [Student("Piotr"), Student("Ewa")] # professor = Professor(student_list) # student_list = [1, 2, 3] # print(student_list) # print(professor.students) # person_1 = Person("Piotr") # person_2 = Student("Ewa") # person_3 = Doctor("Maciej", 2000) # person_2 = person_3 # f(person_3) # ZAD1 # person_2 = person_3 # person_3.name = "Piotr" # person_3 = Doctor("Tomasz", 5000) # print(person_2.name) # print(person_3.name) # print() # print(person_1.name) # print() # print(person_1.description) # print() # print(person_2.name) # print() # print(person_2.description) # print() # print(person_3.name) # print() # print(person_3.description) # print() # person_list = [person_1, person_2, person_3] # for person in person_list: # print(person.description) # person_1 = person_3 # print(person_1.description)
fca8d5354a9bb42359a0be8760e26192aacd8b71
Webkunx/integrals
/Integrals.py
3,293
3.765625
4
from math import pow, sqrt, pi , sin """ f - function in integral , a - bottom limit, b - top limit, n - number of steps, """ f1 = lambda x: pow(x, 2)*sqrt(16 - pow(x,2)) f2 = lambda x , y: 12*y*sin(2*x*y) def wrapper(res, er): print(f'Result calculated w/ my method:{res},\ difference w/ real result:{er}') def rectangles1(f, a, b , n, real_result=0): # Rectangle method for integrals h = (b-a)/n result = f(a+ 0.5*h) for i in range(1,n): result += f(a+i*h+0.5*h) result *= h return result, result - real_result def count_amount_of_steps(f, f_to_count, a, b, real, accuracy, c=0, d=0): """ Count amount of steps for methods. f - method""" n = 1 if c == 0 and d ==0: while True: if abs(f(f_to_count, a , b, n)[0] - real) < accuracy: print(n) break else: n += 1 else: while True: if abs(f(f_to_count, a , b, c,d, n)[0] - real) < accuracy: print(n) break else: n += 1 def trapezium1(f, a, b, n, real_result=0):# Trapezium method for integrals h = (b-a)/n result=(f(a)+f(b))/2 for i in range(1, n): result += f(a+i*h) result *= h return result, result - real_result def simpson1(f, a, b, n, real_result=0): # Simpson's method for integrals h = (b-a)/n result = f(a) + f(b) for i in range(2,n-1,2): result += 2*f(a+i*h) for i in range(1,n,2): result += 4*f(a+i*h) result *= h/3 return result, result - real_result # def rectangles2(f, a, b, c, d, nx, ny): # hx= (b-a)/nx # hy= (d - c)/ ny # result = 0 # for i in range(nx): # for j in range(ny): # xi = a + hx*0.5 + hx* i # yj = c + hy*0.5 + hy * j # result += hx*hy*f(xi,yj) # return result # rect2 = rectangles2(f2, 2, 3 , pi/4, pi/2, 30, 30) # print(rect2) # def trapezium2(f, a, b, c, d, nx, ny): # hx= (b-a)/nx # hy= (d - c)/ ny # result = 0 # for i in range(nx): # for j in range(ny): # xi = a + hx* i # yj = c + hy * j # result += hx*hy*f(xi,yj) # result += (f(a,c) + f(b,d))/2 # return result # trap2 = trapezium2(f2, 2, 3 , pi/4, pi/2, 100, 100) # print(trap2) def simpson2(f, a, b, c, d, n, real_result=0): # Simpson's method for double integrals hx = (b-a)/n hy = (d-c)/n result = 0 for i in range(1,n): for j in range(1,n): if i%2 == 1 and j%2 == 1: result += 4*f(a+hx*i, c + hy*j) elif i%2 == 0 and j%2 == 1: result += 8*f(a+hx*i, c + hy*j) elif i%2 == 1 and j%2 == 0: result += 8*f(a+hx*i, c + hy*j) elif i%2 == 0 and j%2 == 0: result += 16*f(a+hx*i, c + hy*j) result= result*hx*hy/9 return result, result - real_result # count_amount_of_steps(simpson2, f2, 2, 3 , -1, 0.02, pi/4, pi/2) result_rectangles, er_rectangles = rectangles1(f1, 0 , 4 , 107, 16*pi) print("Rectangles method") wrapper(result_rectangles, er_rectangles) result_trapezium , er_trapezium = trapezium1(f1, 0, 4, 242, 16*pi) print("Trapezium method") wrapper(result_trapezium, er_trapezium) result_simpson1, er_simpson1 = simpson1(f1, 0 , 4 , 130, 16*pi) print("Simpson1 method") wrapper(result_simpson1, er_simpson1) result_simpson2, er_simpson2 = simpson2(f2, 2, 3 , pi/4, pi/2, 38, -1) print("Simpson2 method") wrapper(result_simpson2, er_simpson2)
fd6541032678d0628e550f61d41a159710579f1c
AlliesAgainstCOVID/Vulnerablity-Calculator-
/Covid_AGRAJ-master/Gender_Code.py
2,652
3.65625
4
import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import (LinearRegression) def gender_data(a): df = pd.read_csv("Covid_AGRAJ-master/GenderCOVID-19DeathsData.csv") df.drop(df[df['Sex'] != user].index, inplace = True) # Dropping death counts data for other gender group, except the one selected by user columns = df.columns first = columns.get_loc("COVID-19 Deaths") second = columns.get_loc("Total Deaths") deaths = np.array([ ]) totaldeaths = np.array([ ]) # Storing death counts in arrays i = 0 week = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 32, 33, 34 ]).reshape(-1,1) while i < len(df.index): deaths = np.append(deaths, df.iloc[i, first]) # Need to access index[i][first] totaldeaths = np.append(totaldeaths, df.iloc[i, second]) #[i][second ] i += 1 deaths = deaths.reshape(-1,1) # reshaping the array so that it is 2-D totaldeaths = totaldeaths.reshape(-1,1) # reshaping the array so that it is 2-D numericdeaths = np.array([i[0] for i in deaths]) # converting all strings to floats numerictotal = np.array([i[0] for i in totaldeaths]) # converting all strings to floats # Implementing a Linear Regression Model to predict COVID-19 deaths for a certain week model = LinearRegression() fittingmodel = model.fit(week, numericdeaths) #fitting data with a Linear regression line y_plot = model.predict(week[:, np.newaxis].reshape(-1,1)) length = len(week) covid = int(model.predict(week[length-2].reshape(-1,1))) # Using total deaths data to calculate the scale factor that COVID-19 increases or decreases the number of deaths for an gender by alldeaths = int(numerictotal[length-1].reshape(-1,1)) probability = int((covid/alldeaths)*100) # covid-19 deaths / total deaths(including covid-19) return probability gender_data(a) /* OLD CODE import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score def gender_data(a): if (a == 1): val1 = 419.58 + 2088.8*(9) val2 = 419.58 + 2088.8*(8) val3 = ((val1-val2)/val2)*100 final_gender = [] final_gender.append(val3) print(final_gender) return(final_gender) if (a == 2): val1 = 917.36 + 1757.2*(9) val2 = 917.36 + 1757.2*(8) val3 = ((val1-val2)/val2)*100 final_gender = [] final_gender.append(val3) print(final_gender) return(final_gender) gender = input("Enter your gender: \n") g = gender_data(gender) */
8e96a6fcac5695f7f0d47e1cf3f6ecef9382cbbf
janvanboesschoten/Python3
/h3_hours_try.py
275
4.125
4
hours = input('Enter the hour\n') try: hours = float(hours) except: hours = input('Error please enter numeric input\n') rate = input('Enter your rate per hour?\n') try: rate = float(rate) except: rate = input('Error please enter numeric input\n')
ed98b46454cb7865aadfe06077dff076dfd71a73
mujtaba4631/Python
/FibonacciSeries.py
308
4.5625
5
#Fibonacci Sequence - #Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. n = int(input("enter the number till which you wanna generate Fibonacci series ")) a = 0 b = 1 c = a+1 print(a) print(b) for i in range(0,n): c = a+ b print(c) a,b=b,c
bc57bde9b1b37e9c61cf1b8e9bf4563f5f3fa1a3
MatheusBuenoNardi/exercicios
/metros para cm e mm.py
205
3.921875
4
n1 = float(input('Digite um número em metros, ex 4.5:')) cm = int(n1*100) mm = cm*10 print('O seu número em metros, transformado em cm é igual á {}cm e esses cm, em mm é {}mm'.format(cm, mm))
4c99cd87da23da776fff6f9f56348488be10e8d5
zzb15997937197/django-study
/mysite/polls/python_study/dict_demo.py
1,917
4.28125
4
dict_data = {"age": 23, "name": "张正兵"} # 1. items()方法,返回字典的所有键值对,以列表的形式返回可遍历的元组数组 items = dict_data.items() for i in items: print(i) # 2. key in dict 判断键是否在字典里 if "age" in dict_data: print("age is in dict") else: print("age is not in dict") # 3. 可以直接根据键来拿到对应的值 print(dict_data["age"]) # 4. keys()方法,返回该字典的键列表,包含该字典内的所有键 print("获取所有的key", dict_data.keys(), "类型:", type(dict_data.keys())) # 5. get(key,default=None)返回指定的key,如果key不存在,那么返回default值。 print(dict_data.get("address", "不存在!")) # 6. setdefault(key,default=None)设置key的默认值,如果key不存在,那么设置的值为default的值 print(dict_data.setdefault("address", "上海浦东新区")) print(dict_data) # 7.values()方法, values方法,返回一个迭代器,可以用list转换为值列表 print(dict_data.values()) # --> 列表 print(list(dict_data.values())) # 8. pop(key[,default])方法, 返回被删除的key值,如果指定的key值不存在,那么返回设定的default的值。 pop_result = dict_data.pop("add", "666") print("pop_result", pop_result, ",dict_data", dict_data) # 9. popitem()方法,随机返回字典的最后一个键值对。 pop_item = dict_data.popitem() print("pop_item", pop_item, ",dict_data", dict_data) # 10. .fromkeys()方法,根据元组序列来生成一个字典 tuple_data = ("name", "age", "address") print("根据元组生成字典:", dict.fromkeys(tuple_data)) print("当前局部变量", locals()) print("当前全局变量", globals()) dict_data = {"1": 1, "2": 2} print(dict_data) print(dict_data.get("1")) # 取出字典的第二个元素 print("2" in dict_data) print(tuple(dict_data)) # 元组和字典可以相互转换,转换的是字典的keys
1d713170867cbc0a458d3f404fa385cf327b2c5e
AltheFlyer/ECHacks-2018
/plotter.py
1,774
3.71875
4
import sqlite3 import datetime import matplotlib.pyplot as plt from sqlite3 import Error def createTable(db_file, tableName, conn): try: # conn = sqlite3.connect(db_file) c = conn.cursor() values = (tableName) c.execute('CREATE TABLE IF NOT EXISTS plantplants(time TEXT PRIMARY KEY, temperature REAL, light INTEGER, soil INTEGER);') except Error as e: print(e) #finally: # conn.close() def makeGraph(db_file, dependentVariable, conn): try: # conn = sqlite3.connect(db_file) c = conn.cursor() values = [dependentVariable] c.execute('SELECT * FROM plantplants;') result = c.fetchall() print('length' + str(len(result))) for row in result: print(row) except Error as e: print(e) #finally: # conn.close() def getListValues(dependentVariable, conn): try: # conn = sqlite3.connect(db_file) c = conn.cursor() values = [dependentVariable] c.execute('SELECT ' + dependentVariable + ' FROM plantplants;') result = c.fetchall() print('length' + str(len(result))) return result except Error as e: print(e) conn = sqlite3.connect('plant.db') for count, data in enumerate(['soil', 'temperature', 'light']): result = getListValues(data, conn) print(result) count_set = [] for c, i in enumerate(result): count_set.append(c) plt.subplot(3, 1, count + 1) plt.title(data.capitalize()) plt.xlabel("index") plt.ylabel(data) if data == 'soil': plt.ylabel("Soil Humidity") if data == 'temperature': plt.ylabel("temperature (C)") plt.plot(count_set, result) plt.tight_layout() plt.show() plt.close()
8594a70297e1b4eead035a61a603a849684c9550
wolfessential/Homework--Lists-
/Program6 Presidents and Deficits.py
4,076
4.1875
4
#!/usr/bin/env python3 #Names: James Wolf #Date: 10/30/2017 #Program6 Presidents and Deficits #diplay menu def displayMenu(): flag = True while flag: print() print("Deficit List") print("\tList - List the Presidents.") print("\tShow - List the Deficits.") print("\tAdd - Add a President.") print("\tDraw - Draw a Histogram.") print("\tQuit - End Application.") item = input("Enter command first letter: ").lower() if item == "l" or item == "s" or item == "a" or item == "d" or item == "q": flag = False else: print("Error: Invalid input " + ("(")+ item + (")")) return item.lower() #---------------------------function-------------------------------- #Name: ListPresidents(presidents) #Purpose: Will print the list of presidents names list found in main def ListPresidents(presidents): print("List of Presidents") print("-------------------------") if len(presidents) == 0: print("There are no presidents in the list.\n") return else: i = 1 for row in presidents: print ("{:4}{:25}".format((str(i)) + ". " , (row))) i += 1 print() #---------------------------function-------------------------------- #Name: showDeficits(presidents, deficits) #Purpose: Will print the list of presidents names along with deficits list found in main def showDeficits(presidents, deficits): print("List of Presidents and Deficits") print("------------------------------------") if len(presidents) == 0: print("There are no presidents in the list.\n") if len(deficits) == 1: print("There are no presidents in the list.\n") return else: i = 0 for row in deficits: #print ("{:4}{:25}".format((str(i)) + ". " , (row))) #defc = str(deficits[i]) print ("{:4}{:25}{:8}".format((str(i + 1)) + ". " , presidents[i], (row))) i += 1 print() #---------------------------function-------------------------------- #Name: showDeficits(presidents, deficits) #Purpose: Will let you add a new presidents name to add to the presidents list and deficits for that president in billions def addPresident(presidents, deficits): while True: uName = input("Enter presidents name: ") if uName ==(""): print("Please enter something") else: break elif presidents.append(uName): uDeficit = input("Enter the deficit in billions: ") if uDeficit ==(""): print("Please enter something") else: break elif deficits.append(uDeficit): break print(uName + " was added.\n") def main(): #list of presidents presidents = ["Barack H. Obama", "George W. Bush", "William Clinton", "George H. Bush", "Ronald Reagan", "Jimmy Carter", "Gerald Ford", "Richard Nixon", "Lyndon Johnson", "John Kennedy", "Dwight Eisenhower"] #list of deficits deficits = [-6695.00, -3295.00, 63.00, -1035.00, -1412.00, -253.00, -181.00, -70.00, -36.00, -18.00, -22.00] #loop main tasks while True: command = displayMenu() if command == "l": ListPresidents(presidents) elif command == "s": showDeficits(presidents, deficits) elif command == "a": addPresident(presidents, deficits) elif command == "d": drawHistogram(Histogram) elif command == "q": break else: print("Not a valid command. Please try again.\n") print("Bye!") if __name__ == "__main__": main()
e0274ffe2e3f25268c16d2d5cae9484994913f06
anjali-goyal/Guvi
/larg.py
211
3.578125
4
no=list(map(int,input().split())) if no[0]>no[1]: if no[0]>no[2]: print(no[0]) else: print(no[2]) else: if no[1]>no[2]: print(no[1]) else: print(no[2])
93b3333da4d858b1e37a0877c807648204685d92
leeejin/python_
/Assignment_7weeks/이수진_과제7.py
566
3.84375
4
import turtle #1번 t= turtle.Turtle() t.shape('turtle') def cCircle(r): t.penup() t.goto(0,-r) t.pendown() t.circle(r) t.penup() t.home() t.pendown() return r print(cCircle(100)) print(cCircle(70)) print(cCircle(40)) #2번 def number2(x): y="" while x>0: y=str(x%2)+y x//=2 print(y) def number10(bi_num): d = 0 bnum = str(bi_num) for i, digit in enumerate(bnum): d += int(digit) * pow(2,len(bnum)-1-i) print(d) number2(int(input('10진수 :'))) number10(int(input('2진수 :')))
9802e59ff55033fe68edde3d48636d2ea29dec0f
leeejin/python_
/Assignment_6weeks/while&random.py
563
3.578125
4
#while문 n=1 sum=0 while n<=10: sum=sum+n n=n+1 print("1~10까지의 합:",sum) n=1 sum=0 while sum<=500: n=n+1 sum=sum+n print("1~",n,"까지의 합:",sum) #random함수 import random n=0 while n!=4: n = random.randint(0,9) print(n) #random함수 예제 print("1~100사이의 숫자를 맞추시오") count=0 n=0 idk = random.randint(1,100) while n!=idk: n = int(input("숫자 입력 : ")) count=count+1 if n<idk: print("높음!") elif n>idk: print("낮음!") print(count,"번째",n,"찾음.")
1bd13b7ee2926aa9d6ff628a73e29670df365db0
leeejin/python_
/Assignment_5weeks/6W_ex2.py
172
3.765625
4
year = int(input('연도 입력:')) if year % 4 == 0 and year % 100 !=0 or year % 400 ==0 : print(year,'년은 윤년') else: print(year,'년은 윤년이 아님')
2704776a68a38df97a4da6804cac97f4091b5bad
leeejin/python_
/Assignment_5weeks/6W_ex3.py
261
3.65625
4
n1 = int(input('자연수1:')) n2 = int(input('자연수2:')) if n1>n2: print('목:',n1/n2,'나머지:',n1%n2) if n2==0: print('Divide by zero') if n2>n1: print('목:',n2/n1,'나머지:',n2%n1) if n1==0: print('Divide by zero')
e5ac62bf94ebed61c325625e82010ca8bfa5866f
lusan/Seismic-activity-monitor--SAM-
/ManipulateData.py
813
3.6875
4
#csv is pretty fun to work with, we just need the latitude and longitude for #each earthquake. #This code will attempt at extracting only the latitude and longitude #Open the earthquake data file data_file = open('C:\Python27\Py Pro\SAM\dataset.csv') #Create emmpty lists for the latitudes and longitudes. lats, lons = [], [] #Read through the entire file, skip the first line, #and pull out just the lats and lons. for index, line in enumerate(data_file.readlines()): if index > 0: lats.append(float(line.split(',')[1])) lons.append(float(line.split(',')[2])) #display the first 5 lats and lons print('lats', lats[0:5]) print('lons', lons[0:5]) #Result is a success #('lats', [33.8315, 64.3938, 63.5187, 32.817, 38.847332]) #('lons', [-117.5058333, -147.3162, -146.7338, -116.6506667, -122.0111694])
407292d2ade8b8e522fb9e405cbbe599d4f6e2d8
lusan/Seismic-activity-monitor--SAM-
/SplittingData.py
989
3.78125
4
#The US government maintains a set of live feeds of earthquake-related data from recent seismic events #For this project I will use a dataset that contains all seismic events over the last #seven days, which have a magnitude of 1.0 or greater. #In my project I will be parsing a file in the csv format also known as #comma-separated value, after its success I will try json format, but thats a different story :P #http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.csv #The above link contains live seismic events over the last seven days, updated every five minutes data_file = open('C:\Python27\Py Pro\SAM\dataset.csv') for index, line in enumerate(data_file.readlines()): print(line.split(',')) if index == 1: break #Data stored in csv format makes it easier for us to process. #We process the file by reading each line of the file into our program, #splitting each line at the commas, and storing the data we care about in the program #The result is a success
6f174ec937772f9b9896995c9bb1093fb97234f2
Carlos-Alberto-Gallego-Benitez/interfaces_garficas_python
/imgen en interfaz.py
669
3.609375
4
from tkinter import * #importamos la libreria de tkinter para crear interfaces root = Tk() #creamos la interfaz root.title("Carlos Python") #nos permite darle un titulo a la interfaz root.resizable(1,1) #nos permite controlar las margenes de interfaz root.iconbitmap("dr4.ico") #con esta linea le damos la imagen de icono imagen = PhotoImage(file = "facelog.png")#con est linea seleccionamos la imagen y la guardamos en una variable label = Label(root, image = imagen)#con esta linea agregamos la imagen al label label.pack()# con esta linea empaquetamos root.mainloop() # nos permite que la interfaz grafica se mantenga abierta es indispensable utilizar el mainloop
efa386834b4abbbc7db92129b275892b22ca1178
Carlos-Alberto-Gallego-Benitez/interfaces_garficas_python
/Buttointerfaz.py
1,950
4.03125
4
from tkinter import * #importamos la libreria de tkinter para crear interfaces root = Tk() #creamos la interfaz root.title("Carlos Python") #nos permite darle un titulo a la interfaz def Sumar(): #creando metodo sumar if(var1.get()==""): resultado.set("llene el campo uno") elif(var2.get()==""): resultado.set("llene el campo dos") else: resultado.set(int(var1.get())+ int(var2.get())) #linea para combertir dato de string a numero para operacion def Restar():#creando metodo restar if (var1.get() == ""): resultado.set("llene el campo uno") elif (var2.get() == ""): resultado.set("llene el campo dos") else: resultado.set(int(var1.get()) - int(var2.get())) # linea para combertir dato de string a numero para operacion var1 = StringVar() #declarando las variables var2 = StringVar() resultado = StringVar() entrada1 = Entry(root) #entrada de texto entrada1.pack() entrada1.config(bd=10, font = "Curier,20", justify="center", textvariable = var1) #doy margenes colores y agrego las variables que van recibir el valor entrada2 = Entry(root) #entrada de texto entrada2.pack() entrada2.config(bd=10, font = "Curier,20", justify="center", textvariable = var2) #doy margenes colores y agrego las variables que van recibir el valor entrada3 = Entry(root) #entrada de texto entrada3.pack() entrada3.config(bd=10, font = "Curier,20", justify="center", state="disable", textvariable = resultado) #doy margenes colores y agrego las variables que van recibir el valor boton = Button(root, text = "Sumar") boton.pack() boton.config(bg = "Gray", padx = 18, pady = 10, command = Sumar) #con el command se llama a la funcion que hace la operacion boton = Button(root, text = "Restar") boton.pack() boton.config(bg = "Red", padx = 18, pady = 10, command = Restar) root.mainloop() # nos permite que la interfaz grafica se mantenga abierta es indispensable utilizar el mainloop
bbbdd61104379bc3d36231a61fd9fedf1dc3a77c
Oath-of-the-Peach-Garden/Zhang-Fei
/Level1/question16to20.py
1,850
3.765625
4
# 16) 문자열 내 마음대로 정렬하기 # https://programmers.co.kr/learn/courses/30/lessons/12915 # 20분 고민하고 아닌것같아서 다른방법 모색 # 1트 # def solution_16(strings, n): # answer = [] # dict_s = {} # set_answer = {} # for s in strings: # dict_s[s] = s[n] # d_values = list(dict_s.values()) # d_values.sort() # # print(d_values) # for d in d_values: # for k, v in dict_s.items(): # if d == v: # answer.append(k) # set_answer = set(answer) # # print(set_answer) # return list(set_answer) # 2트 # index로 뽑아낸 값을 문자열의 맨 앞에다 붙인 후, 정렬 # 그것을 문자열slice 해서 1번째index부터 맨 끝까지 출력해내면 됨 def solution_16(): strings = ['abce', 'abcd', 'cdx'] n = 2 answer = [] tmp = [] index_s = '' for s in strings: index_s = s[n] s = index_s + s tmp.append(s) tmp.sort() for t in tmp: answer.append(t[1:]) print(answer) return answer # 18) 문자열 내림차순으로 배치하기 # https://programmers.co.kr/learn/courses/30/lessons/12917 def solution_18(s): answer = '' temp = [] #아스키의 역순 temp = list(map(ord,s)) temp.sort(reverse=True) temp = list(map(chr,temp)) answer = ''.join(temp) return answer # 19) 문자열 다루기 기본 # https://programmers.co.kr/learn/courses/30/lessons/12918 def solution_19(s): answer = True #일단 길이가 4 또는 6일때 if len(s) == 4 or len(s) == 6: for i in range(len(s)): if not 47 < ord(s[i]) < 58: return False break else: answer = False return answer
34ed88335ee54f4e5bc0e860cee23ba146188c4e
Oath-of-the-Peach-Garden/Zhang-Fei
/Level2/lv2_q10.py
544
3.5625
4
# 10) 행렬의 곱셈 # https://programmers.co.kr/learn/courses/30/lessons/12949 def solution(arr1, arr2): answer = [] for i, a1 in enumerate(arr1): tmp_arr = [] for j in range(len(arr2[0])): tmp = 0 for k in range(len(arr2)): a = a1[k] # print('a', a) b = arr2[k][j] # print('b', b) tmp += a*b tmp_arr.append(tmp) # print(tmp_arr) answer.append(tmp_arr) return answer
108d56e2b0df4e64e7a1d1f2c076d1043cc22e15
philipwerner/data-structures
/src/test_merge_sort.py
1,249
3.625
4
"""Test module for merge_sort.""" import pytest from merge_sort import merge_sort sb_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] bs_list = [9, 8, 7, 6, 5, 4, 3, 2, 1] uo_list = [56, 3, 78, 79, 34, 22, 87, 1, 23] short = [19, 3] three_list = [19, 56, 5] one_list = [9345] def test_merge_sort_with_numerical_ordered_list(): """Test that a already sorted list returns how it went in.""" merge_sort(sb_list) assert sb_list == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_merge_sort_a_simple_sort(): """Test on a reverse numerical list.""" merge_sort(bs_list) assert sb_list == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_merge_sort_on_out_of_order_list(): """Test sorting a non numerical list.""" result = merge_sort(uo_list) assert result == [1, 3, 22, 23, 34, 56, 78, 79, 87] def test_merge_sort_on_list_of_2(): """Test that merge sort can sort small lists.""" result = merge_sort(short) assert result == [3, 19] def test_merge_sort_on_list_of_3(): """Test that merge sort can sort small lists.""" result = merge_sort(three_list) assert result == [5, 19, 56] def test_merge_sort_with_list_length_of_1(): """Test that merge sort returns a 1 length list.""" assert merge_sort(one_list) == [9345]
d1eb780079162d3320041c6983921fed9d5b17cd
philipwerner/data-structures
/src/bubble_sort.py
987
3.578125
4
"""Bubble sort module.""" def b_sort(ilist): """Bubble sorting function.""" if isinstance(ilist, list): for numbers in range(len(ilist) -1, 0, -1): for i in range(numbers): if ilist[i] > ilist[i + 1]: num_holder = ilist[i] ilist[i] = ilist[i + 1] ilist[i + 1] = num_holder return ilist else: raise TypeError('Bubble sort is for lists only') if __name__ == '__main__': # pragma no cover import timeit as ti sort_1 = [1, 2, 4, 9, 10, 11] sort_2 = b_sort([17, 9, 7, 4, 1, 0]) time_1 = ti.timeit("b_sort(sort_1)", setup="from __main__ import sort_1, b_sort") time_2 = ti.timeit("b_sort(sort_2)", setup="from __main__ import sort_2, b_sort") print(""" Input: [1, 2, 4, 9, 10, 11] Good case: {} Input: [17, 9, 7, 4, 1, 0] Bad case: {}""".format(time_1, time_2))
0756d9cfa339f77fccd5e824fb2c4142dbc72be2
Dan-Elioth/Examen-Unidad-1
/Antecedente del examen/Ejercicio2.py
495
3.65625
4
print("Buen dia") #Variables salariomin=930 #Datos de entrada puntos=int(input("Ingrese los puntos que obtuvo por su desempeño laboral:" )) salariomin=int(input("Ingrese el sueldo minimo:\nTeniedo en cuenta que el salario minimo en el Perú es de=930\n")) #Proceso if puntos>=50 and puntos<=100: bonofinal=salariomin*0.10 elif puntos>=101 and puntos<=150: bonofinal=salariomin*0.40 elif puntos>=151: bonofinal=salariomin*0.70 #Datos de salida print(f"Su bono es de: ${bonofinal:.2f}")
2ddc4abc64069852fdd535b49a26f5712463f14a
nathanandersen/SortingAlgorithms
/MergeSort.py
1,122
4.25
4
# A Merge-Sort implementation in Python # (c) 2016 Nathan Andersen import Testing def mergeSort(xs,key=None): """Sorts a list, xs, in O(n*log n) time.""" if key is None: key = lambda x:x if len(xs) < 2: return xs else: # sort the l and r halves mid = len(xs) // 2 l = mergeSort(xs[:mid],key) r = mergeSort(xs[mid:],key) # merge them r together return merge(l,r,key) def merge(l,r,key): """A merge routine to complete the mergesort.""" result = [] l_ptr = 0 r_ptr = 0 while (l_ptr < len(l) or r_ptr < len(r)): if l_ptr == len(l): # if we have added everything from the l result.extend(r[r_ptr:]) return result elif r_ptr == len(r): # we have added everything from the r result.extend(l[l_ptr:]) return result elif key(l[l_ptr]) < key(r[r_ptr]): result.append(l[l_ptr]) l_ptr += 1 else: result.append(r[r_ptr]) r_ptr += 1 if __name__ == "__main__": Testing.test(mergeSort)
daaa289679afe0ecba042f00db39f0953ad55859
tdiede/coding_problems
/hackbright_challenges.py
14,943
4.25
4
# These are the coding challenges I have worked through. # medium, below # # Concepts: Dictionaries, General # def is_anagram_of_palindrome(word): # """Is a word an anagram of a palindrome? # >>> is_anagram_of_palindrome("a") # True # >>> is_anagram_of_palindrome("ab") # False # >>> is_anagram_of_palindrome("aab") # True # >>> is_anagram_of_palindrome("arceace") # True # >>> is_anagram_of_palindrome("arceaceb") # False # """ ######################################################### ######################################################## # # want to count whether each letter appears an even number of times # # one letter can appear an odd number of times # # seen = [] # # i = 0 # # for i in range(len(word)): # # if word[i] not in seen: # # seen.append(word[i]) # # else: # # seen.remove(word[i]) # # if len(seen) <= 1: # # return True # # return False # seen = {} # i = 0 # for i in range(len(word)): # count = seen.get(word[i], 0) + 1 # seen[word[i]] = count # seen_odd = False # for value in seen.itervalues(): # if value % 2 != 0: # if seen_odd: # return False # seen_odd = True # return True # # Binary Search # def binary_search(val): # """Using binary search, find val in range 1-100. Return # of guesses. # >>> binary_search(50) # 1 # >>> binary_search(25) # 2 # >>> binary_search(75) # 2 # >>> binary_search(31) <= 7 # True # >>> max([binary_search(i) for i in range(1, 101)]) # 7 # """ # assert 0 < val < 101, "Val must be between 1-100" # num_guesses = 0 # return num_guesses # Concepts: Recursion def count_recursively(lst): """Return the number of items in a list, using recursion. >>> count_recursively([]) 0 >>> count_recursively([1, 2, 3]) 3 """ if not lst: return 0 lst.pop() return count_recursively(lst) + 1 # Concepts: Loops def decode(s): """Decode a string into the original text. >>> decode("0h") 'h' >>> decode("2abh") 'h' >>> decode("0h1ae2bcy") 'hey' """ text = '' for idx, char in enumerate(s): if char.isdigit(): letter_index = idx + int(char) + 1 text += s[letter_index] return text # Concepts: Runtime, General def missing_number_scan(nums, max_num): """Find the missing number in a list. *nums*: list of numbers 1..[max_num]; exactly one digit will be missing. *max_num*: Largest potential number in list >>> missing_number_scan([2, 1, 4, 3, 6, 5, 7, 10, 9], 10) 8 >>> missing_number_scan([2, 1, 4, 3, 6, 5, 7, 10, 9], 10) 8 """ # my initial solution has potentially terrible runtime!?! temp_stack = set() idx = 0 # O(n) for idx in range(1, max_num+1): temp_stack.add(idx) # O(n) to create set from nums, plus O(n) to check between sets diff = temp_stack - set(nums) (missing,) = diff return missing # 1st solution, O(n) and requires additional storage: # Keep track of what you've seen in a separate list, at False index is missing number. def missing_number_n_extralist(nums, max_num): seen = [False] * max_num for n in nums: seen[n - 1] = True return seen.index(False) + 1 # 2nd solution, O(n log n) and does not require additional storage: # Sort list first, then scan for missing number. def missing_number_nlogn(nums, max_num): nums.append(max_num + 1) nums.sort() last = 0 for num in nums: if num != last + 1: return last + 1 last += 1 raise Exception("None are missing!") # 3rd solution: find missing number by comparing expected sum vs actual def missing_number_n(nums, max_num): expected = sum(range(max_num + 1)) # sum of 1..n # expected = ( n + 1 ) * ( n / 2 ) return expected - sum(nums) # Concepts: General, Math def print_digits(num): """Given an integer, print digits in reverse order, starting with the ones place. >>> print_digits(1) 1 >>> print_digits(314) 4 1 3 >>> print_digits(12) 2 1 """ number = str(num) idx = -1 while abs(idx) <= len(number): print number[idx] idx += -1 # Concepts: Recursion def print_recursively(lst): """Print items in a list using recursion. >>> print_recursively([1, 2, 3]) 1 2 3 """ if lst: print lst[0] print_recursively(lst[1:]) print_recursively([1, 2, 3]) # if idx also passed as argument to function... def print_recursive(lst, idx): if idx == len(lst): return print_recursive(lst, idx+1) print lst[idx], print_recursive([1, 2, 3], 0) # Concepts: Recursion def recursive_index(needle, haystack): """Given list (haystack), return index (0-based) of needle in the list. Return None if needle is not in haystack. >>> lst = ['hey', 'there', 'you'] >>> recursive_index('hey', lst) 0 >>> recursive_index('you', lst) 2 >>> recursive_index('porcupine', lst) is None True """ def _recursive_index(needle, haystack, idx): if idx == len(haystack): return None if haystack[idx] == needle: return idx return _recursive_index(needle, haystack, idx + 1) return _recursive_index(needle, haystack, 0) ######################################################### ######################################################## # Remove Linked List Node # Remove a node from the start/middle of a linked list. # Concepts: Linked Lists # Reverse Linked List # Reverse a linked list, returning a new list. # Concepts: Linked Lists # Sort Sorted Lists # Merge together two already-sorted lists. # Concepts: Loops, Sorting ######################################################### ######################################################## # Concepts: Loops, Strings def split_string(string, delimiter): """Split a string on another, like the Python built-in split. >>> split_string("i love balloonicorn", " ") ['i', 'love', 'balloonicorn'] >>> split_string("that is which is that which is that", " that ") ['that is which is', 'which is that'] >>> split_string("that is which is that which is that", "that") ['', ' is which is ', ' which is ', ''] >>> split_string("hello world", "nope") ['hello world'] """ # my initial solution, only works if delimiter is a single character # split_string = [] # prev = 0 # for idx, char in enumerate(string+delimiter): # if char == delimiter: # split_string.append(string[prev:idx]) # prev = idx # # split_string.append(string[prev:]) # return split_string split_string = [] idx = 0 while idx <= len(string): curr_idx = idx idx = string.find(delimiter, idx) if idx != -1: split_string.append(string[curr_idx:idx]) idx += len(delimiter) else: split_string.append(string[curr_idx:]) break return split_string # easier, below def sum_list(num_list): """Return the sum of all numbers in list. >>> sum_list([5, 3, 6, 2, 1]) 17 """ sum_num = 0 for num in num_list: sum_num += num return sum_num def show_evens(nums): """Given list of ints, return list of *indices* of even numbers in list. >>> lst = [1, 2, 3, 4, 6, 8] >>> show_evens(lst) [1, 3, 4, 5] """ evens = [] i = 0 for i in range(len(nums)): if nums[i] % 2 == 0: evens.append(i) return evens def rev_string(astring): """Return reverse of string. >>> rev_string("porcupine") 'enipucrop' """ i = 0 rev_string = "" for i in range(len(astring)): rev_string += astring[-1-i] return rev_string def rev_list_in_place(lst): """Reverse list in place. >>> lst = [1, 2, 3] >>> rev_list_in_place(lst) >>> lst [3, 2, 1] """ i = 0 for i in range(len(lst)/2): lst[i], lst[-1-i] = lst[-1-i], lst[i] def pig_latin(phrase): """Turn a phrase into pig latin. >>> pig_latin('hello awesome programmer') 'ellohay awesomeyay rogrammerpay' >>> pig_latin('porcupine are cute') 'orcupinepay areyay utecay' >>> pig_latin('give me an apple') 'ivegay emay anyay appleyay' """ pig_latin_string = "" phrase = phrase.split(" ") for word in phrase: pig_latin_word = "" if word[0] not in ['a', 'e', 'i', 'o', 'u']: pig_latin_word = word[1:] + word[0] + 'ay' + ' ' else: pig_latin_word = word + 'yay' + ' ' pig_latin_string += pig_latin_word return pig_latin_string.rstrip(' ') def max_of_three(num1, num2, num3): """Returns the largest of three integers. >>> max_of_three(1, 5, 2) 5 >>> max_of_three(10, 1, 11) 11 """ if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 elif num3 >= num1 and num3 >= num2: return num3 def max_num(num_list): """Returns largest integer from given list. >>> max_num([5, 3, 6, 2, 1]) 6 """ max_num = num_list[0] for num in num_list: if num > max_num: max_num = num return max_num def is_palindrome(word): """Return True/False if this word is a palindrome. >>> is_palindrome("a") True >>> is_palindrome("noon") True >>> is_palindrome("racecar") True >>> is_palindrome("porcupine") False >>> is_palindrome("Racecar") False """ for i in range(len(word)/2): if word[i] != word[-1-i]: return False return True def is_prime(num): """Is a number a prime number? >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(11) True >>> is_prime(999) False """ if num <= 1: return False for i in range(2, num): if num % i == 0: return False return True def fizzbuzz(): """Count from 1 to 20 in fizzbuzz fashion. >>> fizzbuzz() 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz """ i = 1 while i <= 20: if (i % 3 == 0) and (i % 5 == 0): print 'fizzbuzz' elif (i % 3 == 0): print 'fizz' elif (i % 5 == 0): print 'buzz' else: print i i += 1 fizzbuzz() def find_range(nums): """Given list of numbers, return smallest & largest number as a tuple. >>> find_range([3, 4, 2, 5, 10]) (2, 10) >>> find_range([43, 3, 44, 20, 2, 1, 100]) (1, 100) >>> find_range([]) (None, None) >>> find_range([7]) (7, 7) """ min_current = None max_current = None for item in nums: if min_current is None or item < min_current: min_current = item if max_current is None or item > max_current: max_current = item return min_current, max_current def lucky_numbers(n): """Return n unique random numbers from 1-10 (inclusive). # >>> lucky_numbers(2) # [3, 7] >>> lucky_numbers(0) [] >>> sorted(lucky_numbers(10)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ import random nums = range(1, 11) lucky_nums = [] for i in range(n): num = random.choice(nums) nums.remove(num) lucky_nums.append(num) return lucky_nums def is_leap_year(year): """Is this year a leap year? Every 4 years is a leap year:: >>> is_leap_year(1904) True Except every hundred years:: >>> is_leap_year(1900) False Except-except every 400:: >>> is_leap_year(2000) True """ if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True def days_in_month(date): """How many days are there in a month? >>> for i in range(1, 13): ... date = str(i) + " 2016" ... print "%s has %s days." % (date, days_in_month(date)) 1 2016 has 31 days. 2 2016 has 29 days. 3 2016 has 31 days. 4 2016 has 30 days. 5 2016 has 31 days. 6 2016 has 30 days. 7 2016 has 31 days. 8 2016 has 31 days. 9 2016 has 30 days. 10 2016 has 31 days. 11 2016 has 30 days. 12 2016 has 31 days. >>> days_in_month("02 2015") 28 """ month, year = date.split(" ") month = int(month) year = int(year) thirtyone = [1,3,5,7,8,10,12] thirty = [4,6,9,11] if month in thirtyone: days = 31 elif month in thirty: days = 30 else: leap_year = is_leap_year(year) if leap_year is True: days = 29 else: days = 28 return days def concat_lists(list1, list2): """Combine lists. >>> concat_lists([1, 2], [3, 4]) [1, 2, 3, 4] >>> concat_lists([], [1, 2]) [1, 2] >>> concat_lists([1, 2], []) [1, 2] >>> concat_lists([], []) [] """ for item in list2: list1.append(item) return list1 def add_to_zero(nums): """Given list of ints, return True if any two nums in list sum to 0. >>> add_to_zero([]) False >>> add_to_zero([1]) False >>> add_to_zero([1, 2, 3]) False >>> add_to_zero([1, 2, 3, -2]) True >>> add_to_zero([0, 1, 2]) True """ set_nums = set(nums) for n in nums: if -n in set_nums: return True return False ############################################# if __name__ == "__main__": import doctest result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!"
41931c7f28c35995653995bb5f38902b691435ff
AnichkaAleksanyan/homework
/homework35.py
240
3.65625
4
class Max: def __init__(self,myList): self.myList = myList def get_max_dif(self): newList = [myList[i]-myList[i+1] for i in range(len(myList)-1)] return max(newList) myList = [2, 4, 1, 0] a = Max(myList) print(a.get_max_dif())
2a99a40ba7a5c9eb700eea197b8f30e5dfeae8ee
AnichkaAleksanyan/homework
/homework25.py
1,087
3.765625
4
file1 = open("file1.txt","x") file1.write("Hello my name is Ani") file2 = open("file2.txt","w") file2.write("I em from Yerevan") file3 = open("file3.txt") print(file3.read()) file4 = open("file4.txt") print(file4.read()) file5 = open("file5.txt") print(file5.read()) file = open("file1.txt") for row in file: print(row) file = open("file1.txt") for i in range(2): print(file.readline()) file = open("file1.txt","a") file.write("123456789") file = open("file4.txt") c = file.read().split(" ") print(c) maxLen = c[0] for i in c: if len(i) > len(maxLen): maxLen=i print(i) file = open("file4.txt") for row in file: for i in row: if i.isdigit(): print(i) file = open("password.txt","w") login = input("Write your login: ") password = input("Write your password: ") a = login + " " +password file.write(a) print(file.read) file.close() with open("password.txt","w") as file: login = input("Write your login: ") password = input("Write your password: ") a = login + " " +password file.write(a) with open ("password.txt") as file: print(file.read())
f411f0f867d7188d9ccc94b6455ed3995b5350ef
jay-0625/snfl-startup
/20210406/09.py
167
3.671875
4
valueA=int(input("input first value: ")) valueB=int(input("input second value: ")) print ("{}과 {}의 합은 {}입니다." .format(valueA, valueB, (valueA+valueB)))
3377b70aef5e6afef368146c09d7ace66c64a2d4
jay-0625/snfl-startup
/20210406/03.py
126
3.765625
4
valueA=int(input("input first value: ")) valueB=int(input("input second value: ")) output=int(valueA+valueB) print (output)
e5ebc6664d8a478eb57917d1d4932237926dbb2e
jay-0625/snfl-startup
/20210406/11.py
242
3.921875
4
valueA=float(int(input("input first value: "))) valueB=float(int(input("input second value: "))) valueC=float(int(input("input third value: "))) print ("{}, {}, {}의 평균: {}" .format(valueA, valueB, valueC, ((valueA+valueB+valueC)/3)))
00ae39c14eeb5224571007738176968c6084e49a
fancycheung/LeetCodeTrying
/easy_code/TwoPointers/283.movezeros.py
1,009
4.0625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: 283.movezeros.py @time: 2018/9/4/下午5:26 @software: PyCharm """ """ Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ import sys reload(sys) sys.setdefaultencoding("utf8") def moveZeroes(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ count = 0 i = 0 while(i < nums.__len__()): try: if nums[i] == 0: del nums[i] count += 1 i -= 1 else: i += 1 except: break nums.extend([0] * count) print nums if __name__ == "__main__": nums = [0,1,1] moveZeroes(nums) pass
9271a8d0178b59232e546ca5bad73065dbbd285f
fancycheung/LeetCodeTrying
/hard_code/4.medianoftwosortedarray.py
1,183
3.78125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: 4.medianoftwosortedarray.py @time: 2018/8/27/上午9:01 @software: PyCharm """ """ comment here """ import sys reload(sys) sys.setdefaultencoding("utf8") def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums3 = [] i, j = 0, 0 while (i < nums1.__len__() and j < nums2.__len__()): a = nums1[i] b = nums2[j] print a,b if a < b: nums3.append(a) i += 1 else: nums3.append(b) j += 1 if (i == nums1.__len__()): for k in range(j, nums2.__len__()): nums3.append(nums2[k]) if (j == nums2.__len__()): for k in range(i, nums1.__len__()): nums3.append(nums1[k]) length = nums3.__len__() print nums3 if (length % 2 == 1): return nums3[(length - 1) / 2] else: a = nums3[length/2] b = nums3[(length - 2) / 2] return (a + b) * 1.0 / 2 if __name__ == "__main__": a = [1,3] b = [2] c = findMedianSortedArrays(a,b) print c pass
614d2f3dfc383cf24fd979bb2918bef80fda3450
fancycheung/LeetCodeTrying
/easy_code/Linked_List/876.middleofthelinkedlist.py
1,180
4.15625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: 876.middleofthelinkedlist.py @time: 2018/9/3/上午9:41 @software: PyCharm """ """ Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one. Note: The number of nodes in the given list will be between 1 and 100. """ import sys reload(sys) sys.setdefaultencoding("utf8") def middleNode(head): """ :type head: ListNode :rtype: ListNode """ one, two = head, head while two and two.next: one = one.next two = two.next.next return one if __name__ == "__main__": pass
9d9f02dacbf5444bdb52e007c8487859925acf42
sakuma17/PythonTraining
/0203/turtle_race/race.py
967
3.53125
4
import random import turtle ts=[] def setup(): global ts startline=-620 screen=turtle.Screen() screen.setup(1290,720) screen.bgpic('pavement.gif') t_y=[-40,-20,0,20,40] t_color=['blue','cyan','magenta','pink','green'] for i in range(len(t_y)): t=turtle.Turtle() t.shape('turtle') t.penup() t.color(t_color[i]) t.setpos(startline,t_y[i]) #t.pendown() ts.append(t) def race(): global ts finishline=540 t_speed=[[0,10],[0,10],[0,10],[0,10],[2,12]] while True: for current_t in ts: move=random.randint(0,10) current_t.forward(move) x=current_t.xcor() if x >=finishline: winner_color=current_t.color() current_t.write('Win!'+winner_color[0],font=('Arial',16,'normal')) break else: continue break setup() race() turtle.mainloop()
aaae225ce128d60a26bcafc47898baa6fa09f55d
sakuma17/PythonTraining
/my_kame_chan.py
317
4.09375
4
import turtle while True: num=int(input('亀ちゃんに何角形を描いてもらう?(3以上の半角整数)>>')) if(num>=3): break t=turtle.Turtle() t.shape('turtle') if num%2==0: t.left(90) else: t.right(180) for _ in range(num): t.right(360/num) t.forward(100) turtle.mainloop()
888795768259d981db7a30ff6212bb1667cc4d92
sakuma17/PythonTraining
/0218/str_lesson.py
568
3.65625
4
import string letters=string.ascii_letters width=int(input('幅>>')) row_list=list() for i in range(0,len(letters),width): chars=letters[i:i+width] print(chars) row_list.append(chars) print() row=int(input(f'何行目(1~{len(row_list)})>>'))-1 print(row_list[row]) """ count=0 for char in letters: print(char,end='') count+=1 if count%width==0:print() for i in range(len(letters)): print(letters[i],end='') if(i+1)%width==0: print() for i,c in enumerate(letters,1): print(c,end='') if i%width==0: print() """
a1b033719573a0465477e7da65649a4dd7d724a0
sakuma17/PythonTraining
/0204/python_j/jyanken.py
400
3.59375
4
import random hands={0:'グー',1:'チョキ',2:'パー'} while True: you=int(input('手を入力[0:グー,1:チョキ,2:パー]>>')) pc=random.randint(0,2) print(f'あなたは{hands[you]},PCは{hands[pc]}') if you==pc: print('あいこ') continue elif (you-pc+3)%3==2: print('あなたの勝ち') else: print('あなたの負け') break
2e3ae2b6f4c5776b6fca5dc62f198465b5a4dc82
sakuma17/PythonTraining
/0204/python_j/bingo.py
1,078
3.65625
4
import random table=[] COINS=200 TW=3 def createTable(): global table table=[[random.randint(0,9) for j in range(TW)] for i in range(TW)] for row in table: print(row) def countBingoLine(): global table vertical=[[table[j][i] for j in range(TW)] for i in range(TW)] cross=[[table[j][j] if i==0 else table[j][TW-1-j] for j in range(TW)] for i in range(2)] bingo_line=0 for row in table+vertical+cross: if len(set(row))==1: bingo_line+=1 return bingo_line while True: print(f'残り{COINS}枚') bet=int(input(f'BET枚数を入力。0で終了 1-{COINS}>>')) if bet==0: break if bet>COINS: print('コインが不足しています') continue COINS-=bet createTable() bingo_line=countBingoLine() if bingo_line>0: get_coin=bingo_line*12*bet COINS+=get_coin print(f'{bingo_line}LINE BINGO! コイン{get_coin}枚GET!') else: print('boo') if COINS==0: print('コインがなくなりました') break print('Game Over')
4e2ef817bd967563c72eadc6728f80a74cd661b7
sakuma17/PythonTraining
/0201/dictLesson.py
584
4.1875
4
dict1=dict() #空のdict dict1['apple']='りんご' dict1['orange']='みかん' print(dict1) print(len(dict1)) dict1['banana']='ばなな' del dict1['orange'] print(dict1) print(dict1['apple']) # 指定したキーのバリューを取得 #print(dict1['pine']) #無いのでerror print(dict1.get('pine')) #Noneを返す print(dict1.get('banana')) #ばなな if 'apple' in dict1: print('key:appleは含まれている') if 'pine' not in dict1: print('key:pineは含まれていない') if 'りんご' in dict1.values(): print('value:りんごは含まれている')
963bb363e66c32610f504af1403d3830249db35e
sakuma17/PythonTraining
/0129/code1_11.py
369
3.859375
4
age=24 print('浅木先輩の今年の年齢は') print(age) age=age+1 print('来年は') print(age) age=age+1 print('再来年は') print(age) ''' name=input('あなたの名前を入力してください>>') print('おお'+name+'よ、そなたが来るのを待っておったぞ!') ''' x=10 print(type(x)) price=input('料金を入力>>') print(type(price))
075e71f5ce4babd49ccad7883285139abdbe7b9c
sakuma17/PythonTraining
/0204/python_j/dice1.py
252
3.765625
4
import random num=int(input('サイコロを何回ふる?>>')) dices=[random.randint(1,6) for _ in range(num)] """ nums=list() for _ in range(num): nums.append(random.randint(1,6)) """ print(dices) print('合計は{}でした'.format(sum(dices)))
0fd24e4dbfc26052e43d6b7a110912b7f81c5afc
sakuma17/PythonTraining
/games/shiritori.py
709
3.84375
4
print('しりとりスタート!'),print('しりとり') word_set=set() count=0 word='しりとり' while True: count+=1 print(f'{count}ターン目です。') last_char=word[len(word)-1:] word=input(f'[{last_char}]で始まる平仮名を入れてください:') if word[len(word)-1:]=='ん': print('これは[ん]で終わる単語です。あなたの負けです。') break if word[0:1]!=last_char: print('最初の文字が間違っています。あなたの負けです。') break if word in word_set: print('この単語は既に使われています。あなたの負けです。') break else: word_set.add(word)
3fa5033d814359da34cfea5135882365dcb7eb23
FengYusheng/data-structure-and-algorithm
/Algorithms/python3/chapter2_sort/test.py
3,798
3.59375
4
# -*- coding: utf-8 -*- import sys import random import unittest from sort2 import * class TestSort(unittest.TestCase): def test_selection_sort(self): data = ['S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = selection_sort(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) def test_insertion_sort(self): data = ['S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = insertion_sort(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) def test_shell_sort(self): data = ['S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = shell_sort(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) def test_merge(self): data = ['E', 'E', 'G', 'M', 'R', 'A', 'C', 'E', 'R', 'T'] lo = 0 hi = len(data) - 1 mid = int(len(data)/2) if len(data) % 2 else int(len(data)/2) - 1 # mid = lo + int((hi-lo)/2) merge(data, lo, mid, hi) for i in range(len(data)-1): self.assertLessEqual(data[i], data[i+1]) def test_merge_2(self): data = ['E', 'M', 'R'] lo = 0 hi = len(data) - 1 mid = int(len(data)/2) if len(data) % 2 else int(len(data)/2) - 1 merge(data, lo, mid, hi) for i in range(len(data)-1): self.assertLessEqual(data[i], data[i+1]) def test_merge_sort_top_to_bottom(self): data = ['M', 'E', 'R', 'G', 'E', 'S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = merge_sort_top_to_bottom(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) def test_merge_sort_bottom_to_top(self): data = ['M', 'E', 'R', 'G', 'E', 'S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = merge_sort_bottom_to_top2(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) def test_partition(self): data = ['K', 'R', 'A', 'T', 'E', 'L', 'E', 'P', 'U', 'I', 'M', 'Q', 'C', 'X', 'O', 'S'] self.assertEqual(partition(data, 0, len(data)-1), 5) def test_quick_sort(self): data = ['Q', 'U', 'I', 'C', 'K', 'S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] quick_sort(data, 0, len(data)-1) for i in range(len(data)-1): self.assertLessEqual(data[i], data[i+1]) def test_MaxPQ(self): self.assertEqual(len(MaxPQ(5)), 6) self.assertEqual(len(MaxPQ()), sys.maxsize) self.assertTrue(MaxPQ(5).isEmpty()) pq = MaxPQ() data = ['a', 'b', 'c', 'd', 'e'] random.shuffle(data) for i in data: pq.insert(i) pq.printPQ() self.assertEqual(pq.count(), 5) m = pq.delMax() self.assertEqual(m, 'e') pq.printPQ() def test_MaxPQ_2(self): pq = MaxPQ() pq.insert('P') pq.insert('Q') pq.insert('E') self.assertEqual(pq.delMax(), 'Q') pq.insert('X') pq.insert('A') pq.insert('M') self.assertEqual(pq.delMax(), 'X') pq.insert('P') pq.insert('L') pq.insert('E') self.assertEqual(pq.delMax(), 'P') pq.printPQ() def test_heap_sort(self): data = ['S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] sorted_data = heap_sort(data) for i in range(len(sorted_data)-1): self.assertLessEqual(sorted_data[i], sorted_data[i+1]) if __name__ == '__main__': unittest.main()
94d5e1a1270df692b23ea4da0eb91fa968bb8308
WizLuvFromMars/python-tools-poligon
/3.4.py
592
3.609375
4
"""list of common VLANs.""" def int_in_list(a_list): """Convert a_list elements to int type.""" counter = 0 for elem in a_list: a_list[counter] = int(elem) counter += 1 COMMAND1 = "switchport trunk allowed vlan 1,3,10,20,30,100" COMMAND2 = "switchport trunk allowed vlan 1,3,100,200,300" COMMAND_LIST = [COMMAND1, COMMAND2] COMMON_VLAN = [] for element in COMMAND_LIST: ADDIT = element.split()[-1].split(",") int_in_list(ADDIT) COMMON_VLAN.append(ADDIT) # print(set(COMMON_VLAN)) print(set(COMMON_VLAN[0]).intersection(set(COMMON_VLAN[1])))
1a2c0e5eb174b5a0e0765adb4a91b25c98645fcf
arteev/stepik-course-python
/week-3/week-3-7-step3.py
304
3.90625
4
dic = set([input().lower() for _ in range(int(input()))]) text = set() for y in [x.split() for x in [input() for _ in range(int(input()))]]: text.update(y) printed = set() for word in text: if word.lower() not in dic and word.lower() not in printed: print(word) printed.add(word)
3f22d6543bcf3a57be6de92bf126a33667c6563c
ktp-forked-repos/euler
/problem088/problem088.py
2,008
4
4
""" A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak. For example, 6 = 1 + 2 + 3 = 1 × 2 × 3. For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows. k=2: 4 = 2 × 2 = 2 + 2 k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3 k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4 k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2 k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6 Hence for 2≤k≤6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum. In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is {4, 6, 8, 12, 15, 16}, the sum is 61. What is the sum of all the minimal product-sum numbers for 2≤k≤12000? """ from operator import mul from math import inf import timeit from functools import reduce start = timeit.default_timer() all_factors = [] for n in range(2, 14): factors = [2] * n done = False while not done: i = 0 while reduce(mul, factors) <= 24000: all_factors.append(factors[:]) factors[i] += 1 while not done: i += 1 if i >= n: done = True else: tentative = [factors[i] + 1] * (i + 1) + factors[i+1:] if reduce(mul, tentative) <= 24000: factors = tentative break min_prod_sum = {i: inf for i in range(2, 12001)} for factors in all_factors: p = reduce(mul, factors) k = p - sum(factors) + len(factors) if k > 12000: continue if min_prod_sum[k] > p: min_prod_sum[k] = p print(sum(set(min_prod_sum.values()))) stop = timeit.default_timer() print('Runtime:', stop - start) # Answer: 7587457
99dddd51f626d8f59d7627694fb10164bb5db665
ktp-forked-repos/euler
/problem089/problem089.py
1,509
3.671875
4
""" For a number written in Roman numerals to be considered valid there are basic rules which must be followed. Even though the rules allow some numbers to be expressed in more than one way there is always a "best" way of writing a particular number. For example, it would appear that there are at least six ways of writing the number sixteen: IIIIIIIIIIIIIIII VIIIIIIIIIII VVIIIIII XIIIIII VVVI XVI However, according to the rules only XIIIIII and XVI are valid, and the last example is considered to be the most efficient, as it uses the least number of numerals. The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; see About... Roman Numerals for the definitive rules for this problem. Find the number of characters saved by writing each of these in their minimal form. Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units. """ with open('roman.txt') as f: lines = f.readlines() sum_post = 0 sum_pre = 0 for numeral in (line.strip() for line in lines): sum_pre += len(numeral) numeral = numeral.replace('DCCCC', 'CM') numeral = numeral.replace('CCCC', 'CD') numeral = numeral.replace('LXXXX', 'XC') numeral = numeral.replace('XXXX', 'XL') numeral = numeral.replace('VIIII', 'IX') numeral = numeral.replace('IIII', 'IV') sum_post += len(numeral) print(sum_pre - sum_post) # Answer: 743
814834b5f2a274cd90269606e4bc8e569b84f293
javivi595/practica3
/Practica 3/P3E7.py
638
3.921875
4
#P4E7 JAVIER DURAN Pide una fecha, valida si es una fecha correcta y en caso # de serlo le he añadido al ejercicio que cambie el mes alfabeticamente. dia=int(input("Introduce un día:")) mes=int(input("Introduce mes:")) año=int(input("Introduce el año:")) mesalpha={1:"Enero",2:"Febrero",3:"Marzo",4:"Abril",5:"Mayo",6:"Junio",7:"Julio",8:"Agosto",9:"Septiembre",10:"Octubre",11:"Noviembre",12:"Diciembre"} if mes>12 or año>2019 or(mes%2==0 and dia>=31 and mes<7) or (mes%2==1 and dia>=31 and mes>7): print("Fecha invalida") else: print("La fecha seleccionada es {} de {} del año {}".format(dia,mesalpha[mes],año))