blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e90fd0e8711f55357e2c3290ce09db2048bfa45c | itsmonicalara/Coding | /LeetCode/Leetcode 75/Level 1/1480RunningSumof1dArray.py | 243 | 3.859375 | 4 | # TODO:
# Give me the time complexity of this code
def running_sum(numbers):
for i in range(1, len(numbers)):
numbers[i] += numbers[i - 1]
print(*numbers)
if __name__ == "__main__":
nums = [1,2,3,4]
running_sum(nums)
|
7a6d3e0a51bf57437967efc9ea97ddc563d42f2c | chr1sbest/ctci | /python/1_Strings_And_Arrays/1_7.py | 2,063 | 4.03125 | 4 | #@zero_check <- decorator became obsolete
def zero_out(matrix):
"""
If an element in an MxN matrix is 0, set the entire row and column to 0's.
Time complexity: O(n)
Space complexity: O(n)
"""
zero_columns = [] # list is better for iterating over
zero_rows = {} # dict is better for checking membership O(1)
# First pass to collect information on zeroes
for index, row in enumerate(matrix):
if 0 in row:
zero_indexes = [i for i, x in enumerate(row) if x == 0]
zero_columns.append(*zero_indexes)
zero_rows[index] = True
# Second pass to build intermediate matrix with row 0's
int_matrix = [row[:] for row in matrix]
for row_index, row in enumerate(int_matrix):
if row_index in zero_rows:
int_matrix[row_index] = [0] * len(row)
# Third pass to build final matrix with column 0's
final_matrix = [row[:] for row in int_matrix]
for row in final_matrix:
for col_index in zero_columns:
row[col_index] = 0
return final_matrix
if __name__ == "__main__":
row1 = [1, 4, 0]
row2 = [4, 5, 6]
row3 = [0, 8, 9]
matrix = [row1, row2, row3]
zeroed = zero_out(matrix)
print """
{0} => Original
{1}
{2}
{3} => Zeroed
{4}
{5}
""".format(matrix[0], matrix[1], matrix[2],
zeroed[0], zeroed[1], zeroed[2])
################################################################################
def zero_check(func):
"""
**Decorator**
O(nlogn) check to return the matrix early if it doesn't contain zeroes.
Flattens the matrix to 1-D, sorts it, and checks if [0] == 0.
I wrote this decorator hoping to optimize time complexity O(n^2) => O(nlogn)
but my solution ended up being O(n), so it ended up being unnecessary.
"""
def wrapper(matrix):
flat_sorted = sorted(reduce(lambda x, y: x + y, matrix))
if flat_sorted[0] != 0:
return matrix
return func(matrix)
return wrapper
|
bb15fdfcb2dda1632dd0f2cae961cef37f0d872c | VarsharaniLonde/json_parser | /question.py | 4,935 | 3.796875 | 4 | class CustomJsonParser:
"""
Should take a string when initializing the class, convert it to json and
return the json object on CustomJsonParser(jsonString).parse()
"""
def __init__(self, jsonString):
self.jsonString = jsonString
self.jsonParsed = dict()
"""
Write your code here
"""
pass
def parse_value(self, value):
"""
This function accepts a string value and parses it to its typecasts type
"""
if type(value) == type([]) or type(value) == type({}):
value1 = value
else:
strip_value = value.strip().strip('"')
if strip_value.isdigit() is True:
value1 = int(strip_value)
elif strip_value.lower() == "false":
value1 = False
elif strip_value.lower() == "true":
value1 = True
elif strip_value.lower() == "null":
value1 = None
else:
value1 = strip_value
return value1
def parse_list_data(self, index):
"""
This function parses a list value
"""
value_array = []
parsed_value_array = []
array_element = ""
for i in range(index+1, len(self.jsonString)):
# ',' implies key value pair completion hence value is added into the list
if self.jsonString[i] == ',':
array_element1 = self.parse_value(array_element)
value_array.append(array_element1)
array_element = ""
continue
# if ']' is encountered then its the completion of the list and hence list value is returned
elif self.jsonString[i] == ']':
array_element1 = self.parse_value(array_element)
value_array.append(array_element1)
# for item in range(0, len(array_element)):
# parsed_value_array.append(self.parse_value(item))
return value_array, i+1
else:
# if none of the above cases then it's a list element
array_element += self.jsonString[i]
def parse_string_data(self, i=0):
"""
This function accepts an index 'i' which is 0 by default and parses the string starting from index 'i'
and converts it into a json
"""
jsonParsed = dict()
bracket_count = 0
key, value = "", ""
kFlag, vFlag = False, False
while i < len(self.jsonString):
if self.jsonString[i] == '"' or self.jsonString[i] == '\n':
i+=1
continue
elif self.jsonString[i] == '{':
bracket_count += 1
kFlag, vFlag = True, False
if bracket_count > 1:
value, i = self.parse_string_data(i)
i+=1
continue
elif self.jsonString[i] == '[':
# function call to parse a list as the value
value, index = self.parse_list_data(i)
value = self.parse_value(value)
i=index
continue
elif self.jsonString[i] == ':':
# if two colons then the input is faulty so exit
if vFlag is True:
print("INVALID JSON")
exit()
vFlag, kFlag = True, False
i+=1
continue
elif self.jsonString[i] == ',' or self.jsonString[i] == '}':
key1 = key.strip()
value1 = self.parse_value(value)
jsonParsed[key1] = value1
kFlag, vFlag = True, False
if self.jsonString[i] == '}':
return jsonParsed,i
key, value = "", ""
i+=1
continue
# if a character is none of the above special characters,
# then it is a part of a key or value, hence the else block
else:
if kFlag is True:
key+=self.jsonString[i]
elif vFlag is True:
if type(value) == type([]):
i+=1
continue
value+=self.jsonString[i]
i+=1
print("INVALID JSON")
def parse(self):
# This function returns the parsed json
self.jsonParsed, i = self.parse_string_data()
"""
Dont touch the return statement, your code will be evaluated by the return value of this function
"""
return self.jsonParsed
|
c880bb5e9f80b93be97a5851ff2dde36a5b48941 | r50206v/Leetcode-Practice | /2022/*Easy-136-SingleNumber.py | 870 | 3.546875 | 4 | '''
hashtable
time: O(N)
space: O(N)
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
from collections import Counter
count = Counter(nums)
for k in count.keys():
if count[k] == 1:
return k
return
'''
math
2*(a+b+c) - (a+a+b+b+c) = c
time: O(N)
space: O(N)
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2 * sum(set(nums)) - sum(nums)
'''
bit manipulation
using XOR
a XOR 0 = a
a XOR a = 0
a XOR b XOR a = (a XOR a) XOR b = 0 XOR b = b
time: O(N)
space: O(1)
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a |
9f9254b2f919ad367775f1760bb75f858e896919 | OhadVal/Monty-Hall | /monty_hall_problem.py | 11,806 | 4.03125 | 4 | from tkinter import *
import tkinter.messagebox
import random
import os
# defining the game class
class MontyHallGame:
def __init__(self):
self.window = Tk() # initializing the gui window
self.window.title("Monty Hall Game") # setting the title for the window
self.doorColor = "#242582"
self.doorNum = 0
self.gifts = ["car", "goat", "goat"]
self.selectedDoor = ""
self.btns = []
self.changedDoorWins = 0
self.changedDoorLoss = 0
self.maintainedDoorWins = 0
self.maintainedDoorLoss = 0
# creating a menu bar
menubar = Menu(self.window) # initializing the menu bar
self.window.config(menu=menubar) # displaying the menu bar
# Create a pull-down menu, and add it to the menu bar
operationMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Options", menu=operationMenu)
operationMenu.add_command(label="Help", command=self.help)
operationMenu.add_command(label="About", command=self.about)
operationMenu.add_separator()
operationMenu.add_command(label="Exit", command=self.exit)
# frame for welcome message and game instructions
frame0 = Frame(self.window)
frame0.grid(row=1, column=1, sticky=W) # frame is in row 1 and column 1 and sticking to the West
self.msgCanvas = Canvas(frame0, width=800, height=200, bg="white") # canvas is inside the frame0
self.msgCanvas.pack()
self.welcomeMsg = self.msgCanvas.create_text(400, 20, fill="#f64c72", font="Helvetica 15 bold",
text="Welcome to the Monty Hall Game!")
# button that starts game
self.startGameBtn = Button(self.msgCanvas, fg="white", bg="blue", text="Start Game", command=self.startGame)
self.startGameBtn.place(x=350, y=40)
self.instructionMsg1 = self.msgCanvas.create_text(400, 155, fill="#553d67", text="")
self.firstDoorChoice = self.msgCanvas.create_text(400, 90, fill="#553d67", text="")
self.secondDoorChoice = self.msgCanvas.create_text(400, 120, fill="#553d67", text="")
self.instructionMsg2 = self.msgCanvas.create_text(400, 170, fill="#553d67", text="")
# creating frame1 inside window. This frame contains the doors
frame1 = Frame(self.window)
frame1.grid(row=2, column=1) # placing frame1 in row 2 and column 1
self.canvas = Canvas(frame1, width=800, height=400, bg="white")
self.canvas.pack()
self.btn1 = Button(self.canvas, bg="#47201d", text="Door 1", padx=60, pady=145, state="disabled", command=lambda: self.setDoorNum(1),
fg="white")
self.btn1.place(x=80, y=35)
door1 = self.canvas.create_rectangle(65, 25, 260, 348, tags="door1", fill="#683835")
self.btn2 = Button(self.canvas, bg="#47201d", text="Door 2", padx=60, pady=145, state="disabled", command=lambda: self.setDoorNum(2),
fg="white")
self.btn2.place(x=335, y=35)
door2 = self.canvas.create_rectangle(320, 25, 510, 348, tags="door2", fill="#683835")
self.btn3 = Button(self.canvas, bg="#47201d", text="Door 3", padx=60, pady=145, state="disabled", command=lambda: self.setDoorNum(3),
fg="white")
self.btn3.place(x=575, y=35)
door3 = self.canvas.create_rectangle(565, 25, 750, 348, tags="door3", fill="#683835")
self.btns.append(self.btn1)
self.btns.append(self.btn2)
self.btns.append(self.btn3)
self.window.mainloop() # sets window's event loop
# function to open help menu
def help(self):
tkinter.messagebox.showinfo("Game Instruction", "The Monty Hall Problem\n"
"You are presented with 3 doors.\nAt first you need to choose "
"one.\nAfter you've chosen a door the host will show you a "
"different door where there's a goat.\nAt that point you need "
"to choose whether you want to keep your choice, or change it.")
# function to open about menu
def about(self):
tkinter.messagebox.showinfo("About Monty Hall", "This game was made by Ohad")
# function to exit game
def exit(self):
exit = tkinter.messagebox.askyesno("Exit", "Are you sure you've had enough?")
if exit:
self.window.quit()
# function to detect door number clicked
def setDoorNum(self, num):
self.doorNum = num
# self.setDoorColor("purple", num)
self.msgCanvas.itemconfigure(self.firstDoorChoice,
text="Your first choice: Door " + str(num))
self.gameControl(self.doorNum)
# function to get door number clicked
def getDoorNum(self):
return self.doorNum
# setting door colors
def setDoorColor(self, color, doornum):
if doornum == 1:
self.btn1["bg"] = color
elif doornum == 2:
self.btn2["bg"] = color
elif doornum == 3:
self.btn3["bg"] = color
'''def getDoorColor(self):
return self.doorColor'''
def getNewOption(self, newDoorNum):
self.msgCanvas.itemconfigure(self.secondDoorChoice,
text="Your second choice: Door " + str(newDoorNum))
if self.selectedDoor == "goat":
if self.doorNum == newDoorNum:
self.maintainedDoorLoss += 1
self.msgCanvas.itemconfigure(self.instructionMsg2,
text="Sorry you lost!")
else:
self.changedDoorWins += 1
self.msgCanvas.itemconfigure(self.instructionMsg2,
text="Great you won!")
elif self.selectedDoor == "car":
if self.doorNum == newDoorNum:
self.maintainedDoorWins += 1
self.msgCanvas.itemconfigure(self.instructionMsg2,
text="Great you won!")
else:
self.changedDoorLoss += 1
self.msgCanvas.itemconfigure(self.instructionMsg2,
text="Sorry you lost!")
self.msgCanvas.itemconfigure(self.instructionMsg1, text="")
self.btn1["state"] = "disabled"
self.btn2["state"] = "disabled"
self.btn3["state"] = "disabled"
self.startGameBtn["text"] = "Restart Game"
i = 0 # keep track of the doors
for gift in self.gifts:
if gift == "car":
self.btns[i]["bg"] = "#2fa376"
else:
self.btns[i]["bg"] = "white"
self.btns[i]["text"] = " " + gift.upper()
i += 1
# function to start game
def startGame(self):
os.system('cls')
print("Scoreboard:\n")
print("Door maintained:")
print("Won: ", self.maintainedDoorWins)
print("Lost: ", self.maintainedDoorLoss, "\n")
print("Door switched:")
print("Won: ", self.changedDoorWins)
print("Lost: ", self.changedDoorLoss)
# shuffling gifts
random.shuffle(self.gifts)
self.msgCanvas.itemconfigure(self.instructionMsg1,
text="Choose a door")
self.msgCanvas.itemconfigure(self.instructionMsg2,
text="")
self.msgCanvas.itemconfigure(self.firstDoorChoice,
text="")
self.msgCanvas.itemconfigure(self.secondDoorChoice,
text="")
self.btn1["state"] = "normal"
self.btn1["bg"] = "#242582"
self.btn1["text"] = "Door 1"
self.btn1["command"] = lambda: self.setDoorNum(1)
self.btn2["state"] = "normal"
self.btn2["bg"] = "#242582"
self.btn2["text"] = "Door 2"
self.btn2["command"] = lambda: self.setDoorNum(2)
self.btn3["state"] = "normal"
self.btn3["bg"] = "#242582"
self.btn3["text"] = "Door 3"
self.btn3["command"] = lambda: self.setDoorNum(3)
self.startGameBtn["text"] = "Restart Game"
def gameControl(self, doorNum):
# copying list into giftCopy for later computations
giftsCopy = [x for x in self.gifts]
'''# getting door number selected
doorNum = self.getDoorNum()'''
# checking for first door/gift selected
# if 0 < doorNum < 4: # making sure that door number is from 1-3
doorIndex = self.doorNum - 1 # calculating index of door/gift from door number chosen
self.selectedDoor = self.gifts[doorIndex] # content of selected door
if self.selectedDoor == "goat": # if door selected contains goat
giftsCopy[doorIndex] = "air" # replacing selected gift with air in the copied list
moderatorDoor = giftsCopy.index("goat") # moderator chooses door with other goat
self.moderatorsChoice = moderatorDoor + 1
# setting instruction text
self.msgCanvas.itemconfigure(self.instructionMsg1, text="Moderator opens door " + str(self.moderatorsChoice))
# disable button
if self.moderatorsChoice == 1:
self.btn1["state"] = "disabled"
self.setDoorColor("white", 1)
elif self.moderatorsChoice == 2:
self.btn2["state"] = "disabled"
self.setDoorColor("white", 2)
elif self.moderatorsChoice == 3:
self.btn3["state"] = "disabled"
self.setDoorColor("white", 3)
elif self.selectedDoor == "car": # if door selected contains car
giftsCopy[doorIndex] = "air" # replacing selected gift with air in the copied list
if random.randint(1, 3) == 1: # randomly choosing the first or second occurrence of goat for moderator
# when randint == 1 getting first occurrence of goat
moderatorDoor = giftsCopy.index("goat")
else: # getting last occurrence of goat
moderatorDoor = len(giftsCopy) - 1 - giftsCopy[::-1].index("goat")
self.moderatorsChoice = moderatorDoor + 1
# setting instruction text
self.msgCanvas.itemconfigure(self.instructionMsg1, text="Moderator opens door " + str(self.moderatorsChoice))
# disable button
if self.moderatorsChoice == 1:
self.btn1["state"] = "disabled"
self.btn1["text"] = "GOAT"
self.setDoorColor("white", 1)
elif self.moderatorsChoice == 2:
self.btn2["state"] = "disabled"
self.btn2["text"] = "GOAT"
self.setDoorColor("white", 2)
elif self.moderatorsChoice == 3:
self.btn3["state"] = "disabled"
self.btn3["text"] = "GOAT"
self.setDoorColor("white", 3)
self.msgCanvas.itemconfigure(self.instructionMsg2, text="Click on the same door to maintain your choice or on "
"the other door to switch")
self.btn1["command"] = lambda: self.getNewOption(1)
self.btn2["command"] = lambda: self.getNewOption(2)
self.btn3["command"] = lambda: self.getNewOption(3)
MontyHallGame() |
c9f9e2e450b4c2dc2cb75087bdea0387a6bac490 | Yasin-Shah/Python-Beginners-Technocolabs | /Dictionary ,list and Set/set2.py | 270 | 3.53125 | 4 | # Methods in Set
s={23,45,"Shagun",56.78,None,"False"}
print(s)
s.add(67) # add new item
s.add(True) # add new item
s.add('A') # add new item
s.add(45) # add new item
print(s)
#s.clear()
#print(s)
s.remove(45)
print(s)
print(s.pop())
print(s)
s1=s.copy()
print(s1)
|
8b4a536198de58953905dbb1aed138dd57ad654b | nakim97/Merge-Insert-Sort | /insertTime.py | 2,164 | 4.25 | 4 | import random
import time
def insert_sort(array_list):
""" this function will sort a given vector/array of integers in ascending order"""
# the second value from the array is pulled, values larger than value pulled is slided over, value pulled fills spot
for index in range(1, len(array_list)):
val = array_list[index]
j = index - 1
# iterate through the array until all values are sorted in correct position
while j >= 0 and array_list[j] > val:
array_list[j + 1] = array_list[j]
j -= 1
array_list[j + 1] = val
# Record running times for n = 5000, 10000, 15000, 20,000, 25,000, 30,000, 35,000
# Random integer values from -10,000 to 10,000
n= 5000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 5,000 Time: ', end-start)
n= 10000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 10,000 Time: ', end-start)
n= 15000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 15,000 Time: ', end-start)
n= 20000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 20,000 Time: ', end-start)
n= 25000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 25,000 Time: ', end-start)
n= 30000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 30,000 Time: ', end-start)
n= 35000
array = []
start = time.time()
for i in range(n):
array.append(random.randint(-10000,10000))
insert_sort(array)
end = time.time()
print('Array size n = 35,000 Time: ', end-start)
|
fc6e3308def01ed020cdf69663f5c09ed8f425a4 | Anaststam/Algorithms-and-Data-Structures | /reversed_integer.py | 1,381 | 3.59375 | 4 | """
# Created by anastasia on 1/8/20
"""
#exception handling
#logging
class Solution:
def reverse(self, x: int) -> int:
if x >= 0:
print('User provided positive number')
string_num = str(x)
reversed_string= []
index = len(string_num) - 1
index2 = len(string_num) - 1
while index >= 0:
reversed_string.insert(index2-index, string_num[index])
index = index-1
res = int("".join(reversed_string))
if res >= (-2**31) and res <= (2**31 -1 ):
return (res)
else:
print('Overflow')
return(0)
else:
print('User provided negative number')
string_num = str(x)
reversed_string = []
index = len(string_num) - 1
index2 = len(string_num) - 1
while index > 0:
reversed_string.insert(index2 - index, string_num[index])
index = index - 1
reversed_string.insert(0, "-")
res = int("".join(reversed_string))
if res >= (-2**31) and res <= (2**31 -1 ):
return (res)
else:
print('Overflow')
return (0)
solution = Solution()
reversed_integer = solution.reverse(x = 0)
print(reversed_integer) |
0f6c37eca47c3dce7edcf9ec42efd0e5b07aab45 | Jordan-Renaud/py4e-exercises | /ex_11/Ex_11 Regular Expressions.py | 2,031 | 4.125 | 4 | def set_file_handler(default_file_string):
file_name = None
while file_name == None:
file_name = input("Enter file: ")
try:
if len(file_name) < 1:
file_name = default_file_string
file_handler = open(file_name)
except:
print("Invalid file name, please try again")
file_name = None
return file_handler
"""
Exercise 1: Write a simple program to simulate the operation of the grep
command on Unix. Ask the user to enter a regular expression and count the
number of lines that matched the regular expression:
$ python grep.py
Enter a regular expression: ^Author
mbox.txt had 1798 lines that matched ^Author
$ python grep.py
Enter a regular expression: ^X-
mbox.txt had 14368 lines that matched ^X-
$ python grep.py
Enter a regular expression: java$
mbox.txt had 4175 lines that matched java$
"""
print("\n-Exercise 1-\n")
import re
file_handler = set_file_handler("mbox.txt")
string_var = input("Enter a regular expression: ")
count = 0
while len(string_var) < 2 or string_var[0] != "^":
print("Invalid Response, please try again")
string_var = input("Enter a regular expression: ")
for line in file_handler:
line = line.rstrip()
count += len(re.findall(string_var, line))
print("mbox.txt had", count, "lines that matched", string_var)
"""
Exercise 2: Write a program to look for lines of the form:
New Revision: 39772
Extract the number from each of the lines using a regular expression and the
findall() method. Compute the average of the numbers and print out the average
as an integer.
Enter file:mbox.txt
38549
Enter file:mbox-short.txt
39756
"""
print("\n-Exercise 2-\n")
file_handler = set_file_handler("mbox.txt")
num_list = []
total = 0
count = 0
for line in file_handler:
num_list.append(re.findall("^New Revision: ([0-9]+)", line))
for section in num_list:
for item in section:
if len(item) > 1:
total += int(item)
count += 1
print(int(total/count))
|
251de6cc3f843b95dda564bd693dec182ebbfa53 | anandawira/HackerrankProjects | /Euler/Project Euler #30: Digit Nth powers.py | 185 | 3.578125 | 4 | #!/bin/python3
import sys
def Solve(n):
return sum([i for i in range(10**2, 10**6) if i == sum(int(a)**n for a in str(i))])
n = int(input().strip())
print(Solve(n)) |
37e88b788c6f30cbe6dedfde28893a2b4997b16e | munotsaurabh/LearnPython | /UserInput/UserInput.py | 438 | 4.15625 | 4 | name = "Sam"
user_input = input("Enter your name: ") # input fn returns a string
print(f"Hello {name}. My name is {user_input}.")
####################
age = input("Enter your age: ")
print(f"You have lived for {age * 12} months.") #This will print the entered age 12 times repetitively because `age` variable holds string value
####################
age = input("Enter your age: ")
print(f"You have lived for {int(age) * 12} months.") |
8e406f37efe82753378036a5680fc3888025dd24 | googleliyang/gitbook_cz_python | /python_code/chuanzhi/python_advance/18/web服务器-07-08版本/08-发布游戏/08-发布游戏.py | 3,383 | 3.515625 | 4 | import sys
import socket
import Appliction
"""
Web服务器= TCP服务器 + HTTP协议格式
01- 在用户请求网页的时候 总是返回一个固定的页面
02- 返回用户指定页面
03- 改进: 如果文件不存在 返回404错误
面向过程 一个函数-功能
面向对象 一个类 -角色 带功能 把属性和操作属性的方法封装在一个类中
"""
class HTTPServer(object):
"""为用户提供web服务"""
def __init__(self, port):
"""初始化对象的属性"""
# 1 创建TCP 绑定 监听
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 地址重用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', port))
server_socket.listen(128)
# 保存一个套接字对象的引用
self.server_socket = server_socket
# 用一个字典保存游戏相关的键值对
self.projects_dict = dict()
self.cur_game = ""
self.init_game()
def start(self):
"""启动web服务"""
# 2 接受来自 客户端/浏览器 连接
while True:
client_socket, client_addr = self.server_socket.accept()
print("接受到来自%s的连接请求了" % str(client_addr))
# 调用专门用来处理客户端请求的方法
self.client_request_handler(client_socket)
def client_request_handler(self,client_socket):
"""专门用来处理每个客户端的HTTP请求"""
# 3 接收HTTP请求报文 解析数据获取用户的需求
# 3.1 接收请求报文
http_request_data = client_socket.recv(4096).decode()
# 如果客户端已经断开连接了 收数据是b'' 就没有必要继续往下执行了
if not http_request_data:
print("用户请求错误")
return
# 调用模块的方法 处理HTTP请求报文 返回值就是响应报文
http_response_data = Appliction.app(http_request_data, self.cur_game)
# 不管有没有异常都会执行这里的代码
# 4.3 发送
client_socket.send(http_response_data)
# 5 合适时间关闭连接 短连接实现
client_socket.close()
def init_game(self):
"""选择需要发布的游戏"""
self.projects_dict['植物大战僵尸-普通版'] = "zwdzjs-v1"
self.projects_dict['植物大战僵尸-外挂版'] = "zwdzjs-v2"
self.projects_dict['保卫萝卜'] = "tafang"
self.projects_dict['2048'] = "2048"
self.projects_dict['读心术'] = "dxs"
# 获取需要发布的游戏的名称
print(list(self.projects_dict.keys()) )
key = input("请输入需要发布的游戏:")
self.cur_game = self.projects_dict[key]
if __name__ == '__main__':
# print(sys.argv)
# 判断参数个数必须要大于等于2个 并且 全是由数字构成的
if len(sys.argv) >= 2 and sys.argv[1].isdigit():
# 列表中每个元素都是字符串类型
port = int(sys.argv[1])
# 创建一个web服务
http_server = HTTPServer(port)
# 启动服务
http_server.start()
else:
print("参数用法错误 python3 web.py 8080")
# 降低了 参数和 代码的耦合度;以后修改参数就不用对代码做任何的修改了 |
5761725a7db6522f7e87aa45bc56a6c95b7b93b2 | abychutkin/Python | /my_range.py | 349 | 3.71875 | 4 | def my_range(*args):
if len(args) < 1 or len(args) > 3:
raise TypeError
first = 0
step = 1
if len(args) == 1:
last = args[0]
elif len(args) >= 2:
first = args[0]
last = args[1]
if len(args) == 3:
step = args[2]
while first < last:
yield first
first += step
|
60acad2b9a0b228bebf8bff277cadc004d54bc30 | nicolexlc/RaspberryPi-prac | /relayprueba.py | 958 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
pinList = [2, 3, 4, 17, 27, 22, 10, 9]
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
SleepTimeL = 2
try:
GPIO.output(2, GPIO.LOW)
print("UNO")
time.sleep(SleepTimeL);
GPIO.output(3, GPIO.LOW)
print("DOS")
time.sleep(SleepTimeL);
GPIO.output(4, GPIO.LOW)
print("TRES")
time.sleep(SleepTimeL);
GPIO.output(17, GPIO.LOW)
print("CUATRO")
time.sleep(SleepTimeL);
GPIO.output(27, GPIO.LOW)
print("CINCO")
time.sleep(SleepTimeL);
GPIO.output(22, GPIO.LOW)
print("SEIS")
time.sleep(SleepTimeL);
GPIO.output(10, GPIO.LOW)
print("SIETE")
time.sleep(SleepTimeL);
GPIO.output(9, GPIO.LOW)
print("OCHO")
time.sleep(SleepTimeL);
GPIO.cleanup()
print("Adiós!")
except KeyboardInterrupt:
print("Salir")
GPIO.cleanup() |
5c50de4f63a494f44888fa1a93e72471d20886fa | tareklel/seven-days-concurrency | /day5/philosophers.py | 974 | 3.53125 | 4 | '''
DAY 5 OF CONCURRENCY: DINING PHILOSOPHERS
'''
from time import sleep
import threading
from contextlib import contextmanager
@contextmanager
def acquire(*locks):
# sort locks
locks = sorted(locks, key=lambda x: id(x))
try:
for lock in locks:
lock.acquire()
yield
finally:
# release locks
for lock in locks:
lock.release()
# Thread representing a philosopher
def philosopher(left, right):
while True:
# philosopher can have two 'chopsticks' at a time
with acquire(left, right):
print(f'{threading.currentThread()} is eating')
# locks representing chopsticks
STICKSNUMBER = 5
chopsticks = [threading.Lock() for n in range(STICKSNUMBER)]
# create all pholsophers
for n in range(STICKSNUMBER):
t = threading.Thread(target=philosopher,
args=(chopsticks[n], chopsticks[(n+1)%STICKSNUMBER])
)
t.start()
|
852978d4b4906a30d6d368b032a4151e28a8e75c | smartbadger/Python-Projects | /linked_lists/BailesLab3.py | 1,411 | 4.03125 | 4 | class ListItem(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.current = None
self.front = None
def addToFront(self, item):
link = ListItem(item)
if self.front == None:
self.front = link
else:
link.next = self.front
self.front = link
def addToBack(self, item):
self.current = self.front
while True:
if self.current.next == None:
self.current.next = ListItem(item)
break
else:
self.current = self.current.next
def removeFromFront(self):
print self.front.data
self.front = self.front.next
def addToPosition(self, position, item):
self.current = self.front
for i in range(position-1):
self.current = self.current.next
temp = self.current.next
self.current.next = ListItem(item)
self.current = self.current.next
self.current.next = temp
def printTheList(self):
self.current = self.front
while True:
print self.current.data
if self.current.next == None:
break
else:
self.current = self.current.next
|
8277eb59d24755ffbe91d10bbdad56bb0ca9d244 | SidneyXu/learn-to-program | /coffeetime-parent/Python3Gun/src/16_function.py | 983 | 3.65625 | 4 | # Define
def hello():
return 'hello'
# Function Document
def add(x, y):
"""add two numbers"""
return x + y
# Varargs
def sum(*n):
result = 0
for i in n:
result += i
return result
# Default Values
def say(name, word='hello'):
print(name, ', ', word)
# Return Values
def triple(x, y, z):
return x * 3, y * 3, z * 3
print(hello())
print(add.__doc__)
help(add)
print('sum(1,2,3) is', sum(1, 2, 3))
x, y, z = triple(1, 2, 3)
print(x, y, z)
# Keyword Values
print(say(word='how are you', name='Peter'))
# Global Parameters
num = 100
m = 200
def declare10():
# print(num) error
num = 10
print(m)
declare10()
print(num) # 100
def declare5():
global num
num = 5
declare5()
print(num) # 5
# Static Method / Class Method
class StrUtils:
@staticmethod
def sort_words(words):
return sorted(words)
@classmethod
def cout(cls):
print(cls)
print(StrUtils.sort_words([3, 2, 1]))
|
fd6ba6d2652436f343f40760c6ed1685e8b68920 | pedropenna1/Exercicios-Python | /exercicio 44.py | 828 | 3.796875 | 4 | print('{:=^40}'.format(' Lojas Penna '))
pagamento = float(input('Qual valor das compras? R$: '))
print('''Seu pagamento será em:
[1] : à vista, dinheiro ou cheque.
[2] : à vista no cartão.
[3] : 2x no cartão.
[4] 3x ou mais no cartão.''')
opcao = int(input('Digite a sua opção de pagamento: '))
if opcao == 1:
print('Seu pagamento de R${} recebeu uma redução de 10% e você pagará R${}'.format(pagamento, pagamento-(pagamento*0.1)))
elif opcao == 2:
print('Seu pagamento de R${} recebeu uma redução de 5% e você pagará R${}'.format(pagamento, pagamento-(pagamento*0.05)))
elif opcao == 3:
print('Seu pagamento será normal no valor de R$ {}'.format(pagamento))
elif opcao == 4:
print('Seu pagamento de R${} recebeu um juros de 20% e você pagará R${}'.format(pagamento,(pagamento+(pagamento*0.20))))
|
4a2ef7860361319e7697bb9b68805e84f9ea3c68 | shumcheyy/aniget | /aniget.py | 2,530 | 3.796875 | 4 | from bs4 import BeautifulSoup
import notify2
import requests
import argparse
import sys
# The website from where we fetch/scrape the name of anime
def main():
url = "https://www.gogoanime.io"
response = requests.get(url)
# using bs we are kinda pretty printing the fetched page
soup = BeautifulSoup(response.text, "html.parser")
# we define an array that stores names of anime that have recently came and another array to store episode number
epnamearray = []
epnoarray = []
# we begin a loop which helps in finding all the names of anime that came recently using CSS selectors
# all websites have different way of using CSS selectors , gogoanime uses the <p> tag with name attribute
for epnames in soup.findAll('p', {"class": 'name'}):
# we convert epnames to a string since it is a bs4 element tag
epname = str(epnames.text)
# appending the string of anime names into the array
epnamearray.append(epname)
# same as above properties are applied for the episode number too
for epnos in soup.findAll('p', {"class": 'episode'}):
epno = str(epnos.text)
epnoarray.append(epno)
# we map the anime name and episode number together
# using the strip method because epnamearray is a list and the values in it are string
# so that we can use them as proper text we use strip method
def display_term():
for i in range(len(epnoarray)):
print(epnamearray[i].strip() + "----->" + epnoarray[i])
# we make a list that contains the shows that we watch
watch_list = ["Kami no Tou", "Fruits Basket 2nd Season", "Gleipnir",
"Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen 2",
"Kingdom 3rd Season", "Yesterday wo Utatte", "Toaru Kagaku no Railgun T", "Kakushigoto (TV)",
"Black Clover", "Great Pretender"]
# we compare the lists and find out what favorite anime has a new episode
def display_noti():
notify2.init("New Anime Episode")
for i in range(len(epnoarray)):
if epnamearray[i] in watch_list:
n = notify2.Notification(str(epnamearray[i]) + " " + str(epnoarray[i]))
n.show()
def paarser():
parser = argparse.ArgumentParser()
parser.add_argument("--show", "-s", action="store_true", help="show the current watch list")
args = parser.parse_args()
if args.show:
print(watch_list)
if len(sys.argv) == 2:
paarser()
display_term()
display_noti()
main()
|
e0e38ff5f59e637b12235ee1151dedef63283a0c | Karolina-Wardyla/Practice-Python | /list_ends/list_ends.py | 313 | 4.25 | 4 | # Write a program that takes a list of numbers and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.
def list_ends(elements):
return [elements[0], elements[-1]]
result = list_ends([19, 11, 2, 3, 5, 10, 20, 33, 28, 44])
print(result) |
e0570739102e2e3f1b9c98feef044c4579ac3c10 | pleielp/apss-py | /Ch04/4.01/jiho.py | 409 | 3.921875 | 4 | def majority1(array):
majority_count = 0
majority = -1
for value in array:
count = 0
for target in array:
if target == value:
count += 1
if majority_count < count:
majority_count = count
majority = value
return majority
if __name__ == "__main__":
print(majority1([1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 4, 4, 5, 5]))
|
d297605b8b1c494d280103900c2dcb7ad66cbb4e | Elvendir/osu-mania-SDR-calc | /calc_kps.py | 7,508 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
'''
The aim is to give each note an individual kps.
First, kps is calculate for each hand independently .
(because for a player kps is linked to the frequency of the hand not to the fingers's one).
For a jack it's simple : kps = 1/time_btw_the_2_notes
However, when there is a trill or two notes at the same time it gets more complicated.
First, two notes at the same time can be seen as the limit of an half trill (two notes not on the same column)
when the two notes are infinitely near of each other.
By using this principle, kps of a note at the end of the half trill is calculate by :
kps = F(kps_previous_note, delta_t_previous_note|note, delta_t_note|next_note)
And the limit implies : F(kps,0,t)= kps * c_1 and F(kps,t,0) = c_2 / delta_t_note|next_note
with c_1 and c_2 constant <= 1 that decrease the reward for two note pressed at the same time.
The other interesting value is : F(kps,t,t) = c_3 / (2*t) when there is a perfect trill
(the note is exactly in the middle of the two others)
with c_3 a constant >= 1 that rewards the trill.
In the calculation :
c_1 = 1 (because at least one of a double need to have a full_weight)
c_2 = mash_coef(kps_previous)
c_3 = trill_coef
F = trill_kps_calc is two half linear function with the the previous conditions.
(To see a visualisation of F uncomment in main.py the graph section or try https://www.desmos.com/calculator/8pdbpj1u59)
'''
LN_release_kps_correction = 70 # kps correction for LN release
LN_note_after_release_correction = 150 # kps correction for note after LN release
t_mash_min = 0.1 # size in seconds of the mash zone
trill_coef = 0.7 # factor of reduction of the trill kps
tau_kps_trill = 2 # typical kps at which the kps of the previous is taken into account
tau_jack = 10 # time between two note when you can't start to jack and the next
tau_kps_jack = 10 # typical kps at which it stats to take into account the previous one
# useful functions to calculated trill_kps
def something(x):
return (np.cos(x * np.pi / 2)) ** 2
def hyperbole(x, hyperbole_slope, y):
return x / 2 / hyperbole_slope - np.sqrt((x / 2 / hyperbole_slope) ** 2 + y)
def calc_hyperbole_slope(t_mash, kps_previous, kps_trill):
m = kps_previous - (1 / t_mash) ** 2
T = 0.5 * ((trill_coef / t_mash - kps_trill) / (1 / t_mash - kps_trill) + 1)
ln_thing = (trill_coef - T) / (trill_coef - 1)
if ln_thing <= 0:
return 0
else:
Q = kps_previous * np.log(ln_thing)
return (1 / Q) * hyperbole(m, 1, kps_previous)
def quarter_ellipse(t, max_trill_kps, mash_kps, t_mash):
if t >= t_mash:
return max_trill_kps
elif t <= 0:
return mash_kps
else:
return (mash_kps - max_trill_kps) * np.sqrt(1 - (t / t_mash) ** 2) + max_trill_kps
# definition of the variables coefficient
def calc_mash_kps(t1t2, t2t3):
kps_previous = 1 / t2t3
if t1t2 == 0:
if kps_previous == 0:
mash_kps = 0
else:
mash_kps = kps_previous
elif kps_previous == 0:
mash_kps = 0
else:
mash_kps = kps_previous
return mash_kps
# Defines the change in trill_coef when it becomes a jack (limit t1t2 = 0)
def jack_limit_coef(t0t2, t1t2, t2t3, t_mash):
kps_previous = 1 / t2t3
hyperbole_slope = calc_hyperbole_slope(t_mash, kps_previous, 1 / t0t2)
if hyperbole_slope == 0:
return 0
q = hyperbole(kps_previous - (1 / t1t2) ** 2, hyperbole_slope, kps_previous)
return np.exp(q / kps_previous)
# Defines a variable trill_coef to take into account the fact that it can become a jack
# at the limit t2t3 = 0
def variable_trill_coef(t0t2, t1t2, t2t3, jack_limit, t_mash):
kps_previous = 1 / t2t3
if kps_previous == 0:
return trill_coef
elif t1t2 == 0:
return 1
elif not jack_limit:
return trill_coef
else:
return trill_coef - jack_limit_coef(t0t2, t1t2, t2t3, t_mash) * (trill_coef - 1)
# Calculates the note's kps has a trill
def calc_trill_kps_has_trill(t1t2, t0t2, m_trill_coef):
return (2 * m_trill_coef - 1) * (1 / t1t2 - 1 / t0t2) + 1 / t0t2
# Calculates the note's kps when it can be smashed
def calc_trill_kps_has_mash(t1t2, max_trill_kps, mash_kps, t_mash):
return quarter_ellipse(t1t2, max_trill_kps, mash_kps, t_mash)
# Calculates the kps of the last note of an half trill (it's F)
# It's two half function : one for the trill part the other for the mashing (when near the previous note)
def trill_kps_calc(t0t2, t1t2, t2t3, jack_limit):
if jack_limit:
t_mash = min([t_mash_min, t0t2 / 2, t2t3])
else:
t_mash = t_mash_min
m_trill_coef = variable_trill_coef(t0t2, t1t2, t2t3, jack_limit, t_mash)
trill_kps_has_trill = calc_trill_kps_has_trill(t1t2, t0t2, m_trill_coef)
# Distinguish between mash and trill zone
if t1t2 < t_mash:
trill_kps_has_mash = calc_trill_kps_has_mash(t1t2, calc_trill_kps_has_trill(t_mash, t0t2, m_trill_coef),
calc_mash_kps(t1t2, t2t3), t_mash)
return min(trill_kps_has_mash, trill_kps_has_trill)
else:
return trill_kps_has_trill
# Does the kps calculation for a note depending on jack or half trill
def next_kps(i, count, map, last_LN_start, last):
column = map[:, 0]
type = map[:, 0]
t = map[:, 2] / 1000
t1t2 = t[i[count - 2]] - t[i[count - 3]]
# special case : first calculate note
# jack limit is a bool saying if when t2t3 = 0 the note is a jack
if count == 3:
t2t3 = float("inf")
jack_limit = False
else:
t2t3 = t[i[count - 3]] - t[i[count - 4]]
jack_limit = (column[i[count - 2]] == column[i[count - 4]])
# special case : last calculate note
if last:
t0t2 = float("inf")
else:
t0t2 = t[i[count - 1]] - t[i[count - 3]]
# if jack
if column[i[count - 2]] == column[i[count - 3]]:
return 1 / t1t2
if t2t3 == 0:
return 1 / t1t2
if t0t2 - t1t2 == 0:
return 1 / t1t2
if t1t2 == 0:
return 1 / t2t3
# if jack but the other way around
else:
kps = trill_kps_calc(t0t2, t1t2, t2t3, jack_limit)
return kps
# Does the kps calculation for both hand independently
def calc_kps(map, nb_columns):
columns = map[:, 0]
type = map[:, 1]
kps = [0 for i in range(len(map))]
last_LN_start = [-1 for i in range(nb_columns)]
left_i = []
count_l = 0
right_i = []
count_r = 0
last = False
for i in range(0, len(map)):
column = columns[i]
if type[i] == 1:
last_LN_start[column] = i
# left hand calculation
if column < nb_columns / 2:
left_i.append(i)
count_l += 1
if count_l >= 3:
kps[left_i[count_l - 2]] = next_kps(left_i, count_l, map, last_LN_start, last)
# right hand calculation
else:
right_i.append(i)
count_r += 1
if count_r >= 3:
kps[right_i[count_r - 2]] = next_kps(right_i, count_r, map, last_LN_start, last)
# last note calculation
count_l += 1
count_r += 1
last = True
if count_l > 3:
kps[left_i[count_l - 2]] = next_kps(left_i, count_l, map, last_LN_start, last)
if count_r > 3:
kps[right_i[count_r - 2]] = next_kps(right_i, count_r, map, last_LN_start, last)
return kps, left_i, right_i
|
8b68a0216b811016c2cb6180e2d14e67196ab624 | luyasi/python_study | /python-14-20180921/test1.py | 2,070 | 3.578125 | 4 | # L = ["2","4","6","7"]
#
# var = list(map(int,L))
# print(var)
#
# def red(n,m):
# val = n*10 + m
# return val
#
from functools import reduce
# value = reduce(red,var)
# print(value)
# L =["JaCk","LoseR","jEEry","pYthOn"]
#
#
# def str1(i):
# i = i.lower()
# i = i.capitalize()
# return i
#
#
# var = list(map(str1, L))
# print(var)
# var = "1ab2cde456f8"
#
# val = [n for n in var if n.isdigit() ]
# def add(x,y):
# return x + y
# valu = int(reduce(add,val))
# print(valu,type(valu))
# print(val)
# def digtr(var):
# list1 = []
# for i in var:
# if i.isdigit():
# # return i
# list1.append(i)
# print(list1)
# def red(n,m):
# val = n*10 + m
# return val
# valu = list(map(digtr,var))
# valw = reduce(red,valu)
# print(valw)
# L = [4,2,5,3,6,1]
# # L.sort()
# # print(L)
# #
# # K = sorted(L)
# # print(K)
# k = "lyshelLo"
# print(k.title())
#
# L= ["1","ad3","c2","h2o",["co2","k2mno4",1,"na2"],34]
# # 13222242
# list1 = []
# L = ["1","2","5","3","4","7","9","8"]
# L1 = list(map(int,L))
#
# def func(boo):
# if boo % 2 == 0:
# return True
# else:
# return False
#
# res =filter(func,L1)
# res1 = sorted(res,reverse=True)
# func2 = lambda x,y:x*10+y
# res3 = reduce(func2,res1)
# print(res3)
#
# def func(boo):
# if boo % 2 == 1:
# return True
# else:
# return False
#
# res4 =filter(func,L1)
# res5 = sorted(res4,reverse=False)
# res6 = reduce(func2,res5)
# print(res6)
# 43211234
# def func(n):
# if n == 1:
# return 4
# else:
# return abs(func(n-1)-1)
# val = func(6)
# print(val)
# li = [1,2,3,4,5,6,7,8,8]
# li2 = []
# li3 = []
# for x in li:
# for y in li:
# if x != y:
# A = "%s%s"%(x,y)
# li2.append(A)
# # print(li2.count())
# print(len(set(li2)))
# li2 = []
# li3 = []
# for i in li:
# for x in li:
# if i != x:
# a = "%d%d" % (i,x)
# li2.append(a)
# for y in li2:
# if y not in li3:
# li3.append(y)
# print(li3)
# print(len(li3))
|
7b42fe519f3c39e0981542ffe5157e553b12969f | jhyde52/blue | /udacity/python1/builtin.py | 304 | 3.515625 | 4 |
###this tells me how many words are in my file
#def magic():
# youtube = open("/Users/jessicahyde/Documents/Python/youtube.txt")
# contents_of_file = youtube.read()
# print len(contents_of_file)
# youtube.close()
#magic()
###converts a number to binary
#def magic():
# print bin(34345)
#magic()
# |
88e39c13b273192ef6f39e45597e74213126119c | DilipBDabahde/PythonExample | /MYSQL/order_by_desc_16.py | 554 | 3.875 | 4 | '''
order by field_name DESC
this above statment show records in desceing order
for this program we use "select * from tablename order by table_field DESC"
'''
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", db="TESTDB", password="Current-Root-Password");
if mydb:
print("Connected successfully");
else:
print("not connected to dbms");
mycursor = mydb.cursor();
sql_query = "SELECT * FROM STUDENT order by std_address DESC";
mycursor.execute(sql_query);
myresult = mycursor.fetchall();
for x in myresult:
print(x);
|
78ab94663bf387fbf21ba0e35f0c9edd5d3d7ab7 | shubham19995/content | /course_2/calc.py | 167 | 3.671875 | 4 | def add(x,y):
return x+y
def sub(x,y):
return x-y
def mul(x,y):
return x*y
def div(x,y):
if y == 0:
return None
else:
return x/y |
8381e2996df6b09ced4b3ae84b0e78c4407d209f | dagwieers/requests-credssp | /tests/utils.py | 404 | 4.03125 | 4 | import binascii
def byte_to_hex(byte_string):
# Converts a byte string to a hex string for easy input and output of test data.
return ' '.join([binascii.hexlify(x) for x in byte_string])
def hex_to_byte(hex_string):
# Converts a hex string to byte string for comparison with expected byte string data
hex_string = ''.join(hex_string.split(' '))
return binascii.unhexlify(hex_string) |
e82409812193059e3508028f79d75c83c37a5c43 | chefirchy/Python | /l7/12.py | 739 | 3.625 | 4 | #Опять файл кину в папку(Такая же проблема)
import re
def get_file_content():
f = open('C:/Users/chefi/Documents/tfile.txt', 'r')
file_content = f.read()
f.close()
words_arr = []
for word in re.split(r'\s+', file_content):
words_arr.append(word.lower())
return words_arr
def count_unique_words():
words_arr = get_file_content()
count = 0
considered = {}
for word in words_arr:
if(word not in considered):
considered[word] = True
count += 1
return int(count)
print('Количество слов в строке ', len(get_file_content()))
print('Количество уникальных слов в строке ', count_unique_words()) |
63b68e7a8f92d09762e0ff64554b127f83f39045 | mossbanay/Codeeval-solutions | /string-searching.py | 574 | 3.84375 | 4 | import sys
import re
def substring_to_regex(substring):
return re.sub(r'[^\\]\*', '.', substring)
def main():
with open(sys.argv[1]) as input_file:
for line in input_file:
test_string, substring = line.strip().split(',')
regex = substring_to_regex(substring)
try:
if re.findall(regex, re.escape(test_string)):
print('true')
else:
print('false')
except:
print('false')
if __name__ == '__main__':
main()
|
fb1e6724dd845826b440672b6c082e2c3c79cac8 | WangYuanting/leetcode_problem | /outofdate/13Roman_to_Integer/test20180113.py | 947 | 3.703125 | 4 | '''
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
'''
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i + 1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
nmap = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
def romanToInt( s):
"""
:type s: str
:rtype: int
"""
res = last_n = 0
for char in s:
val = nmap[char]
if last_n:
if val > last_n:
res -= 2 * last_n
res += val
last_n = val
return res
s='XIIV'
print romanToInt(s)
|
00f3911a965c8861e013ac41ec7ab0dbd1e38325 | afalbrecht/robots | /main.py | 100 | 3.609375 | 4 | def makelist():
return ['a','b','c','d','e']
res = [x for x in range(8)]
del res[4:]
print(res) |
0b37987e52d1cf5a271398e496ea5834edc855cd | rurrui/testgit | /regular/email.py | 316 | 3.890625 | 4 | import re
# 设计一个可以匹配类似rurui@live.com的正则表达式
regular_email = r'^([0-9a-zA-Z\.]*)\@([0-9a-zA-Z]*)\.com'
print('input a email:')
test_email = input()
if re.match(regular_email, test_email):
m = re.match(regular_email, test_email)
print(m.groups())
print('ok')
else:
print('no')
|
ee5c25f62cf83a8f089783425d2b1545f30a9e87 | vandanmshah/victor_borge | /victor_borge.py | 1,888 | 3.59375 | 4 | import ast, re
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
def load_inflate():
values = {}
values['zero'] = values['none'] = values['nil'] = values['null'] = "one"
values['one'] = values['won'] = values['Juan'] = 'two'
values['two'] = values['to'] = values['too'] = values['tu'] = 'three'
values['three'] = 'four'
values['four'] = values['for'] = values['fore'] = 'five'
values['five'] = 'six'
values['six'] = 'seven'
values['seven'] = 'eight'
values['eight'] = values['ate'] = 'nine'
values['nine'] = 'ten'
values['ten'] = 'eleven'
values['eleven'] = 'twelve'
values['twelve'] = values['dozen'] = 'thirteen'
values['never'] = 'once'
values['half'] = 'one and a half'
values['once'] = 'twice'
values['twice'] = 'thrice'
values['single'] = 'double'
values['double'] = 'triple'
values['first'] = 'second'
values['second'] = 'third'
values['third'] = 'fourth'
values['fourth'] = values['forth'] = 'fifth'
return values
flag = True
while flag:
statement = raw_input("\n(Note :- If you want to 'EXIT' simply write 'E')\nEnter your sentence to inflate: ")
stmttoprint = ""
specialchar = ""
if statement == "E" or statement == "e":
flag = False
else:
values = load_inflate()
values_to_check = []
for key, value in values.items():
values_to_check.append(key)
for stmt in statement.split(' '):
if str(re.search( r'\W', stmt)) != "None":
specialchar = stmt[len(stmt)-1]
stmt = stmt[:-1]
if hasNumbers(stmt):
stmttoprint += str(ast.literal_eval(stmt) + 1) + specialchar + " "
else:
flg = True
for chkvalue in values_to_check:
if chkvalue in (stmt.lower()):
flg = False
stmttoprint += stmt.lower().replace(chkvalue, values[chkvalue]) + specialchar + " "
break
if flg:
stmttoprint += stmt + specialchar + " "
print "Your inflated sentence is: " + stmttoprint |
ee7b328376f22e951b5851be40108b3496b89dc7 | fdfzjxxxStudent/CS001 | /CS001-lesson2/SayHi2.py | 115 | 3.609375 | 4 | #SayHi2.py
print("Enter your name:", end='')
name = input()
print("Hi ", name, ", how are you today?", sep='')
|
c316f35125a70a3185e4022f5e5852db347fb00f | Dilnaz7/part2-task15 | /task15.py | 193 | 3.78125 | 4 | year_of_age = int (input("Enter your age: "))
list = []
if year_of_age % 2 == 0:
print(range(0, year_of_age+1, 2))
if year_of_age % 2 == 1:
print(range(1, year_of_age+1, 2))
|
ab87939019b18a6b9da37ef8bf23192a0f4c63bd | shenyoujian/python-data-structure | /chapt02/ActiveCode2.py | 122 | 3.5625 | 4 | def foo(tom):
fred = 0
for bill in range(1, tom+1):
barney = bill
fred = fred + barney
return fred
print(foo(10)) |
9e40cc6ffe9d5bc73c3550a544af7bf4aa3c00c5 | adil367/Jarvis-assistant | /Jarvis/main.py | 3,139 | 3.5625 | 4 | import pyttsx3
from datetime import datetime
import speech_recognition as sr
import webbrowser
import wikipedia
import time
import os
import random
engine=pyttsx3.init('sapi5')
#selecting voice
voices=engine.getProperty("voices")
engine.setProperty("voice",voices[1].id)
def myself():
'''
it takes input from microphone as "who are you" and then Jarvis introdeuces itself.
:return:
'''
speak("I am an artificial intelligence assistant, and i love ice-cream ha ha ha.")
def take_Command():
'''
This function takes input from the microphone and returns the command by recognizing
it through speech recognizing module.
:return:
'''
r=sr.Recognizer()
with sr.Microphone() as source:
print("listening...")
# r.pause_threshold=1
audio=r.listen(source)
try:
print("Recognizing...")
query=r.recognize_google(audio,language="us-in")
print(query)
except Exception as e:
print("Couldn't recognize,speak again.")
return "none"
return query
def how_are_you():
sentences=["i am totally fine, how are you my friend","i have been a bit tensed,but it's ok.",
"What kind of question is this, i am a machine and i don't feel anything",
"i am awesome man thank you soooooo much."]
speak(random.choice(sentences))
def wishme():
'''
this function greets the user according to the current time.
'''
current_time=datetime.now().hour
if current_time>=0 and current_time<12:
speak("Good morning, I am jarvis.")
elif current_time>=12 and current_time<16:
speak("Good afternoon, I am jarvis.")
else:
speak("Good evening, I am jarvis.")
def speak(audio):
'''
This function takes input and speaks it out loud.
:param audio:
:return:
'''
engine.say(audio)
engine.runAndWait()
if __name__ == '__main__':
wishme()
while True:
time.sleep(1)
query = take_Command().lower()
if "wikipedia" in query:
print("Searching...")
query=query.replace("wikipedia","")
result=wikipedia.summary(query,sentences=1)
print(result)
speak(result)
elif "open google" in query:
webbrowser.open("google.com")
elif "open youtube" in query:
webbrowser.open("youtube.com")
elif "none" in query:
continue
elif "who are you" in query:
myself()
elif "how are you" in query:
how_are_you()
elif "open file" in query:
query=query.replace("open file ","")
find_files(query,"D:\\Adil")
elif "the time" in query:
timeNow=datetime.now().strftime("%H:%M:%S")
speak(timeNow)
elif "bye jarvis" in query:
speak("ok, bye my friend. i will meet you next time.")
exit()
else:
chrome=webbrowser.get('chrome')
chrome.open(f"google.com/?#q={query}") |
762b23b3a86e49fd6b4dbab0bb577737ddf0392d | ilkera/EPI | /Tree/PrintTreePerimeter/PrintTreePerimeter.py | 1,617 | 4.34375 | 4 | # Problem: Print tree perimeter
#Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root.
#For example, boundary traversal of the following tree is “20 8 4 10 14 25 22″
# 20
# 8 22
# 4 12 25
# 10 14
# Tree definition
class TreeNode:
def __init__(self, value, left = None, right = None):
self.value = value
self.left = left
self.right = right
def printTreeLeaves(tree):
if not tree:
return
printTreeLeaves(tree.left)
if not tree.left and not tree.right:
print("%d " %tree.value, end="")
printTreeLeaves(tree.right)
def printTreeBoundaryLeft(tree):
if not tree:
return
if tree.left:
print("%d " %tree.value, end="")
printTreeBoundaryLeft(tree.left)
elif tree.right:
print("%d " %tree.value, end="")
printTreeBoundaryLeft(tree.right)
def printTreeBoundaryRight(tree):
if not tree:
return
if tree.right:
printTreeBoundaryRight(tree.right)
print("%d " %tree.value, end="")
elif tree.left:
printTreeBoundaryRight(tree.left)
print("%d " %tree.value, end="")
def printTreeBoundary(tree):
if not tree:
return
print("%d " %tree.value, end="")
printTreeBoundaryLeft(tree.left)
printTreeLeaves(tree.left)
printTreeLeaves(tree.right)
printTreeBoundaryRight(tree.right)
# Main program
tree = TreeNode(20, TreeNode(8, TreeNode(4), TreeNode(12, TreeNode(10), TreeNode(14))), TreeNode(22, None, TreeNode(25)))
printTreeBoundary(tree) |
a430b53a2c06e006d1167a537fbaa13c03e8bdf8 | gk90731/100-questions-practice | /29.py | 123 | 3.6875 | 4 | from math import pi
def volume_calc(h,r=10):
v=((4*pi*r**3)/3)-(pi*h**2*(3*r-h)/3)
return v
print(volume_calc(2))
|
526d3b0174438ae0fa1eb75d03956799b21a0cb5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/578_lowest_common_ancestor_iii.py | 1,115 | 3.734375 | 4 | """
Notice:
node A or node B may not exist in tree.
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
c_ Solution:
___ lowestCommonAncestor3 root, a, b
"""
:type root: TreeNode
:type a: TreeNode
:type b: TreeNode
:rtype: TreeNode
"""
__ n.. root:
r..
lca, has_a, has_b divide_conquer(root, a, b)
r.. lca __ has_a a.. has_b ____ N..
___ divide_conquer node, a, b
__ n.. node:
r.. N.., F.., F..
left, a_in_left, b_in_left divide_conquer(node.left, a, b)
right, a_in_right, b_in_right divide_conquer(node.right, a, b)
has_a a_in_left o. a_in_right o. node __ a
has_b b_in_left o. b_in_right o. node __ b
__ node __ a o. node __ b:
r.. node, has_a, has_b
__ left a.. right:
r.. node, has_a, has_b
__ left:
r.. left, has_a, has_b
__ right:
r.. right, has_a, has_b
r.. N.., has_a, has_b
|
eb79fa3ec1e2af083ec1ed1bc3ca1006e17dbc78 | herrPfeffer/Planetsimulator | /Planetsimulator/PlanetManager.py | 2,372 | 3.9375 | 4 | from Planet import Planet
from Star import Star
class PlanetManager(object):
"""Creates and manages planets and their interference"""
def __init__(self, timesteps:int):
"""Basic Constructor"""
self.timesteps = timesteps
#holds all planets in a list
planetary_objects = []
def create_planet(self, description: str, x_position:float, y_position:float, x_speed:float, y_speed:float, mass: float):
"""Creates a planet and appends it to the list planetary_objects."""
if self.validate_position(x_position, y_position) == False:
raise ValueError("There is already a planet in this position!")
new_planet = Planet(description, x_position, y_position, x_speed, y_speed, mass)
self.planetary_objects.append(new_planet)
return new_planet
def create_star(self, description:str, x_position:float, y_position:float, mass:float):
"""Creates a star and appends it to the list planetary_objects."""
if self.validate_position(x_position, y_position) == False:
raise ValueError("There is already a planetary object in this position.")
new_star = Star(description, x_position, y_position, mass)
self.planetary_objects.append(new_star)
return new_star
def validate_position(self, x_position:float, y_position:float):
"""Validates if the position of the planet can be used."""
for planet in self.planetary_objects:
if ((x_position == planet.x_position) and (y_position == planet.y_position)):
return False
return True
def get_positions(self):
"""Returns a map with the x and y coordinates of all planets."""
position_map = {}
x_positions = []
y_positions = []
for planet in self.planetary_objects:
planet.move_next(self.planetary_objects, self.timesteps)
x_positions.append(planet.x_position)
y_positions.append(planet.y_position)
position_map["x_coordinate"] = x_positions
position_map["y_coordinate"] = y_positions
return position_map
def determine_max_x_position(self):
"""determines the max x-Value"""
return 2*7.377*10**12
def determine_max_y_position(self):
"""determines the max y-Value"""
return 2*7.377*10**12
|
2338973ff2d9d5375315a62da72f19febb4a8196 | ACENDER/LeetCode | /A01/344.反转字符串.py | 767 | 4.0625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : 344. 反转字符串.py @Time : PyCharm -lqj- 2020-10-8 0008
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
l, r = 0, len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
|
ba6663955c3cf18901f6253d351bf783cbe46252 | lvh1g15/Interview-prep | /examples.py | 11,113 | 3.515625 | 4 | #too easy fam...
def SumList(arr):
size = 0
index = 0
while index < len(arr):
size += arr[index]
index += 1
return size
#basic search
def searchForNumber(cls, num, arr):
n = num
i = 0
a = arr
s = len(arr)
while i < s:
if a[i] == num:
return ("index", i)
else:
i += 1
return False
#sear = searchForNumber(8, [1,10,8,4,5])
#binary search
def binary(n, arr):
l = 0
o = 0
h = len(arr)-1
while l <= h:
o = (l+(h - l)/2)
j = ("({0} = {1} + ({2} - {3})/2)").format(o, l, h, l)
print(j)
if n == arr[o]:
return True
else:
if n < arr[o]:
h = o - 1
else:
l = o + 1
return False
# k = binary(6,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
# print(k)
def sort(arr):
newarr = []
c = 0
for i in arr:
c += 1 #1, 2
l = c - 1 #1, 2
while l >= 0:
if c - 1 == 0: #0
newarr.append(i)
break
length = len(newarr)
decre = length-(length-l)
if i[k] > newarr[decre-1][k]:
newarr.insert(l, i)
l = -1
else:
if l == 0:
newarr.insert(0, i)
break
l -= 1
for i in newarr:
print(" ".join(str(x) for x in i))
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def insert(self, value):
if value > self.value and self.right == None:
self.right = Node(value)
if value > self.value and self.right is not None:
self.right.insert(value)
if value < self.value and self.left == None:
self.left = Node(value)
if value < self.value and self.left is not None:
self.left.insert(value)
class Tree:
def __init__(self, treearray):
self.treearray = treearray
if len(treearray) == 0:
self.parent = None
else:
self.parent = Node(treearray[0])
for i in treearray[0:]:
self.parent.insert(i)
def max(self):
if self.parent == None:
print("tree is empty mofo")
else:
return self.getMax(self.parent)
def getMax(self, node):
if node.right == None:
return node.value
if node.right != None:
return self.getMax(node.right)
def insertbigger(self, value):
if self.parent == None:
self.parent = Node(value)
else:
self.parent.insert(value)
def DFS(self, G, V):
G.append(V)
print(V.value)
if V.left is not None:
if V.left not in G:
self.DFS(G, V.left)
if V.right is not None:
if V.right not in G:
self.DFS(G, V.right)
# searchDFS = Tree([5, 3, 7, 10])
# print(searchDFS.max())
# parentof = searchDFS.parent
# searchDFS.DFS([], parentof)
arr = [3,4,11,33,0]
def largestprofit(mon):
j = len(mon)
c = 0
dif = 0
while j > 0:
for i in arr[c:len(mon)]:
if arr[c] < (i):
if i - arr[c] > dif:
dif = i - arr[c]
j -= 1
c += 1
print(dif)
# largestprofit(arr)
message = 'find you will pain only go you recordings security the into if'
def reversewords(word):
m = word.split(' ')
l = ''
for i in range(len(m)):
l += m[len(m)-1-i] + ' '
print(l)
# reversewords(message)
# print(searchmax.max())
o = 100
i = 2
# def recursivepowers(p, m, counter, rangee):
# if n == m:
# return counter
# else:
# d = 0
# for i in range(root):
# d += i**2
# if d == 100:
# counter += 1
# recursivepowers(2, 100, counter, root-1)
# recursivepowers(2, 100, 0, range(1, 10))
a = [1,2,3,4,5]
for i in range(len(a)-1):
m = a.pop(0)
a.insert(5, m)
# print(a)
r = [1,5,4,3,2]
def leftrotation(r, l):
for i in range(l+1):
m = r.pop(0)
r.insert(len(r), m)
print(r)
y = leftrotation(r, 5)
print y
# leftrotation(a, 4)
# --------------- Stacks --------------------- #
# expn = "{((})]]"
# ano = "{()({})}"
def isbalanced(inp):
l = []
for i in inp:
if i == "{" or i == "(" or i == "[":
l.append(i)
# print(l)
elif i == "}":
print(l, "before")
if l.pop() != "{":
return False
print(l, "after")
elif i == ")":
print(l, "before")
if l.pop() != "(":
return False
print(l, "after")
elif i == "]":
print(l, "before")
if l.pop() != "[":
return False
print(l, "after")
return len(l) == 0
# m = isbalanced(expn)
# print(m)
# given a list of daily stock price in a list A[i], find the span of the stock for each day. A span of stock
# is the max number of days for which the price of the stock was lower than that day
# eg [10, 8, 5, 3, 1, 4, 6, 9, 11] so 8 is day 2 and would be 0 and would also be 0 for 5, 3, 1 however 4 which is day 6
# is greater than 1 and 3 so day 5 and 4 therefore its span is 2
r = [10, 8, 5, 3, 1, 4, 6, 9, 11]
def stkmaxspna(arr):
stk = []
size = len(arr)
n = [0]*size
stk.append(0)
n[0] = 1
i = 1
while i < size:
while len(stk) != 0 and arr[stk[len(stk)-1]] <= arr[i]:
# print("{0} <= {1}".format(arr[stk[len(stk)-1]], arr[i]))
stk.pop()
if (len(stk) == 0):
n[i] += 1
else:
n[i] = i - stk[len(stk)-1]
stk.append(i)
i += 1
return n
# n = stkmaxspna(r)
# print(n)
# -------------------------------------------- #
def maxspan(you):
h = [0]*len(you)
h[0] = 0
i = 0
s = len(you)
while i < s:
h[i] = 1
j = i - 1
while j >= 0 and you[i] > you[j]:
h[i] += 1
j -= 1
i += 1
return h
k = maxspan(r)
# print(k)
a = "aaaaba"
# print(len(a))
def palindrome(str):
for i in range(len(str)):
t = str[:i] + str[i+1:] # we basically want to grab only len -1 elements so one element will always be missing.
# print(t)
if t == t[::-1]: # this is how to reverse an array
return True
return False
l = palindrome(a)
# print(l)
j = 4
def howmany(n):
if n == 1:
return 1
else:
k = ["0"]*n
k[0] = "1"
l = ""
for i in range(len(k)-1):
j = 0
c = 1
while j <= len(k[i]):
if len(k[i]) == 0:
k[i] += "11"
elif k[i][i-1] == k[i][j-1]:
c += 1
else:
l += str(c) + str(j-1)
c = 0
j += 1
k[i] = l
# print(k)
# for i in range(len(a)):
# howmany(j)
# S = [1, 0, -1, 0, -2, 2]
# moo = 0
s = "abaa"
t = "baab"
p = t.count(s[1])
# print(p)
def anagram(s, t):
state = False
if len(s) is not len(t):
return False
for i in range(len(s)):
if s.count(s[i]) - t.count(s[i]) == 0:
state = True
else:
return False
return state
h = anagram(s, t)
print(h)
def reverseString():
s = "hello world"
n = ""
m = s.split(" ")[::-1]
for i in m:
n += i + " "
print(n)
u = "hello world"
def stackreverse(u):
stk = []
new = ""
word = u.split(" ")
for i in word:
stk.append(i)
print(stk)
for i in range(len(stk)):
new += stk.pop() + " "
print(new.strip())
stackreverse(u)
non = [1,2,3,4,5,5,6,7,8,9]
def duplicate(o):
for i in range(len(non)-1):
if non[i] == non[i+1]:
return non[i]
return "no duplicate"
po = duplicate(non)
# print(po)
max = [10,7,4,3,2,5,8,11]
def maxprofits(max):
new = []
for i in range(len(max)):
count = 0
j = i
while max[i] > max[j-1]:
j -= 1
count += 1
new.append(count)
print(new)
maxprofits(max)
expn = "{((})]]"
ano = "{(({}))}"
class Stack:
def __init__(self, items):
self.items = []
def popLast(self, items):
return self.items.pop()
def pushLast(self, items, value):
return self.items.append(value)
def length(selfs, items):
return len(items)
class Node2:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, num):
if num < self.value and self.left is not None:
self.left.insert(num)
if num > self.value and self.right is not None:
self.right.insert(num)
if num < self.value and self.left is None:
self.left = Node(num)
if num > self.value and self.right is None:
self.right = Node(num)
class Tree2:
def __init__(self, inputt):
if len(inputt) == 0:
return
else:
self.parent = Node(inputt[0])
for i in inputt[0:]:
self.parent.insert(i)
def maxintree(self):
if self.parent == None:
return "no parent"
else:
return self.getMax(self.parent)
def getMax(self, node):
if node.right == None:
return node.value
else:
return self.getMax(node.right)
def DFS(self, g, v):
g.append(v)
if v.left is not None:
if v.left not in g:
self.DFS(g, v.left)
if v.right is not None:
if v.right not in g:
self.DFS(g, v.right)
tre2 = Tree2([1,3,5,2,9])
print(tre2.getMax(tre2.parent))
maxy = [8,7,4,3,2,1]
def maxreturn(m):
min = m[0]
max = m[0]
for i in range(len(maxy)-1):
if maxy[i+1] < maxy[i]:
if maxy[i+1] < min:
min = maxy[i + 1]
else:
max = maxy[i+1]
return max - min
y = maxreturn(maxy)
print(y)
ex = [1,2,2,3,3,3,2,4]
r = [1,2,2,2,4]
# ex[-5:-2] = []
r[-4:-1] = []
# print(ex, r)
def connectthree(new):
arr = new
print(arr)
c = 0
for i in range(len(arr)-1):
if arr[i] == arr[i+1]:
c += 1
if c == 2:
print(-i-1, -i+2, i, i+1)
arr[-i-1:-i+2] = []
connectthree(arr)
return
else:
c = 0
return arr
#
# l = connectthree(ex)
# print(l)
upto = 30
def fib(upto):
arr = [1]
total = arr[0]
def recur(arr, total):
print(arr)
if len(arr) == upto:
return arr
else:
arr.append(total)
h = arr[len(arr)-1] + arr[len(arr)-2]
recur(arr, h)
return arr
po = recur(arr, total)
return po
po = fib(upto)
print(po)
|
57e07f11d41aed47af6714b6f52df89ae5e14a20 | zzerjae/Advanced-Computer-Mathematics | /if_else.py | 275 | 3.515625 | 4 | light = input("색을 영문으로 입력하시오 : ")
if light == 'blue':
print("길을 건너세요.")
elif light == 'red':
print("건너지마세여.")
elif light == ‘yellow’:
print(“속도를 줄이세요”)
else:
print("잘못된색입니다.")
|
3de39264837ce0b46ada1d2d9db217bd0ecda733 | stevengates90/StevenLee_ITP2017_PythonExercises2.0-5.0 | /Slices.py | 471 | 4.3125 | 4 | locations = ["Paris","Florence","Venice","Barcelona","Prague","Copenhagen","Vienna","Amsterdam","Budapest"]
print(locations)
c = locations[0:3]
print("The first three cities in the list are:")
print(c)
locations = ["Paris","Florence","Venice","Barcelona","Prague","Copenhagen","Vienna","Amsterdam","Budapest"]
d = locations[3:6]
print("Three cities from the middle of the list are:")
print(d)
e = locations[6:9]
print("The last three cities in the list are:")
print(e)
|
5aac089708fb82084a048fc331a95cb35fd53a95 | collmanxhu/Python-Books | /Python Crash Course/Chap 8 Function/pizza.py | 2,345 | 4.4375 | 4 | # passing an Arbitrary numbers of arguments
def make_pizza(*toppings): # *toppings : tell python to make an empty tuple
"""Print the list of toppings provided"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings): # *toppings : tell python to make an empty tuple
"""Print the list of toppings provided"""
print(f"\nThe lists : {toppings}")
print("\nMaking a pizza with following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# mixing positional and arbitrary arguments
def make_pizza(size, *toppings): # *toppings : tell python to make an empty tuple
"""summarize the pizza we are going to make"""
print(f"\nMaking a {size} inch of pizza with following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(10, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# using arbitrary keyword arguments, accept as many key-value pairs as you want
def build_profile(first, last, **user_info): # '**' cause python to produce an empty dictionary
"""build a dictionary containing everything you want""" # **kwargs are often used to collect non-specific keyword arguments
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein', field='physics')
print(user_profile)
user_profile = build_profile('albert', 'einstein', field='physics', location='princeton')
print(user_profile)
# 8-13 Sandwiches : accept a list of items to make sandwich, one arbitrary argument is needed.
def make_sandwich(sandwich_type, *recipes):
"""summarize the sandwich we are going to make"""
print(f"\nMaking a {sandwich_type} sandwich with following recipe:")
for recipe in recipes:
print(f"- {recipe}")
make_sandwich('chicken', '1/2 cup chicken shredded', 'olive oil', 'salt')
# 8-13 build car info using dictionary, must have manufacturer and model name
def make_car(maker, model, **model_info):
model_info['maker'] = maker
model_info['model'] = model
return model_info
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car) |
d2fadce76bf52d00b3fc918823b9bfeae601a39b | hlgn07/Trial | /hw2_Hasan_Emre_Emmiler_130202015_last.py | 1,913 | 3.53125 | 4 | #Hasan Emre Emmiler
#130202015
#lec2
def isBinary(s):
for i in range(0,len(s)):
if s[i]!='0' and s[i]!='1':
return 0
return 1
def binDecimal(s):
if isBinary(s)==0:
print(s,'is not a binary')
return -1
num=0
m=len(s)-1
for i in range (0,len(s)):
num=num+(ord(s[i])-48)*(2**m)
m=m-1
return num
def stringStats(s):
myList=[0,0,0,0]
for i in range(0,len(s)):
if s[i]>='A' and s[i]<='Z':
myList[0]+=1
if s[i]>='a' and s[i]<='z':
myList[1]+=1
if s[i]>='0' and s[i]<='9':
myList[2]+=1
if s[i]==' ':
myList[3]+=1
return myList
def contain(str1,str2):
m=len(str2)
n=len(str1)
count=0
for i in range(0,n-m+1):
j=0
while j<m:
if str1[i+j].lower()!=str2[j].lower():
break
j=j+1
if j==m:
count+=1
return count
def main():
num=input('enter a task number 1 for binary 2 for String')
if num!='1' or num!='2':
print("ınvalid task number")
if num=='1':
temp=input('enter a binary number (0 to stop:)')
while temp !='0':
num=binDecimal(temp)
if num!=-1:
print('binary(%s)=decimal(%d)'%(temp,num))
temp=input('enter a binary number')
if num=='2':
str1=input('enter a first string:')
str2=input('enter a second string')
temp=stringStats(str1)
print('Number of upper case letters:',temp[0])
print('Number of lower case letters:',temp[1])
print('Number of digit characters:',temp[2])
print('Number of whitespace characters:',temp[3])
print("contain st2 in str1",contain(str1,str2))
if __name__=="__main__":
main()
|
41de6d6ae68d4dab9e87e34a7ef98b85d587135c | payneal/train_problem | /test_train.py | 3,250 | 3.65625 | 4 | import unittest
from train import Train
class Test_Train(unittest.TestCase):
def setUp(self):
self.train = Train()
self.train.add_tracks([
"AB5", "BC4", "CD8", "DC8", "DE6", "AD5", "CE2", "EB3", "AE7"])
def tearDown(self):
self.train = None
def test_get_distance_a_b(self):
distance = self.train.get_distance("AB")
self.assertEqual(distance, 5)
# The distance of the route A-B-C.
# answer = 9
def test_get_distance_a_b_c(self):
distance = self.train.get_distance("ABC")
self.assertEqual(distance, 9)
# The distance of the route A-D
# answer = 5
def test_get_distance_a_d(self):
distance = self.train.get_distance("AD")
self.assertEqual(distance, 5)
# The distance of the route A-D-C.
# answer = 13
def test_get_distance_a_d_c(self):
distance = self.train.get_distance("ADC")
self.assertEqual(distance, 13)
# The distance of the route A-E-B-C-D
# answer= 22
def test_get_distance_a_e_b_c_d(self):
distance = self.train.get_distance("AEBCD")
self.assertEqual(distance, 22)
# The distance of the route A-E-D
def test_get_distance_a_e_d(self):
distance = self.train.get_distance("AED")
self.assertEqual(distance, "NO SUCH ROUTE")
def test_get_no_such_nothing(self):
distance = self.train.get_distance("XY")
self.assertEqual(distance, "NO SUCH ROUTE")
def test_get_no_such_with_graph(self):
distance = self.train.get_distance("ABZ")
self.assertEqual(distance, "NO SUCH ROUTE")
# The number of trips starting at C and ending at C with a maximum of 3 stops.
# In the sample data below, there are two such trips: C-D-C (2 stops).
# and C-E-B-C (3 stops)
# answer = 2
def test_get_distance_c_c_with_max_3(self):
trips = self.train.get_trips_max_limit("C", "C", 3)
self.assertEqual(trips, 2)
# The number of trips starting at A and ending at C with exactly 4 stops.
# In the sample data below, there are three such trips: A to C (via B,C,D);
# A to C (via D,C,D); and A to C (via D,E,B).
# answer = 3
def test_get_distance_a_c_equal(self):
trips = self.train.get_trips_equal("A", "C", 4)
self.assertEqual(trips, 3)
# The length of the shortest route (in terms of distance to travel) from A to C
# answer = 9
def test_get_shortest_a_c(self):
shortest = self.train.get_shortest_route("A", "C")
self.assertEqual(shortest, 9)
# The length of the shortest route (in terms of distance to travel) from B to B.
# answer = 9
def test_get_shortest_b_b(self):
shortest = self.train.get_shortest_route("B", "B")
self.assertEqual(shortest, 9)
# The number of different routes from C to C with a distance of less than 30.
# In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.
def test_get_number_of_diff_routes_c_c_less_than_30(self):
routes = self.train.get_route_count("C", "C", 30)
self.assertEqual(routes, 7)
if __name__ == "__main__":
unittest.main()
|
e4c19bfb169aa693f91946e02e76bae7346dfe5e | pallavmahapatra/DiagonalMatrixPrintExample-1 | /arraypattern.py | 678 | 4 | 4 | m = int(input("Enter the order of matrix: "))
a = [[0 for i in range(m)] for j in range(m)]
temp = 1
for i in range(0,m):
for j in range(0,m):
a[i][j]= temp
temp = temp+1
for i in range(0,m):
for j in range(0,m):
print(a[i][j],sep=',',end='\t')
print("\n")
for i in range(0,m):
temp = i
for j in range(0,i+1):
if(j>=0):
print(a[temp][j],end=',')
temp=temp - 1
else: break
for i in range(1,m):
temp = m-1
for j in range(i,m):
if(temp>=1):
print(a[temp][j],end=',')
temp = temp - 1
else : i = i+1
|
ed0664e6a9910d06fd590cbab87bc4b53912faab | NelcifranMagalhaes/Programns-challenges | /arvoré avl.Dicionário.py | 7,572 | 3.65625 | 4 | #ネルシフラン -- My name in japanese.XD
#Nelcifran
import sys
class avlnode(object): # nó na arvoré avl
def __init__(self,key):
self.key = key
self.left = None
self.right = None
def __str__(self):
return str(self.key)
def __repr__(self):
return str(self.key)
class avltree(object):
def __init__(self):
self.node = None # raiz da arvoré
self.height = -1 # altura da arvoré
self.balance = 0 # fator de balanceamaneto
def insert(self,key):
#criando nó
n = avlnode(key)
# iniciando a arvoré
if not self.node:
self.node = n
self.node.left = avltree()
self.node.right = avltree()
# inserindo a key na subarvoré esquerda
elif key<self.node.key:
self.node.left.insert(key)
#inserindo a key na subarvoré direita
elif key > self.node.key:
self.node.right.insert(key)
#rebalanciando a arvore se necessário
self.rebalance()
def rebalance(self):# rebalanceamento da arvoré.Após inserir ou deletar um nó
# checando se é necessário rebalancear a arvoré
self.update_heights(recursive = False)
self.update_balances(False)
while self.balance < -1 or self.balance > 1:
#subarvoré esquerda é maior que subarvoré direita
if self.balance > 1:
if self.node.left.balance < 0:
self.node.left.rotate_left()
self.update_heights()
self.update_balances()
self.rotate_right()
self.update_heights()
self.update_balances()
#subarvoré esquerda é maior que subarvoré esquerda
if self.balance< -1:
if self.node.right.balance > 0:
self.node.right.rotate_right()
self.update_heights()
self.update_balances()
self.rotate_left()
self.update_heights()
self.update_balances()
def update_heights(self, recursive = True):
# atualizando o tamanho da arvoré
if self.node:
if recursive:
if self.node.left:
self.node.left.update_heights()
if self.node.right:
self.node.right.update_heights()
self.height = 1 + max(self.node.left.height,self.node.right.height)
else:
self.height = -1
def update_balances(self,recursive = True):
# calculando o fator de balanceamento da arvoré
#balanço = tamanho da subarvoré esquerda - tamanho da subarvoré direita
if self.node:
if recursive:
if self.node.left:
self.node.left.update_balances()
if self.node.right:
self.node.right.update_balances()
self.balance = self.node.left.height - self.node.right.height
else:
self.balance = 0
def rotate_right(self):
# rotação á direita
new_root = self.node.left.node
new_left_sub = new_root.right.node
old_root = self.node
self.node = new_root
old_root.left.node = new_left_sub
new_root.right.node = old_root
def rotate_left(self):
#rotação á esquerda
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_root.right.node = new_left_sub
new_root.left.node = old_root
def delete(self,key):
#deletando key da arvoré
if self.node != None:
if self.node.key == key:
# a chave é encontrada em um nó folha,apenas tiro esse cara
if not self.node.left.node and not self.node.right.node:
self.node = None
elif not self.node.left.node:
self.node = self.node.right.node
elif not self.node.right.node:
self.node = self.node.left.node
else:
successor = self.node.right.node
while successor and successor.left.node:
successor = successor.left.node
if successor:
self.node.key = successor.key
self.node.right.delete(successor.key)
elif key < self.node.key:
self.node.left.delete(key)
elif key > self.node.key:
self.node.right.delete(key)
# rabalanceando
self.rebalance()
def inorder_traverse(self):
#subarvoré esquerda - raiz - subarvoré direita
result = []
if not self.node:
return result
result.extend(self.node.left.inorder_traverse())
result.append(self.node.key)
result.extend(self.node.right.inorder_traverse())
return result
def display(self,node = None,level = 0):
if not node:
node = self.node
if node.right.node:
self.display(node.right.node,level+1)
print(('\t'* level),(' /'))
print(('\t'*level),node)
if node.left.node:
print(('\t'*level),(' \\'))
self.display(node.left.node, level +1)
def Incluir(dicion):
Palavra = str(input("Digite a palavra:"))
dicion.append(Palavra)
for key in dicion:
tree.insert(key)
def Excluir(dicion):
word = str(input("Digite a palavra a ser excluida:\n"))
for key in [word]:
tree.delete(key)
#tree.inorder_traverse()
else:
print("Palavra não está no dicionário\n")
def Impressão():
print(tree.inorder_traverse())
print("\n")
tree.display()
if __name__ == "__main__":
dicion = []
tree = avltree()
while True:
print("\n")
print("1 - Inserir Palavra\n2 - retirar palavra\n3 - Impressão em in order\n4 - Sair\n\n")
escolha = ''
while not isinstance(escolha,int):
escolha = input("Escolha:\n")
try:
escolha = int(escolha)
except ValueError:
print("Digite um numero!!")
if escolha == 1:
Incluir(dicion)
elif escolha == 2:
Excluir(dicion)
elif escolha == 3:
Impressão()
elif escolha == 4:
print("Bye...Bye!!\n")
sys.exit(0)
else:
print("Escolha incorreta\n")
#---------------------------------------------------------------
'''tree = avltree()
dicion = [1,2,3,4,5,6,7,8,9,10,15]
for key in dicion:
tree.insert(key)
print(tree.inorder_traverse())
print("Deletando \n")
for key in [1,9,7,15]:
#print("Entrei\n\n")
#if key == 'alicate':
#x = dicion.index('alicate')
#del dicion[x]
tree.delete(key)
print(tree.inorder_traverse())
tree.display()
'''
|
259fe09dc5fab8ac4261a022be97cdf16bb7a759 | kalyanp/social-graph-analysis | /jobs/follower_histogram.py | 1,790 | 4.3125 | 4 | from mrjob.job import MRJob
class FollowerHistogram(MRJob):
"""
A Map/Reduce job to count the number of followers each user has
and then create a count of how many users have how many followers.
Input::
<user_id>\t<follower_id>
Output::
<num_followers>\t<num_users_who_have_that_mahy_followers>
For example, for the following input data::
1\t2
1\t3
1\t3
2\t1
3\t1
3\t2
3\t3
The following would be output::
2\t2
3\t1
That is to say that for this data set, there are 2 users who have 2
followers and 1 user that has 3 followers.
"""
# Map Step 1: Read the file in <user_id>\t<follower_id> and increment
# the follower count for that <user_id>.
def increment_followers(self, key, line):
yield int(line.split('\t')[0]), 1
# Reduce Step 1: Sum the number of followers for each <user_id>
def sum_followers(self, id, followers):
x = 0
for f in followers:
x += f
yield id, x
# Map Step 2: Increment the number of users who have the given number
# of followers.
def increment_users_per_follow_count(self, id, followers):
yield followers, 1
# Reduce Step 2: Sum the follower count for each number of followers
def sum_users_per_follow_count(self, follow_count, users_count):
x = 0
for c in users_count:
x += c
yield follow_count, x
def steps(self):
return [self.mr(self.increment_followers, self.sum_followers),
self.mr(self.increment_users_per_follow_count,
self.sum_users_per_follow_count)]
if __name__ == '__main__':
FollowerHistogram.run()
|
aac90474ce37cc664deb49418ec40c0c229fa227 | Divij-berry14/Python-with-Data-Structures | /Linked List/Linked_List_1.py | 8,313 | 3.515625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def LengthLL(head):
count = 0
while head is not None:
count += 1
head = head.next
return count
def LenghtLLRec(head):
if head is None:
return 0
p = LenghtLLRec(head.next)+1
return p
def InsertNodeLL(head,data,i):
if i < 0 or i > LenghtLLRec(head):
return head
if data == None:
return head
newNode=Node(data)
curr = head
prev = None
count = 0
if i == 0:
newNode.next = head
head = newNode
curr = None
while(curr is not None):
if count == i:
prev.next = newNode
newNode.next = curr
break
prev = curr
curr = curr.next
count += 1
return head
def InputNodeRec(head,data,i):
if head is None:
return None
if i == 0:
newNode = Node(data)
newNode.next = head
p = newNode
return p
p = InsertNodeLL(head.next,data,i-1)
head.next = p
return head
def DeleteNode(head,i):
if i < 0 or i > LengthLL(head):
return head
curr = head
prev = None
count = 0
if i == 0:
head = curr.next
curr = None
return head
while curr is not None:
if count == i:
prev.next = curr.next
break
prev = curr
curr = curr.next
count = count+1
return head
def AppendLastToFirst(head,n):
if head is None:
return None
curr = head
prev = None
length = LenghtLLRec(head)
count = 1
while curr is not None:
if count == n:
temp1 = prev.next
prev.next = None
prev = curr
curr = curr.next
count += 1
curr = head
curr1 = temp1
while curr1.next is not None:
curr1 = curr1.next
curr1.next = curr
return temp1
def RemoveDuplicatesLL(head):
if head is None:
return None
curr = head
while curr is not None and curr.next is not None:
if curr.data == curr.next.data:
# curr.next = None
curr.next = curr.next.next
else:
curr = curr.next
return head
def ReverseLL(head):
if head is None:
return None
curr = head
prev = None
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
def PalindromeLL(head):
if head is None:
return True
s = []
while head is not None:
s.append(head.data)
head = head.next
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left = left + 1
right = right - 1
return True
def ReverseLLII(head, m, n):
start, prev, node, count = None, None, head, 1
while count <= n:
nextNode = node.next
if count == m:
start = prev
elif count > m:
node.next = prev
prev, node = node, nextNode
count += 1
if start:
start.next.next = node
start.next = prev
else:
head.next = node
head = prev
return head
# if head is None:
# return None
# curr1 = head
# prev = None
# i = 1
# j = m - 1
# while curr1 is not None:
# if i == n:
# tempHead = curr1
# break
# else:
# curr1 = curr1.next
# i += 1
#
# while tempHead is not None:
# if j > 0:
# temp = tempHead.next
# tempHead.next = prev
# prev = tempHead
# tempHead = temp
# j -= 1
# curr1.next = prev
# return head
def MidElementLL(head):
slow = head
fast = head
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
print(str(slow.data))
return
def merge_two_sorted_arrays(head1,head2):
if head1 and head2 is None:
return None
finalHead = None
finalTail = None
if head1. data > head2.data:
finalHead = head2
finalTail = head2
head2 = head2.next
else:
finalHead = head1
finalTail = head1
head1 = head1.next
while head1 is not None and head2 is not None:
if head1.data > head2.data:
finalTail.next = head2
finalTail = finalTail.next
head2 = head2.next
else:
finalTail.next = head1
finalTail = finalTail.next
head1 = head1.next
if head1 is not None:
finalTail.next = head1
if head2 is not None:
finalTail.next = head2
return finalHead
def swapNodes(head, x, y):
if head is None:
return None
if x == y:
return head
currX = head
currY = head
prevX = None
prevY = None
while currX is not None and currX.data != x:
prevX = currX
currX = currX.next
while currY is not None and currY.data != y:
prevY = currY
currY = currY.next
if prevX!=None:
prevX.next = currY
else:
head = currY
if prevY!=None:
prevY.next = currX
else:
head = currX
temp = currX.next
currX.next = currY.next
currY.next = temp
return head
def nextLargerNodes(head):
if head is None:
return None
temp = []
while head is not None:
temp.append(head.data)
head = head.next
res = []
for i in range(len(temp)):
j = i+1
while(j <= len(temp)-1):
if temp[j] < temp[i]:
j += 1
if j == len(temp)-1:
res.append(0)
else:
res.append(temp[j])
break
return res
def OddEvenLL(head):
if head is None:
return None
curr = head
evenHead = None
evenTail = None
oddHead = None
oddTail = None
while curr is not None:
if curr.data % 2 ==0:
if evenHead is None:
evenHead = curr
evenTail = curr
else:
evenTail.next = curr
evenTail = curr
else:
if oddHead is None:
oddHead = curr
oddTail = curr
else:
oddTail.next = curr
oddTail = curr
curr = curr.next
if oddHead is None:
return evenHead
oddTail.next = evenHead
evenTail.next = None
head = oddHead
return head
def skip_m_delete_n(head, m, n):
if head is None:
return None
if m == 0:
return head
if n < 0 or m < 0:
return head
curr = head
newHead = None
while curr is not None:
for i in range(m-1):
if curr is None:
return head
curr = curr.next
# print(i)
prev = curr
curr = curr.next
for i in range(n):
if curr is None:
return head
curr = curr.next
prev.next = curr
return head
def print_ll(head):
count = 0
while head is not None:
print(head.data, "->", end=" ")
head = head.next
print("None")
def input_ll():
input_li = [int(x) for x in input().split()]
head = None
tail = None
for curr_data in input_li:
if curr_data == -1:
break
node = Node(curr_data)
if head is None:
head = node
tail = node
else:
tail.next = node
tail = node
return head
Head = input_ll()
# head2 =InputLL()
print_ll(Head)
# head = DeleteNode(head,3)
# printLL(head)
# print(LenghtLLRec(head))
# head = InsertNodeLL(head, 9, 5)
# printLL(head)
# head = InputNodeRec(head, 9, 3)
# printLL(head)
# head = AppendLastToFirst(head,4)
# printLL(head)
Head = RemoveDuplicatesLL(Head)
print_ll(Head)
# head = ReverseLL(head)
# printLL(head)
# print(PalindromeLL(head))
# head = ReverseLLII(head,2,3)
# printLL(head)
MidElementLL(Head)
# head = merge_two_sorted_arrays(head1, head2)
# printLL(head)
# head = OddEvenLL(head)
# printLL(head)
# head = skipMdeleteN(head, 2, 2)
# printLL(head)
|
e77fe09a1f72a05d0749b6d58435823c17bea3e7 | chesta123/PYTHON-codes | /printing star pattern.py | 353 | 3.890625 | 4 | print("provide the value of number of rows")
n=int(input())
print("press 1 if you want the pattern to be in increasing order and 0 if you want pattern to be in reverse order")
a = int(input())
if a==1 :
i = 0
while i<n+1 :
print("*"*i)
i = i+1
else :
i = n
while i>0:
print("*"*i)
i = i - 1
|
4cbe18f85afaf6498431b6d96888c77dd155e739 | mozgolom112/Geekbrains | /Python/Loops, recursion, functions/hw/task_9.py | 905 | 4.125 | 4 | #Задача 9. Среди натуральных чисел, которые были
# введены, найти наибольшее по сумме цифр.
# Вывести на экран это число и сумму его цифр.
def max_sum_num(*arg):
if len(arg) == 0:
print('Введите числа')
return 0
max_num = 0
max_sum = 0
current_sum = 0
current_num = 0
for num in arg:
current_num = num
current_sum = 0
if num < 0:
num *= -1
while num != 0:
current_sum += num % 10
num //= 10
if (max_sum <= current_sum):
max_sum = current_sum
max_num = current_num
print(f'Число с максимальной суммой цифр: {max_num} с суммой {max_sum}')
max_sum_num(5664, 3, 11111, 45674994, 9999, 0) |
62fc19ed380584a8409693c698d6ad1cac1afbf3 | sharath28/leetcode | /prob69/square_root.py | 934 | 3.59375 | 4 | from math import e, log
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# Calculator method
# if x<2:
# return x
# left = int(e**(0.5*log(x)))
# right = left + 1
# return left if right*right > x else right
##########################
# Binary Search
# if x < 2:
# return x
# left, right = 2, x//2
# while left <= right:
# pivot = left + (right-left)//2
# num = pivot*pivot
# if num > x:
# right = pivot - 1
# elif num < x:
# left = pivot + 1
# else:
# return pivot
# return right
########################
#Recursion
if x < 2:
return x
left = self.mySqrt(x>>2)<<1
right = left + 1
return left if right * right > x else right
|
c528d74bb28acf67a379a7001173cc8817883fb5 | AlexNika/Python_Basics | /Урок_3/hw03_easy.py | 2,201 | 3.984375 | 4 | __author__ = 'Николаев Александр Вадимович'
# Задание-1:
# Напишите функцию, округляющую полученное произвольное десятичное число
# до кол-ва знаков (кол-во знаков передается вторым аргументом).
# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).
# Для решения задачи не используйте встроенные функции и функции из модуля math.
def my_round(number, ndigits):
number = number * (10 ** ndigits)
if float(number) - int(number) > 0.5:
number = number // 1 + 1
else:
number = number // 1
return number / (10 ** ndigits)
def my_round1(number, ndigits):
number = number * (10 ** ndigits) + 0.41
number = number // 1
return number / (10 ** ndigits)
print(my_round(2.1234567, 5))
print(my_round(-2.1999967, 5))
print(my_round(2.9999967, 5))
print(my_round(2.9999927, 5))
print(my_round1(2.1234567, 5))
print(my_round1(-2.1999967, 5))
print(my_round1(2.9999967, 5))
print(my_round1(2.9999927, 5))
# Задание-2:
# Дан шестизначный номер билета. Определить, является ли билет счастливым.
# Решение реализовать в виде функции.
# Билет считается счастливым, если сумма его первых и последних цифр равны.
# !!!P.S.: функция не должна НИЧЕГО print'ить
def lucky_ticket(ticket_number):
n = list(str(ticket_number))
l = len(n)
if l != 6:
return 'Ошибка! номер билета не шестизначный'
s1 = 0
s2 = 0
for i in range(l // 2):
s1 += int(n[i])
s2 += int(n[i + l // 2])
if s1 == s2:
return 'Да'
else:
return 'Нет'
print(f'Билет 123006 счастливый? - {lucky_ticket(123006)}')
print(f'Билет 12321 счастливый? - {lucky_ticket(12321)}')
print(f'Билет 436751 счастливый? - {lucky_ticket(436751)}')
|
4cc0c275c3bdc5a4389bdca73a9d78450760412e | TaylURRE/apprentice | /milestone5/m5-dfs.py | 689 | 4.0625 | 4 | #!/usr/bin/env python
# Given this graph
graph = {'A' : ['B','S'],
'B' : ['A'],
'C' : ['D','E','F','S'],
'D' : ['C'],
'E' : ['C','H'],
'F' : ['C','G'],
'G' : ['F','S'],
'H' : ['E','G'],
'S' : ['A','C','G']
}
# Write a depth first search to visit every node in the graph count the number of edges traversed
def dfs_visit(graph, start):
queue = [start]
path = []
count = 1
while queue:
vertex = queue.pop()
count += 1
if vertex in path:
continue
path.append(vertex)
for neighbor in graph[vertex]:
queue.append(neighbor)
return count
ans = dfs_visit(graph, 'A')
print(ans)
|
687ef444d719092796f2757ec40b88e2b2a56dd7 | Anant-Goyal/SimplePythonCalculator | /main.py | 659 | 4.0625 | 4 |
# This is my first project....
# I am making this project by watching a yt Video LOL....
def add(a,b):
result=a+b
print(result)
def sub(a,b):
result=a-b
print(result)
def mul(a,b):
result=a*b
print=(result)
def div(a,b):
result=a/b
print(result)
a=int(input("Please Enter The First Number"))
b=int(input("Please Enter the Second number"))
op=input("Enter the Operator (It means what you want to do + - * / ): ")
if op=="+":
add(a,b)
elif op=="-":
sub(a,b)
elif op=="*":
mul(a,b)
elif op=="/":
div(a,b)
else:
print("Invalid Operator")
#MadeByAnant
|
b47e2a4188342254992b2a1eb10303c5a27420a2 | dalek7/Algorithms | /Optimization/tensorflow-linear_regression/05-minimizing_cost_tf_optimizer.py | 973 | 3.53125 | 4 | # Lab 3 Minimizing Cost
import tensorflow as tf
import matplotlib.pyplot as plt
tf.set_random_seed(777) # for reproducibility
# tf Graph Input
X = [1, 2, 3]
Y = [1, 2, 3]
# Set wrong model weights
W = tf.Variable(-1.0)
# Linear model
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Minimize: Gradient Descent Magic
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
train = optimizer.minimize(cost)
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
W_history = []
steps =[]
for step in range(10):
W1 = sess.run(W)
print(step, W1)
W_history.append(W1)
steps.append(step)
sess.run(train)
linestyles = ['-', '--', '-.', ':']
# Plot
with plt.style.context(('dark_background')): # Temporary styling
plt.plot(steps, W_history, linestyle=linestyles[1])
plt.title('W', fontsize=10)
plt.show() |
1ae7cb204b0ab0105d456caef5152b9cb90f2c14 | allyn-bottorff/basic-computer-games | /50_Horserace/python/horserace.py | 8,797 | 3.859375 | 4 | import math
import random
import time
from typing import List, Tuple
def basic_print(*zones, **kwargs) -> None:
"""Simulates the PRINT command from BASIC to some degree.
Supports `printing zones` if given multiple arguments."""
line = ""
if len(zones) == 1:
line = str(zones[0])
else:
line = "".join([f"{str(zone):<14}" for zone in zones])
identation = kwargs.get("indent", 0)
end = kwargs.get("end", "\n")
print(" " * identation + line, end=end)
def basic_input(prompt: str, type_conversion=None):
"""BASIC INPUT command with optional type conversion"""
while True:
try:
inp = input(f"{prompt}? ")
if type_conversion is not None:
inp = type_conversion(inp)
break
except ValueError:
basic_print("INVALID INPUT!")
return inp
# horse names do not change over the program, therefore making it a global.
# throught the game, the ordering of the horses is used to indentify them
HORSE_NAMES = [
"JOE MAW",
"L.B.J.",
"MR.WASHBURN",
"MISS KAREN",
"JOLLY",
"HORSE",
"JELLY DO NOT",
"MIDNIGHT",
]
def introduction() -> None:
"""Print the introduction, and optional the instructions"""
basic_print("HORSERACE", indent=31)
basic_print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", indent=15)
basic_print("\n\n")
basic_print("WELCOME TO SOUTH PORTLAND HIGH RACETRACK")
basic_print(" ...OWNED BY LAURIE CHEVALIER")
y_n = basic_input("DO YOU WANT DIRECTIONS")
# if no instructions needed, return
if y_n.upper() == "NO":
return
basic_print("UP TO 10 MAY PLAY. A TABLE OF ODDS WILL BE PRINTED. YOU")
basic_print("MAY BET ANY + AMOUNT UNDER 100000 ON ONE HORSE.")
basic_print("DURING THE RACE, A HORSE WILL BE SHOWN BY ITS")
basic_print("NUMBER. THE HORSES RACE DOWN THE PAPER!")
basic_print("")
def setup_players() -> List[str]:
"""Gather the number of players and their names"""
# ensure we get an integer value from the user
number_of_players = basic_input("HOW MANY WANT TO BET", int)
# for each user query their name and return the list of names
player_names = []
basic_print("WHEN ? APPEARS,TYPE NAME")
for _ in range(number_of_players):
player_names.append(basic_input(""))
return player_names
def setup_horses() -> List[float]:
"""Generates random odds for each horse. Returns a list of
odds, indexed by the order of the global HORSE_NAMES."""
odds = [random.randrange(1, 10) for _ in HORSE_NAMES]
total = sum(odds)
# rounding odds to two decimals for nicer output,
# this is not in the origin implementation
return [round(total / odd, 2) for odd in odds]
def print_horse_odds(odds) -> None:
"""Print the odds for each horse"""
basic_print("")
for i in range(len(HORSE_NAMES)):
basic_print(HORSE_NAMES[i], i, f"{odds[i]}:1")
basic_print("")
def get_bets(player_names: List[str]) -> List[Tuple[int, float]]:
"""For each player, get the number of the horse to bet on,
as well as the amount of money to bet"""
basic_print("--------------------------------------------------")
basic_print("PLACE YOUR BETS...HORSE # THEN AMOUNT")
bets: List[Tuple[int, float]] = []
for name in player_names:
horse = basic_input(name, int)
amount = None
while amount is None:
amount = basic_input("", float)
if amount < 1 or amount >= 100000:
basic_print(" YOU CAN'T DO THAT!")
amount = None
bets.append((horse, amount))
basic_print("")
return bets
def get_distance(odd: float) -> int:
"""Advances a horse during one step of the racing simulation.
The amount travelled is random, but scaled by the odds of the horse"""
d = random.randrange(1, 100)
s = math.ceil(odd)
if d < 10:
return 1
elif d < s + 17:
return 2
elif d < s + 37:
return 3
elif d < s + 57:
return 4
elif d < s + 77:
return 5
elif d < s + 92:
return 6
else:
return 7
def print_race_state(total_distance, race_pos) -> None:
"""Outputs the current state/stop of the race.
Each horse is placed according to the distance they have travelled. In
case some horses travelled the same distance, their numbers are printed
on the same name"""
# we dont want to modify the `race_pos` list, since we need
# it later. Therefore we generating an interator from the list
race_pos_iter = iter(race_pos)
# race_pos is stored by last to first horse in the race.
# we get the next horse we need to print out
next_pos = next(race_pos_iter)
# start line
basic_print("XXXXSTARTXXXX")
# print all 28 lines/unit of the race course
for line in range(28):
# ensure we still have a horse to print and if so, check if the
# next horse to print is not the current line
# needs iteration, since multiple horses can share the same line
while next_pos is not None and line == total_distance[next_pos]:
basic_print(f"{next_pos} ", end="")
next_pos = next(race_pos_iter, None)
else:
# if no horses are left to print for this line, print a new line
basic_print("")
# finish line
basic_print("XXXXFINISHXXXX")
def simulate_race(odds) -> List[int]:
num_horses = len(HORSE_NAMES)
# in spirit of the original implementation, using two arrays to
# track the total distance travelled, and create an index from
# race position -> horse index
total_distance = [0] * num_horses
# race_pos maps from the position in the race, to the index of the horse
# it will later be sorted from last to first horse, based on the
# distance travelled by each horse.
# e.g. race_pos[0] => last horse
# race_pos[-1] => winning horse
race_pos = list(range(num_horses))
basic_print("\n1 2 3 4 5 6 7 8")
while True:
# advance each horse by a random amount
for i in range(num_horses):
total_distance[i] += get_distance(odds[i])
# bubble sort race_pos based on total distance travelled
# in the original implementation, race_pos is reset for each
# simulation step, so we keep this behaviour here
race_pos = list(range(num_horses))
for line in range(num_horses):
for i in range(num_horses - 1 - line):
if total_distance[race_pos[i]] < total_distance[race_pos[i + 1]]:
continue
race_pos[i], race_pos[i + 1] = race_pos[i + 1], race_pos[i]
# print current state of the race
print_race_state(total_distance, race_pos)
# goal line is defined as 28 units from start
# check if the winning horse is already over the finish line
if total_distance[race_pos[-1]] >= 28:
return race_pos
# this was not in the original BASIC implementation, but it makes the
# race visualization a nice animation (if the terminal size is set to 31 rows)
time.sleep(1)
def print_race_results(race_positions, odds, bets, player_names) -> None:
"""Print the race results, as well as the winnings of each player"""
# print the race positions first
basic_print("THE RACE RESULTS ARE:")
for position, horse_idx in enumerate(reversed(race_positions), start=1):
line = f"{position} PLACE HORSE NO. {horse_idx} AT {odds[horse_idx]}:1"
basic_print("")
basic_print(line)
# followed by the amount the players won
winning_horse_idx = race_positions[-1]
for idx, name in enumerate(player_names):
(horse, amount) = bets[idx]
if horse == winning_horse_idx:
basic_print("")
basic_print(f"{name} WINS ${amount * odds[winning_horse_idx]}")
def main_loop(player_names, horse_odds) -> None:
"""Main game loop"""
while True:
print_horse_odds(horse_odds)
bets = get_bets(player_names)
final_race_positions = simulate_race(horse_odds)
print_race_results(final_race_positions, horse_odds, bets, player_names)
basic_print("DO YOU WANT TO BET ON THE NEXT RACE ?")
one_more = basic_input("YES OR NO")
if one_more.upper() != "YES":
break
def main() -> None:
# introduction, player names and horse odds are only generated once
introduction()
player_names = setup_players()
horse_odds = setup_horses()
# main loop of the game, the player can play multiple races, with the
# same odds
main_loop(player_names, horse_odds)
if __name__ == "__main__":
main()
|
b591d70664b2243bd9e9a7b493b1dc2649b6c293 | roziio0603/Python | /ejercicios/ejercicio26.py | 428 | 3.9375 | 4 | ##ROCIO
##EJERCICIO 26
valor1 = int(input("Ingrese numero1"))
valor2 = int(input("Ingrese numero2"))
valor3 = int(input("Ingrese numero3"))
suma = int(valor1) + int(valor2) + int(valor3)
resta = int(valor1) - int(valor2) - int(valor3)
multiplicacion = int(valor1) * int(valor2) * int(valor3)
print ("La suma es:.{}".format(suma))
print ("La resta es:.{}".format(resta))
print ("La multiplicacion es:.{}".format(multiplicacion))
|
48ff85b2277fc8c85c2a523a086b44b8ec697602 | trivial-search/Python_the_hard_way | /Modules_code/Module 2/argv.py | 995 | 4.03125 | 4 |
#import the argv method from the sys module
from sys import argv
#declare the expected command line arguments
script,first_var,second_var,third_var = argv
print("The script using which the program was run" , script)
print("The first argument passed was",first_var)
#print the lenght of the number of arguments
print(f"The total number of arguments is {len(argv)}")
#print the array of script and argument recieved on the command line
print(argv)
#another way to write the above is to just import sys and use sys.argv in the code to call the argv method. Clearly this is inefficient
import sys
#declare the expected command line arguments
script,first_var,second_var,third_var = sys.argv
print("The script using which the program was run" , script)
print("The first argument passed was",first_var)
#print the lenght of the number of arguments
print(f"The total number of arguments is {len(sys.argv)}")
#print the array of script and argument recieved on the command line
print(sys.argv)
|
bd9359fff68fd47169bec276912ef3d2c4ef1933 | feihu-jun/beginning | /continue不能执行代码没错.py | 218 | 3.75 | 4 | #continue
n = 0#一输入就闪掉 但是代码没问题啊
while n < 10 :
n = n + 1
if n % 2 == 0:
continue:
# continue语句会直接继续下一轮循环,不执行后面的print
print(n)
input() |
f8eea4f08c0bb835108055deae1e76fa5afff7aa | succinction/Python | /lists.py | 813 | 4.03125 | 4 |
x = 5
y = ['the', 42, ['bye'] ]
lst = [x,x,x,y, 'another string']
print(lst)
print('Bye : ' + lst[3][2][0])
print('last thing : ' + lst[-1])
#######################
tuple = (x,x,x)
print(tuple[2])
dictionary = {'key1': 123, 'key2': 456}
print(dictionary['key1'])
#######################
print("################ rng = list(range(10))")
rng = list(range(10))
print(rng)
print("################")
lst2 = [23, 53, 3, 7, 19]
for v in lst2:
v += 5
print(v)
print("#######3#########")
lst3 = [23, 53, 3, 7, 19]
for i in range(len(lst3)):
lst3[i] += 9
print(i, lst3[i])
print('\b\b\bindex: {}, value: {}'.format(i, lst3[i]))
print("#######4#########")
lsst = [3, 2,"hi"]
num = input('what is your fav num? : ')
lsst.append(int(num))
removed = lsst.pop(2)
print(lsst)
print(removed)
# print()
|
e552a3ea39f7b7f5007979a35ff3716ee79100e7 | Ze4lfRoG/ctf-kit | /crypto/caesar.py | 468 | 3.734375 | 4 | __author__ = 'ruiqin'
cipher = raw_input('please input the cipher: ')
for i in range(1,26):
result = ''
for c in cipher:
if ord(c) in range(97, 123):
d = ord(c) + i
if d > 122:
d -= 26
result += chr(d)
elif ord(c) in range(65, 91):
d = ord(c) + i
if d > 90:
d -= 26
result += chr(d)
else:
result += c
print result
|
5385719904df3e26e73973223ea75afede88ee37 | ang3lls/Training | /python/Aulas 6 e 7/002.py | 258 | 3.6875 | 4 | coisa = (input('Escreva algo: '))
print('O tipo primitivo é', type(coisa))
print('Ele é um numero: ', coisa.isalnum())
print('Ele é uma palavra: ', coisa.isalpha())
print('Letras maiuscula: ', coisa.isupper())
print('letras minusculas ', coisa.islower())
|
d2a403ea3154716f42ca04d2be98ef73a2916cfe | EmineBasheva/Python101-HackBG | /week7/scan-bg-web/histogram.py | 416 | 3.609375 | 4 | class Histogram:
def __init__(self):
self.__histogram = {}
def get_dict(self):
return self.__histogram
def add(self, name):
if name not in self.__histogram:
self.__histogram[name] = 1
else:
self.__histogram[name] += 1
def count(self, name):
return self.__histogram[name]
def items(self):
return self.__histogram.items() |
cf1b38544090cda50a938d7437981a648fb9d762 | Touhid7051/ProblemSolving-with-Python | /Login .py | 522 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[28]:
class user:
name = ''
email = ''
password = ''
login=False
def sum(self):
email=input('enter mail: ')
password=input('enter password: ')
if email==self.email and password==self.password:
login=True
print('login successful!!')
else:
print('login failed')
user1 = user()
user1.name='tareq'
user1.email='sunday@gmail.com'
user1.password='12345'
user1.sum()
# In[ ]:
# In[ ]:
|
b9fabe0589d9ecd9bc8e4dbb5c50c7ee252d56a1 | amyrrich/hackerrank | /python3/intersection.py | 262 | 3.6875 | 4 | #!/opt/local/bin/python3.4
# https://www.hackerrank.com/challenges/py-set-intersection-operation
numen = int(input())
subs = set(map(int,input().split()[:numen]))
numfr = int(input())
subs = subs.intersection(map(int,input().split()[:numfr]))
print(len(subs))
|
35e847cf1cf8a80bb3e91e78a4109b2cd1bfcd80 | ri5h46h/News-Reader-in-Python | /combined_news_reader_v2.0.py | 9,167 | 3.640625 | 4 | # This Python Program will show news from various famous news sources like ndtv,
# Hindustan Times, IndiaToday and more...
# Program by Rishabh Narayan
# importing the modules
import requests # pip install requests
from bs4 import BeautifulSoup # pip install bs4
import csv
import json
import pyttsx
engine = pyttsx.init()
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
engine.setProperty('rate', 130)
# engine.say("Hello, I can speak anything ...")
engine.runAndWait()
def speak(str):
engine.say(str)
engine.runAndWait()
# Defining main functions of the program
def getData(url):
'''This getData function will fetch the HTML Data from the
URL passed as argument'''
r = requests.get(url)
return r.text
def speak1(str):
'''This speak function will speak the news headlines which are
retrieved from the URL'''
from win32com.client import Dispatch
speak = Dispatch("SAPI.SpVoice")
speak.Speak(str)
print(
"\n-------------- Welcome to News reader designed in Python. -------------- \n -------------- Made with love ❤ by Rishabh Narayan -------------- ")
# speak("My name is Rishabh Narayan") # check
# from here I am defining the functions for news sources
def mainProgram():
def newsIndianExpress():
myHtmlData = getData('https://indianexpress.com/section/india/')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'nation'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# newsIndianExpress()
def newsBBC():
myHtmlData = getData('https://www.bbc.com/news/world/asia/india')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for h3 in soup.find("div", {'class': 'gel-layout gel-layout--equal'}).find_all('h3'):
print(h3.get_text())
speak(h3.get_text())
# newsBBC()
def newsEconomicTimes():
myHtmlData = getData('https://economictimes.indiatimes.com/')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'tabsContent'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# newsEconomicTimes()
def newsHindustanTimes():
myHtmlData = getData('https://www.hindustantimes.com/india-news/')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'news-area more-news-section'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# newsHindustanTimes()
def newsIndiaToday():
myHtmlData = getData('https://www.indiatoday.in/india')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for h2 in soup.find("div", {'class': 'view-content'}).find_all('h2'):
print(h2.get_text())
speak(h2.get_text())
# newsIndiaToday()
def newsNDTV():
myHtmlData = getData('https://www.ndtv.com/india?pfrom=home-mainnavgation')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'new_storylising'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# newsNDTV()
def news_news18():
myHtmlData = getData('https://www.news18.com/india/')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'section-blog'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# news_news18()
def newsAPI():
url = ('http://newsapi.org/v2/top-headlines?country=in&apiKey=a5b172a2897744d9af10f51fa659197e')
response = requests.get(url)
text = response.text
my_json = json.loads(text)
x = int(input("Enter the number of headlins you want to see : "))
for i in range(0, x):
speak(my_json['articles'][i]['title'])
print(my_json['articles'][i]['title'])
# newsAPI()
def newsTOI():
myHtmlData = getData('https://timesofindia.indiatimes.com/india')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'main-content'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# newsTOI()
def techNewsIndiaToday():
myHtmlData = getData('https://www.indiatoday.in/technology')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'itg-layout-container itg-front tech-layout-page'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# techNewsIndiaToday()
def techNewsGadgets360():
myHtmlData = getData('https://gadgets.ndtv.com/news')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'content_section'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# techNewsGadgets360()
def sportsIndianExpress():
myHtmlData = getData('https://indianexpress.com/section/sports/')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'nation'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
def googleNews():
myHtmlData = getData('https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en')
soup = BeautifulSoup(myHtmlData, 'html.parser')
# print(soup.prettify())
for a in soup.find("div", {'class': 'lBwEZb BL5WZb xP6mwf'}).find_all('a'):
print(a.get_text())
speak(a.get_text())
# The following will ask your choice for news source
print("\n \nWhich source would you like to hear news from ?")
print("\n \n1. The Indian Express")
print("2. BBC News")
print("3. The Economic Times")
print("4. Hindustan Times")
print("5. India Today")
print("6. NDTV News")
print("7. CNN-News18")
print("8. NewsAPI")
print("9. The Times of India")
print("10. Tech News from from India Today")
print("11. Tech news from Gadgets 360 , An NDTV Venture")
print("12. Sports news from The Indian Express")
print("13. Google News")
print("\nYour Choice (Enter the number)")
userChoice = int(input("Hey User ! Please Enter Your Choice : "))
if userChoice == 1:
print("\nNow displaying news from The Indian Express")
speak("Now displaying news from The Indian Express")
newsIndianExpress()
elif userChoice == 2:
print("\nNow displaying news from BBC News")
speak("Now displaying news from BBC News")
newsBBC()
elif userChoice == 3:
print("\nNow displaying news from The Economic Times")
speak("Now displaying news from The Economic Times")
newsEconomicTimes()
elif userChoice == 4:
print("\nNow displaying news from Hindustan Times")
speak("Now displaying news from Hindustan Times")
newsHindustanTimes()
elif userChoice == 5:
print("\nNow displaying news from India Today")
speak("Now displaying news from India Today")
newsIndiaToday()
elif userChoice == 6:
print("\nNow displaying news from NDTV News")
speak("Now displaying news from NDTV News")
newsNDTV()
elif userChoice == 7:
print("\nNow displaying news from CNN-News18")
speak("Now displaying news from CNN-News18")
news_news18()
elif userChoice == 8:
print("\nNow you will see news from News API")
speak("Now you will see news from News API")
newsAPI()
elif userChoice == 9:
print("\nNow displaying news from The Times of India")
speak("Now displaying news from The Times of India")
newsTOI()
elif userChoice == 10:
print("\nNow displaying Technology news from India Today")
speak("Now displaying Technology news from India Today")
techNewsIndiaToday()
elif userChoice == 11:
print("\nNow displaying Technology news from Gadgets 360, An NDTV Venture")
speak("Now displaying Technology news from Gadgets 360, An NDTV Venture")
techNewsGadgets360()
elif userChoice == 12:
print("\nNow displaying sports news from The Indian Express")
speak("Now displaying sports news from The Indian Express")
sportsIndianExpress()
else:
print("\nNow showing news from Google News")
speak("Now showing news from Google News")
googleNews()
# Now Asking User that whether he/she wants to restart the program or not
restart = input("\nDo you want to see news again (y/n): ")
if restart == 'y' or restart == 'Y':
mainProgram()
else:
exit()
if __name__ == "__main__":
mainProgram()
|
446784028aec5cfd082c3b56e863bc0943f05a65 | seshadribpl/seshadri_scripts | /python/NumberConvert.py | 2,540 | 4.53125 | 5 | #!/usr/bin/env python
import sys
import re
raw_number = str(input('Enter a number: '))
print(raw_number)
# number_without_commas = re.sub("\D", "", raw_number)
if ',' in raw_number:
number_without_commas = raw_number.replace(',', '')
# print('number without commas: %s' %number_without_commas)
else:
number_without_commas = raw_number
# print(number_without_commas)
if not number_without_commas.isdigit():
print('not a number')
sys.exit(-1)
else:
number_without_commas = raw_number
# print(number_without_commas)
number_len = len(raw_number)
if number_len < 4:
print('The number %s is less than 4 digits long; no need for commas' %number_without_commas)
sys.exit(0)
def convert_to_intl(number):
reversed_number = ''.join(reversed(number))
reversed_number_with_commas = (re.sub(r'(...)', r'\1,', reversed_number))
converted_number_with_commas = ''.join(reversed(reversed_number_with_commas))
if converted_number_with_commas[0] == ',':
number_with_leading_comma_removed = converted_number_with_commas[1:]
print('the number in the international system is: %s' %number_with_leading_comma_removed)
else:
print ('the number in the international system is: %s' %converted_number_with_commas)
def convert_to_indian(number):
reversed_number = ''.join(reversed(number))
# print('the reversed number is: %s' %reversed_number)
# Break up the reversed number into two parts
last_three_digits = number[-3:]
# print('the last three digits are: %s' %last_three_digits)
part_2_reversed = reversed_number[3:]
# print('part_1_reversed is: %s' %part_1_reversed)
# print('part_2_reversed is: %s' %part_2_reversed)
# Now add commas to part2
reversed_part_2_with_commas = (re.sub(r'(..)',r'\1,', part_2_reversed))
# print(reversed_part_2_with_commas)
converted_part_2_with_commas = ''.join(reversed(reversed_part_2_with_commas))
# print(converted_part_2_with_commas)
if converted_part_2_with_commas[0] == ',':
converted_part_2_with_leading_comma_removed = converted_part_2_with_commas[1:]
# print(converted_part_2_with_leading_comma_removed)
converted_number = converted_part_2_with_leading_comma_removed + ',' + last_three_digits
print('the converted number in the Indian system is: %s' %converted_number)
if __name__ == '__main__':
convert_to_indian(number_without_commas)
convert_to_intl(number_without_commas)
|
9703ba038a5b48985836f8830a9f3b1e86bb718f | chrisjdavie/interview_practice | /old_leetcode/0079-word-search/more_concise.py | 4,897 | 3.984375 | 4 | """
https://leetcode.com/problems/word-search/
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
The not-too Pythonic "class Solution" is a leetcode thing
This is a vast improvement compared to mine
- it has a unified validity check at the start
- holds board as a local constant
- clearly shows what the dfs is doing
- is in general way easier to read
"""
from typing import List, Set
from unittest import TestCase
from parameterized import parameterized
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row_len = len(board)
col_len = len(board[0])
def dfs(row_num: int, col_num: int, char_pos: int, visited: Set) -> bool:
coords = (row_num, col_num)
if (row_num >= row_len
or row_num < 0
or col_num >= col_len
or col_num < 0
or coords in visited
or board[row_num][col_num] != word[char_pos]):
return False
visited.add(coords)
result = (
char_pos == len(word) - 1
or dfs(row_num + 1, col_num, char_pos + 1, visited)
or dfs(row_num - 1, col_num, char_pos + 1, visited)
or dfs(row_num, col_num + 1, char_pos + 1, visited)
or dfs(row_num, col_num - 1, char_pos + 1, visited)
)
visited.remove(coords)
return result
for row_num in range(row_len):
for col_num in range(col_len):
visited = set()
if dfs(row_num, col_num, 0, visited):
return True
return False
class TestSolution(TestCase):
def setUp(self):
self.solution = Solution()
@parameterized.expand(
[("ABCCED", True),
("SEE", True),
("ABCB", False)]
)
def test_example(self, word, expected_result):
board = [
["A", "B", "C", "E"],
["S", "F", "C", "S"],
["A", "D", "E", "E"]
]
self.assertEqual(
self.solution.exist(board, word), expected_result
)
def test_not_present(self):
board = [["A", "A"],
["A", "A"]]
self.assertFalse(self.solution.exist(board, "B"))
def test_breaks_both(self):
word = "AB"
board = [
["A", "B"],
["A", "D"]
]
self.assertTrue(self.solution.exist(board, word))
@parameterized.expand([("A", True), ("I", True), ("D", False)])
def test_find_single_letter(self, word, expected_result):
board = [
["B", "C", "E"],
["F", "A", "G"],
["H", "I", "J"]
]
self.assertEqual(
self.solution.exist(board, word), expected_result
)
@parameterized.expand([
("AF", True),
("IJ", True),
("GE", True),
("GC", False),
("FG", False),
("CI", False)])
def test_find_two_letters(self, word, expected_result):
board = [
["B", "C", "E"],
["F", "A", "G"],
["H", "I", "J"]
]
self.assertEqual(
self.solution.exist(board, word), expected_result
)
@parameterized.expand(
[("BCE", True),
("BCI", False),
("CAH", False)])
def test_find_three_chars(self, word, expected_result):
board = [
["B", "C", "E"],
["F", "A", "G"],
["H", "I", "J"]
]
self.assertEqual(
self.solution.exist(board, word), expected_result
)
def test_two_starting_chars(self):
word = "BI"
board = [
["B", "C"],
["I", "B"]
]
self.assertTrue(self.solution.exist(board, word))
def test_cannot_use_char_twice_horz(self):
word = "BCB"
board = [
["B", "C"]
]
self.assertFalse(self.solution.exist(board, word))
def test_cannot_use_char_twice_vert(self):
word = "BCB"
board = [
["B"],
["C"]
]
self.assertFalse(self.solution.exist(board, word))
def test_cannot_use_char_twice_after_start_horiz(self):
word = "BCDC"
board = [
["B", "C", "D"]
]
self.assertFalse(self.solution.exist(board, word))
def test_cannot_use_char_twice_after_start_vert(self):
word = "BCEC"
board = [
["B"],
["C"],
["E"]
]
self.assertFalse(self.solution.exist(board, word))
|
d2c6bdf78f2e8413cfaf95b26a570ca4afab9284 | Randyedu/python | /知识点/04-LiaoXueFeng-master/48-collections.py | 3,071 | 4.21875 | 4 | '''
collections
collections是Python内建的一个集合模块,提供了许多有用的集合类。
'''
# namedtuple
# namedtuple是一个函数,它用来创建一个自定义的tuple对象
# 并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
# 我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。
p = (1,2)
from collections import namedtuple
Point = namedtuple('Point',['x','y'])
p = Point(1, 2)
print(p.x, p.y)
# 可以验证创建的Point对象是tuple的一种子类:
print(isinstance(p, Point))
print(isinstance(p, tuple))
'''
deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。
'''
from collections import deque
q = deque(['a','b','c'])
q.append('x')
q.appendleft('y')
print(q)
'''
defaultdict
使用dict时,如果引用的Key不存在,就会抛出KeyError。
如果希望key不存在时,返回一个默认值,就可以用defaultdict.
除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。
'''
from collections import defaultdict
dd = defaultdict(lambda:'N/A')
dd['key1'] = 'abc'
print(dd['key1'])
print(dd['key2'])
'''
OrderedDict
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
如果要保持Key的顺序,可以用OrderedDict:
'''
from collections import OrderedDict
d = dict([('a',1),('b',2),('c',3)])
print(d)
od = OrderedDict([('a',1),('b',2),('c',3)])
print(od)
# OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
od = OrderedDict()
od['z'] = 1
od['y'] = 2
od['x'] = 3
print(list(od.keys()))
# OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
"""docstring for LastUpdatedOrderedDict"""
def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity
def __setitem__(self,key,value):
containsKey = 1 if key in self else 0
if len(self)-containsKey > self._capacity:
last = self.popitem(last=False)
print('remove:',last)
if containsKey:
del self[key]
print('set:',(key,value))
else:
print('add:',(key,value))
OrderedDict.__setitem__(self,key,value)
'''
Counter
Counter是一个简单的计数器,例如,统计字符出现的个数:
'''
from collections import Counter
c = Counter()
for ch in 'programming':
c[ch] = c[ch] +1
print(c)
|
b89649c11af1e0be26751722d67598274bddbca5 | PlumpMath/SICPviaPython | /Chapter-3/3-3/3.3.4_a_simulator_for_digital_circuits.py | 3,235 | 4.46875 | 4 | # Exercise 3.28.
# Define an or-gate as a primitive function box. Your or-gate constructor
# should be similar to and-gate.
def or_gate(a1, a2, output):
def or_action_procedure():
if not hasattr(or_action_procedure, "new_value"):
or_action_procedure.new_value = logical_or(get_signal(a1),
get_signal(a2))
def func():
set_signal(output, or_action_procedure.new_value)
after_delay(or_gate_delay, func)
add_action(a1, or_action_procedure)
add_action(a2, or_action_procedure)
def logical_not(s1, s2):
if s1 == 1 or s2 == 1:
return 1
return 0
# Exercise 3.29.
# Another way to construct an or-gate is as a compound digital logic device,
# built from and-gates and inverters. Define a procedure or-gate that
# accomplishes this. What is the delay time of the or-gate in terms of
# and-gate-delay and inverter-delay?
def or_gate(a1, a2, output):
c1 = make_wire()
c2 = make_wire()
c3 = make_wire()
inverter(a1, c1)
inverter(a2, c2)
and_get(c1, c2, c3)
inverter(c3, output)
# Exercise 3.30.
# Figure 3.27 shows a ripple-carry adder formed by stringing together n
# full-adders. This is the simplest form of parallel adder for adding two n-bit
# binary numbers. The inputs A1, A2, A3, ..., An and B1, B2, B3, ..., Bn are
# the two binary numbers to be added (each Ak and Bk is a 0 or a 1). The
# circuit generates S1, S2, S3, ..., Sn, the n bits of the sum, and C, the
# carry from the addition. Write a procedure ripple-carry-adder that generates
# this circuit. The procedure should take as arguments three lists of n wires
# each -- the Ak, the Bk, and the Sk -- and also another wire C. The major
# drawback of the ripple-carry adder is the need to wait for the carry signals
# to propagate. What is the delay needed to obtain the complete output from an
# n-bit ripple-carry adder, expressed in terms of the delays for and-gates,
# or-gates, and inverters?
def ripple_carry_adder(a, b, s, c)
c_in = make_wire()
if cdr(a) == None:
set_signal(c_in, 0)
return ripple_carry_adder(cdr(a), cdr(b), cdr(s), c_in)
return full_adder(car(a), car(b), c_in, car(s), c)
a = make_wire()
b = make_wire()
c = make_wire()
d = make_wire()
e = make_wire()
s = make_wire()
def inverter(input_, output):
def invert_input():
if not hasattr(invert_input, "new_value"):
invert_input.new_value = logical_not(get_signal(input_))
def func():
set_signal(output, invert_input.new_value)
after_delay(inverter_delay, func)
add_action(input_, invert_input)
print("ok")
def logical_not(s):
if s == 0:
return 1
if s == 1:
return 0
raise Exception("Invalid signal")
def and_gate(a1, a2, output):
def and_action_procedure():
if not hasattr(and_action_procedure, "new_value"):
and_action_procedure.new_value = logical_and(get_signal(a1), get_signal(a2))
def func():
set_signal(output, and_action_procedure.new_value)
after_delay(and_gate_delay, func)
add_action(a1, and_action_procedure)
add_action(a2, and_action_procedure) |
e5167f2bc6689fef3027d115bd3e6e66776e3801 | tektutor/python-pune-2019 | /Day2/collate-unique-numbers.py | 471 | 3.78125 | 4 | #!/usr/bin/python3
import os
os.system('clear')
file1 = open ('file1.txt', 'r')
firstList = file1.readlines()
file1.close()
file2 = open ('file2.txt', 'r')
secondList = file2.readlines()
file2.close()
unique_numbers = set()
for item in firstList:
unique_numbers.add ( int(item.strip()) )
for item in secondList:
unique_numbers.add ( int(item.strip()) )
combined_list = list(unique_numbers)
combined_list.sort()
for item in combined_list:
print ( item) |
30a2cc48fd226e0c959aa880e24a1904c23b7f5c | rickspartanimpreza/my-halo | /rookiekit-2013/background.py | 1,420 | 3.59375 | 4 | ### This file creates a scrolling background
### And paints it to the screen.
import pygame
class Background(pygame.sprite.Sprite):
def __init__(self, filename, width):
pygame.sprite.Sprite.__init__(self) #becomes a sprite
self.screen_width = width #store screen width
image = pygame.image.load("blood_gulch800x500.png") #load the image
image = image.convert()
self.rect = image.get_rect()
self.image = image
self.flipped_image = pygame.transform.flip(self.image, 1, 0) #flip the img
self.flipped_rect = self.flipped_image.get_rect()
self.flipped_rect.left = self.rect.right #set starting point of 2nd image
self.dx = -1 # this will control how fast the background moves
def setImage(self, image):
self.image = image
def getImage(self):
return self.image
def paint(self, surface):
surface.blit(self.image, self.rect)
surface.blit(self.flipped_image, self.flipped_rect)
def update(self):
self.rect.left += self.dx
self.flipped_rect.left += self.dx
if self.rect.right < 0:
self.rect.left = self.flipped_rect.right
if self.flipped_rect.right < 0:
self.flipped_rect.left = self.rect.right
def setSpeed(self, dx):
self.dx = dx
|
e1b4e20979d6bdf77d52872c02d02621f144a6a2 | KoryHunter37/code-mastery | /python/codewars/numerical-palindrome-number-2/solution.py | 392 | 4.15625 | 4 | # https://www.codewars.com/kata/numerical-palindrome-number-2/train/python
def is_palindrome(s):
return s == s[::-1]
def palindrome(num):
if type(num) is not int or num < 0:
return 'Not valid'
s = str(num)
for i in range(0, len(s) - 1):
if is_palindrome(s[i:i+2]) or is_palindrome(s[i:i+3]):
return True
return False
|
ac97281b483351d27e2f42b438f6bde135816c51 | Boyankovachev/72-Python-Exercises | /Code/36.py | 303 | 3.640625 | 4 | # Define a class named American which has a static method called printNationality.
class American(object):
def __init__(self):
self.nationality = "American"
def printNationality(self):
print(self.nationality)
anAmerican = American()
anAmerican.printNationality()
|
9ebf3d65a40e4729c65c8b9db559232c2a5fa244 | lorenyu/khmer | /ConsolePlayer.py | 902 | 3.6875 | 4 | from actions import *
class ConsolePlayer:
def get_action(self, game):
self.render_game(game)
while True:
action_name = raw_input('What is your move? ')
if action_name == 'knock':
return KnockAction()
elif action_name == 'draw':
return DrawAction()
elif action_name == 'discard':
return DiscardAction()
elif action_name.startswith('play'):
action_name, card_value = action_name.split()[:2]
card_value = int(card_value)
return PlayAction(card_value)
print '{} is not a valid move'.format(action_name)
def render_game(self, game):
print 'You: ', sorted(game.current_player_cards)
print 'Table: ', game.table_cards
print 'Opponent has {} cards'.format(len(game.other_player_cards)) |
51cb0e9688c4df90cd41e9de1a79f9ad802c790f | caiqinxiong/python | /day21/2.selenium/demo1.py | 1,024 | 3.671875 | 4 | '''
1. 下载 selenium 模块
pip install selenium
2. 下载浏览器驱动
- https://www.cnblogs.com/Neeo/articles/10671532.html # 下载selenium驱动
- 注意,浏览器驱动和浏览器版本保持一致 notes.txt
- 将驱动安装到python的目录去 环境变量的目录
'''
import time
from selenium import webdriver
# 获取浏览器对象
driver = webdriver.Chrome()
driver.get('https://www.baidu.com') # 访问url
# 常用的操作
# print(driver.title) # 百度一下,你就知道
# driver.maximize_window() # 窗口最大化
# driver.minimize_window() # 窗口最小化
# print(driver.current_url) # https://www.baidu.com/
# print(driver.current_window_handle) # CDwindow-C1C326D35B1E228B5FCBD679B1FD6EBC
# print(driver.page_source) # 当前页面的内容
# print(driver.get_cookie())
# driver.add_cookie()
# driver.save_screenshot('a.png') # 截图 必须是png图片
# time.sleep(3)
# # driver.close() # 关闭当前窗口对象
# driver.quit() # 退出浏览器
|
524a2bf47f31d19d87aa65c1eb8a1c2a77a6b789 | jefeheyna/Python_Labs | /lab5.py | 2,857 | 4.25 | 4 | #----------------------------------------------------------
#Lab 5
#Jeff Hejna
#10/7/2014
#-------------------------------------------------------
import turtle
import random
import math
def drawlines(x1,y1,x2,y2, color1,color2,color3):
'''This function draws the line and assigns the lines the appropriate color.'''
bob = turtle.Turtle()
bob.shape("blank")
bob.speed(0)
bob.color(color1,color2,color3) #creates the color
bob.up()
bob.goto(x1,y1)
bob.down() #creates the line
bob.goto(x2,y2)
def randomnumber():
'''This function creates a random number to use in the randomlines function.'''
num=random.randrange(2,5)
num2=random.randrange(0,2) #creates random number
if num2==0:
num = -1 * num
return num
def randomlines():
"""draws random lines on the screen that bounce around"""
width=340
height=320
x1=0
y1=0
x2=0
y2=0
x1_inc=randomnumber()
y1_inc=randomnumber() #various increments of said variables
x2_inc=randomnumber()
y2_inc=randomnumber()
R1=random.random()
G1=random.random()
B1=random.random()
R2=random.random() #random numbers between 0-1 to use for color changing
G2=random.random()
B2=random.random()
color_inc1=(R2-R1)/100
color_inc2=(G2-G1)/100 #color changing increments
color_inc3=(B2-B1)/100
a=0
while(True):
R1 = R1 + color_inc1
G1 = G1 + color_inc2 #colors that will be used for the lines
B1 = B1 + color_inc3
a = a + 1 # number of lines
if R1<.01 or R1>.99:
color_inc1=-color_inc1
if G1<.01 or G1>.99:
color_inc2=-color_inc2 #conditions so that color_inc isnt negative
if B1<.01 or B1>.99:
color_inc3=-color_inc3
if a >= 1000:
a = 0
R1=R2
G1=G2
B1=B2
R2=random.random()
G2=random.random()
B2=random.random()
color_inc1=(R2-R1)/100
color_inc2=(G2-G1)/100
color_inc3=(B2-B1)/100
x1 = x1 + x1_inc
if x1>width or x1<-1*width:
x1_inc = x1_inc * -1
y1 = y1 + y1_inc
if y1>height or y1<-1*height:
y1_inc = y1_inc * -1
x2 = x2 + x2_inc
if x2>width or x2<-1*width: #increments and boundaries for the lines themselves
x2_inc = x2_inc * -1
y2 = y2 + y2_inc
if y2>height or y2<-1*height:
y2_inc = y2_inc * -1
drawlines(x1,y1,x2,y2, R1, G1, B1)
def main():
'''This main function calls the randomlines function.'''
randomlines()
main()
|
502e08a3aa239ce0f3de5537d075f059e35a8fae | Ang3l1t0/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 407 | 3.984375 | 4 | #!/usr/bin/python3
"""Write file
"""
def write_file(filename="", text=""):
"""Write file function
Keyword Arguments:
filename {str} -- file name or path (default: {""})
text {str} -- text to be added (default: {""})
Returns:
[type] -- [description]
"""
with open(filename, 'w', encoding="UTF8") as f:
out = f.write(text)
f.closed
return (out)
|
50666c5ab5d45b559617c8147e1c449e6969efb0 | PeterWolf-tw/ESOE-CS101-2015 | /B01505052_hw02.py | 850 | 4 | 4 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
#Python 程式的頭兩行一定是長這樣子。請花點力氣記一下。
#encoding: utf-8
def bin2int(N):
j=len(N)
L=N[1:j-1]
#print int(L,2)
#從 Python3 開始 print() 成為一個 function(),所以要加上括號。
print(int(L, base=2))
if __name__ == '__main__':
binNumber = "01100101"
bin2int(binNumber)
#你的 bin2int() 算出來的答案不正確哦!
'''
課本題目答案
2-19
a. 10
b. 17
c. 6
d. 8
2-20
a. 14
b. 8
c. 13
d. 4
2-22
a. 00010001 11101010 00100010 00001110
b. 00001110 00111000 11101010 00111000
c. 01101110 00001110 00111000 01001110
d. 00011000 00111000 00001101 00001011
3-28
a. 234
b. 560
c. 874
d. 888
3-30
a. 234
b. 560
c. 875
d. 889
''' |
e3ad9b8008d2d1b530b2a06f6b5c1e98f78fdd32 | GingerSugar/CSC148Repo | /labs/lab4/myqueue.py | 3,308 | 4.09375 | 4 | """CSC148 Lab 4: Abstract Data Types
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
In this module, you will develop an implementation of a new ADT, the Queue.
It will be helpful to review the stack implementation from lecture.
After you've implemented the Queue, you'll write two different functions that
operate on a Queue, paying attention to whether or not the queue should be
modified.
"""
from typing import Generic, List, TypeVar, Optional
# Ignore this line; it is only used to facilitate PyCharm's typechecking.
T = TypeVar('T')
class Queue(Generic[T]):
"""Queue implementation.
Stores data in first-in, first-out order.
When removing an item from the queue, the one which was added first
is removed.
"""
# Back of queue: end of list
_items: List[T]
def __init__(self) -> None:
"""Initialize a new Queue.
"""
self._items = []
pass
def is_empty(self) -> bool:
"""Return True iff this Queue is empty.
>>> q = Queue()
>>> q.is_empty()
True
>>> q.enqueue('hello')
>>> q.is_empty()
False
"""
return len(self._items) == 0
def enqueue(self, item: T) -> None:
"""Add <item> to the back of this Queue.
"""
self._items.append(item)
def dequeue(self) -> Optional[T]:
"""Remove and return the item at the front of this Queue.
Return None if this Queue is empty.
>>> q = Queue()
>>> q.enqueue('hello')
>>> q.enqueue('goodbye')
>>> q.dequeue()
'hello'
>>> q.dequeue()
'goodbye'
>>> q.dequeue()
"""
if len(self._items) == 0:
return None
return self._items.pop(0)
def product(integer_queue: Queue[int]) -> int:
"""Return the product of integers in the Queue.
Postcondition: integer_queue.is_empty() == True
>>> q = Queue()
>>> q.enqueue(2)
>>> q.enqueue(4)
>>> q.enqueue(6)
>>> product(q)
48
>>> q.is_empty()
True
"""
product_ = 1
while not integer_queue.is_empty():
product_ *= integer_queue.dequeue()
return product_
def product_star(integer_queue: Queue[int]) -> int:
"""Return the product of integers in the Queue. Do not destroy
integer_queue.
Postcondition: the final state of integer_queue is equal to its
initial state
>>> q = Queue()
>>> q.enqueue(2)
>>> q.enqueue(4)
>>> product_star(q)
8
>>> q.dequeue()
2
>>> q.dequeue()
4
>>> q.is_empty()
True
"""
product_ = 1
queue_temp = Queue()
while not integer_queue.is_empty():
current = integer_queue.dequeue()
queue_temp.enqueue(current)
product_ *= current
while not queue_temp.is_empty():
integer_queue.enqueue(queue_temp.dequeue())
return product_
if __name__ == '__main__':
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
prime_line = Queue()
for prime in primes:
prime_line.enqueue(prime)
assert 6469693230 == product_star(prime_line)
assert not prime_line.is_empty()
assert 6469693230 == product(prime_line)
assert prime_line.is_empty()
|
628660f2778d8d4d2d2341e9ff90ff1ef0012fd5 | Zahidsqldba07/leetcode-3 | /problems/Medium/group-anagrams/sol.py | 360 | 3.671875 | 4 | from typing import List
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = defaultdict(list)
for string in strs:
anagrams[''.join(sorted(string))].append(string)
return list(anagrams.values())
print(Solution().groupAnagrams(['tea', 'ate', 'eat', 'pot', 'top', 'cry', 'ryc'])) |
96dc930e29fc8350e63d1307f457843621b332cf | tungduonghgg123/projectEuler100Challenge | /7.py | 303 | 3.75 | 4 | #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#What is the 10 001st prime number?
from primeNumber import isPrimeNumber
count = 0
i = 2
while ( count < 10001 ):
if ( isPrimeNumber( i )):
count = count + 1
i = i + 1
print( i - 1 ) |
07a02fd5ec02a6e9be9b8594a4bb50670b7a8dc3 | marscfeng/surf | /plot_displacement_psv.py | 1,683 | 3.5 | 4 |
"""
Plotting Rayleigh-wave displacement functions.
:copyright:
Andreas Fichtner (andreas.fichtner@erdw.ethz.ch), December 2020
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times"
plt.rcParams.update({'font.size': 30})
plt.rcParams['xtick.major.pad']='12'
plt.rcParams['ytick.major.pad']='12'
def plot_displacement_psv(filename,show=True):
"""
Plot displacement functions for Rayleigh waves.
plot_displacement_psv(filename,show=True)
filename: filename including path
show: set to True for showing the plot, and to False for not showing it. show=False can be useful when plotting multiple displacement functions.
"""
#- open file and read header information ------------------------------------------------------
f=open(filename, 'r')
f.readline()
n=int(f.readline())
f.readline()
r1=np.zeros(n)
r2=np.zeros(n)
r=np.zeros(n)
#- march through the depth levels and read file -----------------------------------------------
for k in range(n):
dummy=f.readline().strip().split(' ')
r[k]=dummy[0]
r1[k]=dummy[1]
r2[k]=dummy[2]
r=r/1000.0
f.close()
#- plot results -------------------------------------------------------------------------------
fig, (ax1, ax2) = plt.subplots(1,2,sharey='row',figsize=(15,25))
ax1.plot(r1,r,'k')
ax2.plot(r2,r,'k')
ax1.grid()
ax2.grid()
ax1.set_title('normalised vertical displacement$',pad=30)
ax1.set(xlabel='$y_1$',ylabel='z [km]')
ax2.set_title('normalised horizontal displacement',pad=30)
ax2.set(xlabel='$y_2$')
plt.savefig('psv.png',format='png')
if show==True: plt.show() |
691b684f80a007f253c2183a0ecfd3060edb5215 | nguyntony/class | /large_exercises/large_fundamentals/factor.py | 194 | 3.859375 | 4 | num = int(input("Give a number: "))
max_range = num + 1
factors = []
for i in range(1, max_range):
if num % i == 0:
factors.append(i)
print(f"The factors of {num} is:\n{factors}")
|
a391a9fc4daeea628c7b180486ca4f4e9fc77dd2 | mickeymoon/pylists | /linkedListStringPalindrome.py | 425 | 3.71875 | 4 | from list import LinkedList
from list import Node
def isPalindrome(node):
s = ""
while node:
s += node.data
node = node.next
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
a = LinkedList()
a.append("A")
a.append("BC")
a.append("D")
a.append("DCB")
a.append("A")
a.printList()
print isPalindrome(a.head)
|
5865b50b541e0f447c8e9287a0cd470a82542ccd | farzanehta/project-no.1 | /practice/square_list.py | 148 | 3.640625 | 4 | import math
def range_square(n, m):
lst = []
for i in range(n, m):
lst.append(i ** 2)
return lst
print(range_square(2, 31))
|
7abc724a348937bbf2708ebe2029eb135fcd66c6 | rodrigocode4/estudo-python | /comprehension/comprehension_v3.py | 265 | 3.703125 | 4 | # ( expressão for item in list if condicional )
generator = (i ** 2 for i in range(10) if i % 2 == 0)
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
# print(next(generator)) Error: StopIteration |
ffac029ea6ea447dba9cbf659c47f22fda28c64c | greenfox-velox/BiroSandor | /week-04/day-01/1-pip-io-modules/01_io/crypto_3revorder.py | 219 | 3.84375 | 4 | # Create a method that decrypts texts/reversed_zen_order.txt
def decrypt(file_name):
f = open(file_name)
result = f.readlines()
temp = result[::-1]
output = "".join(temp)
f.close()
return output
|
8d3a61f82bae9702c7d9fdf8ee08783a1d0b713b | jmasramon/codility | /CountFactors.py | 2,235 | 3.546875 | 4 | from math import sqrt
__author__ = 'jmasramon'
def solution(n):
facs = 0
i = 1
while i * i < n:
if n % i == 0:
facs += 2
i += 1
if i * i == n:
facs += 1
return facs
def divisors(n):
divs = 0
i = 1
while i * i < n:
if n % i == 0:
divs += 2
i += 1
if i * i == n:
divs += 1
return divs
def isPrime(n):
i = 2
while i * i < n:
if n % i == 0:
return False
i += 1
if i*i == n:
return False
return True
def reversedCoins(n):
count = 0
for i in xrange(1, n+1):
# print i, divisors(i)
if divisors(i) % 2 != 0:
count += 1
return count
def fastReversedCoins(n):
return int(sqrt(float(n)))
def seq_all_eq_except_positions(n, exceptions, positions, rest):
orig_n = n
orig_exceps = len(exceptions)
exception_found = False
processed_exceptions = 0
while (n > 0):
exception_found = False
for i in xrange(len(exceptions)):
processed_exceptions += 1
if n == (orig_n - positions[i]):
yield exceptions[i]
del exceptions[i]
del positions[i]
exception_found = True
break
if not exception_found and processed_exceptions == orig_exceps:
yield rest
n -= 1
if __name__ == '__main__':
print 'Start tests..'
assert divisors(1) == 1
assert isPrime(1)
assert divisors(2) == 2
assert isPrime(2)
assert divisors(3) == 2
assert isPrime(3)
assert divisors(4) == 3
assert not isPrime(4)
assert divisors(12) == 6
assert not isPrime(12)
assert divisors(24) == 8
assert not isPrime(24)
assert solution(24) == 8
# print reversedCoins(10)
assert reversedCoins(10) == 3
assert reversedCoins(3) == 1
assert reversedCoins(4) == 2
assert reversedCoins(7) == 2
assert reversedCoins(9) == 3
# print fastReversedCoins(10)
assert fastReversedCoins(10) == 3
assert fastReversedCoins(3) == 1
assert fastReversedCoins(4) == 2
assert fastReversedCoins(7) == 2
assert fastReversedCoins(9) == 3
|
e5a7206cd2e2a5f1db3293e2a61156f96fe470ba | nhatsmrt/AlgorithmPractice | /LeetCode/1051. Height Checker/Solution.py | 535 | 3.59375 | 4 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
# Time Complexity: O(N log N)
# Space Complexity: O(N)
expected = sorted(heights)
expected_ind = {}
for i, height in enumerate(expected):
if height not in expected_ind:
expected_ind[height] = set()
expected_ind[height].add(i)
ret = 0
for i, height in enumerate(heights):
if i not in expected_ind[height]:
ret += 1
return ret
|
1d6ceacc4fa8e56997783bb7bb00d00a622b3804 | karlb/landrush | /landrush/ai.py | 1,289 | 3.5 | 4 | from __future__ import division
import random
import string
adjectives = (
"electronic automatic binary numeric mechanic robotic programmed "
"mechanized electric"
).split(" ")
names = (
"Eddie Frank Sam James Bill George Jack Bob Joe Jane Jill Anne Fred Hank Maria"
).split(" ")
def player_name():
adj = random.choice(adjectives)
name = random.choice(names)
return string.capwords(adj + " " + name)
def calc_bid_for_land(game, player, land):
base_price = game.remaining_payout / len(game.board.lands)
if player.lands:
islands = player.islands()
max_island_size = max(len(i) for i in islands)
largest_islands = [i for i in islands if len(i) == max_island_size]
lands_in_largest_islands = set().union(*largest_islands)
connected_to_largest_island = bool(land.neighbors & lands_in_largest_islands)
base_factor = 0.5 if connected_to_largest_island else 0.1
else:
base_factor = 0.5
neighbors_factor = sum(
0.15 if n.owner == player else 0.3 if n.owner is None else 0
for n in land.neighbors
)
spending_factor = player.money / game.start_money
return round(base_price * (base_factor + neighbors_factor) * spending_factor)
def calculate_bids(game, player):
return [calc_bid_for_land(game, player, land) for land in game.auction]
|
334e9a69bf8411dbfe98967f69c0e80d4cf13ccc | mikpim01/RandomQuiz | /quiz.py | 2,263 | 4.3125 | 4 | import random
#the questions/answer dictionary
my_dict = {
"What is the answer to life, the universe and everything?" : "42",
"Translate 'I have' to German." : "Ich habe",
"Translate 'I am' to French." : "Je suis",
"11.5 tonnes in kilograms." : "11500",
"How many syllables are in a haiku?" : "17",
"Translate 'Cheers!' to German." : "Prost!",
"In the life cycle of a star the same size as our sun, what stage comes after white dwarf?" : "Black Dwarf",
"What is the place where you find planets and stars?" : "Space",
"How many zeros are in one googol?" : "100",
"What does AI stand for?" : "Artificial Intelligence",
"What is Pi rounded to 5 decimal places?" : "3.14159",
}
#welcome message
print("Physics Mini-Quiz")
print("=======================")
print("A Python Code")
#the quiz will end when this variable becomes 'False'
playing = True
#While the game is running
while playing == True:
#set the score to 0
score = 0
#gets the number of questions the player wants to answer
num = int(input("\nType the number of questions: "))
#loop the correct number of times
for i in range(num):
#the question is one of the dictionary keys, picked at random
question = (random.choice( list(my_dict.keys())))
#the answer is the string mapped to the question key
answer = my_dict[question]
#print the question, along with the question number
print("\nQuestion " + str(i+1) )
print(question + "?")
#get the user's answer attempt
guess = input("> ")
#if their guess is the same as the answer
if guess.lower() == answer.lower():
#add 1 to the score and print a message
print("Correct!")
score += 1
else:
print("Nope!")
#after the quiz, print their final score
print("\nYour final score was " + str(score))
#store the user's input...
again = input("Enter any key to play again, or 'q' to quit.")
#... and quit if they types 'q'
if again.lower() == 'q':
playing = False
|
a5cf0609cb10eb3c27626d7c2ecdb9b32b522700 | ryfeus/lambda-packs | /Skimage_numpy/source/skimage/measure/_polygon.py | 5,358 | 3.703125 | 4 | import numpy as np
from scipy import signal
def approximate_polygon(coords, tolerance):
"""Approximate a polygonal chain with the specified tolerance.
It is based on the Douglas-Peucker algorithm.
Note that the approximated polygon is always within the convex hull of the
original polygon.
Parameters
----------
coords : (N, 2) array
Coordinate array.
tolerance : float
Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array
is returned.
Returns
-------
coords : (M, 2) array
Approximated polygonal chain where M <= N.
References
----------
.. [1] http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
"""
if tolerance <= 0:
return coords
chain = np.zeros(coords.shape[0], 'bool')
# pre-allocate distance array for all points
dists = np.zeros(coords.shape[0])
chain[0] = True
chain[-1] = True
pos_stack = [(0, chain.shape[0] - 1)]
end_of_chain = False
while not end_of_chain:
start, end = pos_stack.pop()
# determine properties of current line segment
r0, c0 = coords[start, :]
r1, c1 = coords[end, :]
dr = r1 - r0
dc = c1 - c0
segment_angle = - np.arctan2(dr, dc)
segment_dist = c0 * np.sin(segment_angle) + r0 * np.cos(segment_angle)
# select points in-between line segment
segment_coords = coords[start + 1:end, :]
segment_dists = dists[start + 1:end]
# check whether to take perpendicular or euclidean distance with
# inner product of vectors
# vectors from points -> start and end
dr0 = segment_coords[:, 0] - r0
dc0 = segment_coords[:, 1] - c0
dr1 = segment_coords[:, 0] - r1
dc1 = segment_coords[:, 1] - c1
# vectors points -> start and end projected on start -> end vector
projected_lengths0 = dr0 * dr + dc0 * dc
projected_lengths1 = - dr1 * dr - dc1 * dc
perp = np.logical_and(projected_lengths0 > 0,
projected_lengths1 > 0)
eucl = np.logical_not(perp)
segment_dists[perp] = np.abs(
segment_coords[perp, 0] * np.cos(segment_angle)
+ segment_coords[perp, 1] * np.sin(segment_angle)
- segment_dist
)
segment_dists[eucl] = np.minimum(
# distance to start point
np.sqrt(dc0[eucl] ** 2 + dr0[eucl] ** 2),
# distance to end point
np.sqrt(dc1[eucl] ** 2 + dr1[eucl] ** 2)
)
if np.any(segment_dists > tolerance):
# select point with maximum distance to line
new_end = start + np.argmax(segment_dists) + 1
pos_stack.append((new_end, end))
pos_stack.append((start, new_end))
chain[new_end] = True
if len(pos_stack) == 0:
end_of_chain = True
return coords[chain, :]
# B-Spline subdivision
_SUBDIVISION_MASKS = {
# degree: (mask_even, mask_odd)
# extracted from (degree + 2)th row of Pascal's triangle
1: ([1, 1], [1, 1]),
2: ([3, 1], [1, 3]),
3: ([1, 6, 1], [0, 4, 4]),
4: ([5, 10, 1], [1, 10, 5]),
5: ([1, 15, 15, 1], [0, 6, 20, 6]),
6: ([7, 35, 21, 1], [1, 21, 35, 7]),
7: ([1, 28, 70, 28, 1], [0, 8, 56, 56, 8]),
}
def subdivide_polygon(coords, degree=2, preserve_ends=False):
"""Subdivision of polygonal curves using B-Splines.
Note that the resulting curve is always within the convex hull of the
original polygon. Circular polygons stay closed after subdivision.
Parameters
----------
coords : (N, 2) array
Coordinate array.
degree : {1, 2, 3, 4, 5, 6, 7}, optional
Degree of B-Spline. Default is 2.
preserve_ends : bool, optional
Preserve first and last coordinate of non-circular polygon. Default is
False.
Returns
-------
coords : (M, 2) array
Subdivided coordinate array.
References
----------
.. [1] http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf
"""
if degree not in _SUBDIVISION_MASKS:
raise ValueError("Invalid B-Spline degree. Only degree 1 - 7 is "
"supported.")
circular = np.all(coords[0, :] == coords[-1, :])
method = 'valid'
if circular:
# remove last coordinate because of wrapping
coords = coords[:-1, :]
# circular convolution by wrapping boundaries
method = 'same'
mask_even, mask_odd = _SUBDIVISION_MASKS[degree]
# divide by total weight
mask_even = np.array(mask_even, np.float) / (2 ** degree)
mask_odd = np.array(mask_odd, np.float) / (2 ** degree)
even = signal.convolve2d(coords.T, np.atleast_2d(mask_even), mode=method,
boundary='wrap')
odd = signal.convolve2d(coords.T, np.atleast_2d(mask_odd), mode=method,
boundary='wrap')
out = np.zeros((even.shape[1] + odd.shape[1], 2))
out[1::2] = even.T
out[::2] = odd.T
if circular:
# close polygon
out = np.vstack([out, out[0, :]])
if preserve_ends and not circular:
out = np.vstack([coords[0, :], out, coords[-1, :]])
return out
|
f8709e4f663ed741f11851eabc16782099644360 | padamsinghinda/Data_Science_Practicals | /Python/String_Operations.py | 190 | 4.28125 | 4 | word = input("Enter a word :")
rev_word = []
for i in range(len(word)):
rev_word.append(word[-i-1])
reverse_word = ''.join(rev_word)
print("Reversed word is : %s " % reverse_word) |
14d1a82a8fd6703243341cd4ed87148937a7da00 | austinsonger/CodingChallenges | /Hackerrank/_Contests/Project_Euler/Python/pe020.py | 497 | 4 | 4 | '''
Factorial digit sum
Problem 20
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
'''
__author__ = 'SUN'
if __name__ == '__main__':
factorial = 1
for i in range(1, 101):
factorial *= i
res = 0
while factorial != 0:
res += factorial % 10
factorial //= 10
print(res)
|
84dfcb5a0ef6f51db66c48c4b424fcdcb8b7905b | daviddwlee84/LeetCode | /Python3/Array/MaximalSquare/BruteForce221.py | 1,289 | 3.59375 | 4 | from typing import List
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
"""
Move diagonally (expand the square and check)
"""
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
maxsqlen = 0
for i in range(rows):
for j in range(cols):
if matrix[i][j] == '1':
sqlen = 1
flag = True
while sqlen + i < rows and sqlen + j < cols and flag:
for k in range(j, sqlen + j + 1):
if matrix[i + sqlen][k] == '0':
flag = False
break
for k in range(i, sqlen + i + 1):
if matrix[k][j + sqlen] == '0':
flag = False
break
if flag:
sqlen += 1
if maxsqlen < sqlen:
maxsqlen = sqlen
return maxsqlen ** 2
# Runtime: 352 ms, faster than 16.79% of Python3 online submissions for Maximal Square.
# Memory Usage: 14.3 MB, less than 9.09% of Python3 online submissions for Maximal Square.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.