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 |
|---|---|---|---|---|---|---|
a3f91f812104d60fc2662ce07ba69716345ecabe | VZRXS/LeetCode-noob-solutions | /Medium/151_Reverse_Words_in_a_String.py | 1,565 | 4.03125 | 4 | #!/usr/bin/env python3
class Solution(object):
# 151. Reverse Words in a String
def reverseWords(self, s: str) -> str:
reversed_words = ''
word_ind = []
if s[0] != 0 and s[0] != ' ':
start = 0
for i in range(1, len(s)):
if s[i] != s[i - 1] and s[i - 1] == ' ':
start = i
elif s[i] != s[i - 1] and s[i] == ' ':
end = i
word_ind.append([start, end])
elif i == len(s) - 2 and s[i] != ' ':
end = i
word_ind.append([start, end])
if i == len(s) - 1 and s[i] != ' ':
end = i
word_ind.append([start, end])
for i in range(len(word_ind) - 1, -1, -1):
reversed_words += s[word_ind[i][0]:word_ind[i][1]] + ' '
return reversed_words[:-1:]
def reverseWords_attemp2(self, s: str) -> str:
reversed_words = ''
if s[-1] != 0 and s[-1] != ' ':
end = len(s)
for i in range(len(s) - 1, -1, -1):
if s[i] != s[i - 1] and s[i] == ' ':
end = i
elif s[i] != s[i - 1] and s[i - 1] == ' ':
start = i
reversed_words += ' ' + s[start:end]
if i == 0 and end > 0 and s[i - 1] != ' ':
start = 0
reversed_words += ' ' + s[start:end]
return reversed_words[1::]
if __name__ == '__main__':
print(Solution().reverseWords(s=" a good example "))
print(Solution().reverseWords_attemp2(s=" fffff ff gg ee"))
|
2a6daa5ae0f7bb9581eb9410a598d38fd91ec850 | andrasfeher/Python | /03_tuples/main.py | 665 | 4.46875 | 4 | # one element
one_marx = 'Groucho',
print(one_marx)
marx_tuple = 'Groucho', 'Chico', 'Harpo'
print(marx_tuple)
# parenthesis is not mandatory, you can use it to make tuple more visible
marx_tuple = ('Groucho', 'Chico', 'Harpo')
print(marx_tuple)
# tuples let you assign multiple variables at once
# tuple unpacking
marx_tuple = ('Groucho', 'Chico', 'Harpo')
a, b, c = marx_tuple
print(a)
print(b)
print(c)
# you can use tuples to exchange values in one statement without
# using a temporary variable
a = 1
b = 2
a, b = b, a
print(a)
print(b)
# tuple() conversion makes tuples from other things
marx_list = ['Groucho', 'Chico', 'Harpo']
print(tuple(marx_list))
|
74fdb1fbd1f7367e1916b180c384b3427c563949 | MilindRastogi/DSA-Solution | /Recursion/Day1/product_sum.py | 249 | 3.625 | 4 | def Product_Sum(arr, depth=1):
sum = 0
for i in arr:
if isinstance(i, list):
sum = sum + Product_Sum(i, depth+1)
else:
sum = sum + i
return sum*depth
arr = [1, 2, [3, 4]]
print(Product_Sum(arr))
|
bedbf748a998367cb11bfa0b9db9e797bb2cac54 | aadiupadhyay/CodeForces | /atcoder/abc153/D.py | 75 | 3.59375 | 4 | n=int(input())
x=1
p=0
while (x<<1)<=n:
x=x<<1
p+=1
print(pow(2,p+1)-1) |
be6d94a97f259f625607a713dcb294faa906f41f | ductandev/Tkinter_GUI_tutorial | /loop_button.py | 341 | 3.5 | 4 | import tkinter as tk
def click(data):
print("clickevent", data)
def other():
app = tk.Tk()
frame = tk.Frame(app)
frame.pack()
buttons = []
for x in range(10):
b = tk.Button(frame, text='Button ' + str(x), command=lambda: click(x))
b.pack()
buttons.append(b)
app.mainloop()
other()
|
a9975d8ed945689279b8df26cab2d165bfe7225b | rjNemo/design-patterns | /creational/prototype/components.py | 2,393 | 4 | 4 | from __future__ import annotations
import copy
from dataclasses import dataclass
from typing import Any, List
class SelfReferencingEntity:
def __init__(self):
self.parent = None
def set_parent(self, parent):
self.parent = parent
@dataclass
class SomeComponent:
"""
Python provides its own interface of Prototype via `copy.copy` and
`copy.deepcopy` functions. And any class that wants to implement custom
implementations have to override `__copy__` and `__deepcopy__` member
functions.
"""
some_int: int
some_list_of_objects: List
some_circular_ref: Any
def __copy__(self) -> SomeComponent:
"""
Create a shallow copy. This method will be called whenever someone
calls `copy.copy` with this object and the returned value is returned
as the new shallow copy.
"""
# First, let's create copies of the nested objects.
some_list_of_objects = copy.copy(self.some_list_of_objects)
some_circular_ref = copy.copy(self.some_circular_ref)
# Then, let's clone the object itself, using the prepared clones of the
# nested objects.
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
new.__dict__.update(self.__dict__)
return new
def __deepcopy__(self, memo={}) -> SomeComponent:
"""
Create a deep copy. This method will be called whenever someone calls
`copy.deepcopy` with this object and the returned value is returned as
the new deep copy.
What is the use of the argument `memo`? Memo is the dictionary that is
used by the `deepcopy` library to prevent infinite recursive copies in
instances of circular references. Pass it to all the `deepcopy` calls
you make in the `__deepcopy__` implementation to prevent infinite
recursions.
"""
# First, let's create copies of the nested objects.
some_list_of_objects = copy.deepcopy(self.some_list_of_objects, memo)
some_circular_ref = copy.deepcopy(self.some_circular_ref, memo)
# Then, let's clone the object itself, using the prepared clones of the
# nested objects.
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
new.__dict__ = copy.deepcopy(self.__dict__, memo)
return new
|
e0897f8939af7b91328895fc01a53e6f1b331a55 | ahujapankaj16/CompetitiveProgramming | /surrounded_regions.py | 2,431 | 4 | 4 | '''
Surrounded Regions
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
'''
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
if m==0:
return
n = len(board[0])
if n==0:
return
queue = collections.deque([])
for i in range(m):
if board[i][0] == "O":
board[i][0] = "1"
queue.append((i-1, 0)); queue.append((i+1, 0))
queue.append((i, 1))
if board[i][n-1] == "O":
board[i][n-1] = "1"
queue.append((i-1, n-1)); queue.append((i+1, n-1))
queue.append((i, n-2))
for i in range(n):
if board[0][i] == "O":
board[0][i] = "1"
queue.append((0, i-1)); queue.append((0, i+1))
queue.append((1, i))
if board[m-1][i] == "O":
board[m-1][i] = "1"
queue.append((m-1, i-1)); queue.append((m-1, i+1))
queue.append((m-2, i));
print(queue)
while queue:
r, c = queue.popleft()
if 0<=r<len(board) and 0<=c<len(board[0]) and board[r][c] == "O":
board[r][c] = "1"
queue.append((r-1, c)); queue.append((r+1, c))
queue.append((r, c-1)); queue.append((r, c+1))
for i in range(m):
for j in range(n):
if board[i][j] == "1":
board[i][j] ="O"
elif board[i][j] == "O":
board[i][j] = "X"
else:
continue
|
ddf748894ac4a04eb73f754393f07d4a75f10ea0 | doityu/Project_Euler | /PE1...50/pe-37.py | 775 | 3.859375 | 4 | import math
# 素数判定関数(総当たり √N)
def isPrime(number):
if(number < 2):
return False
for i in range(2, int(math.sqrt(number)) + 1):
if(number % i == 0):
return False
return True
# 切り詰め可能な数値か
def isTruncatable(num):
s_num = str(num)
for i in range(len(s_num)):
# 左から右に桁を除いた時
l_tmp = int(s_num[i:])
if(not isPrime(l_tmp)):
return False
# 右から左に桁を除いた時
if(i != 0):
r_tmp = int(s_num[:i])
if(not isPrime(r_tmp)):
return False
return True
res = []
for i in range(11, 1000000):
if(isTruncatable(i)):
res.append(i)
print(res)
print(sum(res))
|
a4005ef3326e9dc8144ad7ebc81e068017c68229 | araki2410/Reinforcement | /card_env.py | 2,324 | 3.53125 | 4 | import random
class Card():
def __init__(self):
self.deck = []
self.table = []
self.trash = []
marks = ["h","s","c","d"]
num = 13
for i in marks:
for j in range(num):
self.deck.append([i+str(j+1), j+1])
def random_pick(self):
peace_num = len(self.deck)-1
if peace_num <= 0:
print("deck empty! reset!")
#self.reset()
#peace_num = len(self.deck)-1
return -1
picked = self.deck.pop(random.randrange(peace_num))
self.table.append(picked)
return picked
def clean_table(self):
self.trash.extend(self.table)
self.table = {}
def reset(self):
self.deck.extend(self.table)
self.deck.extend(self.trash)
class Highlow():
def __init__(self, steps=40):
self.cards = Card()
self.steps = steps
self.draw_count = 0
self.top = -1
def draw(self):
self.top = self.cards.random_pick()[1]
def highlow(self, action):
chosen = int(action) % 2 ## 0:low, 1:high
newone = self.cards.random_pick()[1]
draw = 2
if newone < self.top:
hl = 0
elif newone > self.top:
hl = 1
elif newone == self.top:
hl = 2 ## Draw game
self.top = newone
if hl == draw:
reword = 0
elif chosen == hl:
reword = 1 ## Win!
else:
reword = -1 ## Lose..
return self.top, reword
def actions(self):
low = 0
high = 1
return [low, high]
def reset(self):
self.cards.reset()
self.draw_count = 0
self.top = -1
def step(self, action):
step = self.steps - 1
if self.draw_count > step:
raise Exception("The step count exceed maximum. Please reset env")
else:
done = True if self.draw_count==step else False
self.draw_count += 1
state, reword = self.highlow(action)
return state, reword, done
# game = Highlow()
# game.draw()
# for i in range(5):
# #print(game.top, game.highlow(0))
# print(game.top, game.step(0))
# print(game.top)
|
449ff0f7d5f7f80e9e456fbfced7914451f979a5 | LogankumarR/Logankumar | /OOPS/oop3.py | 666 | 4.09375 | 4 | # types of variable in oops
#one is class variable and another one is instance variable
# variable is defined inside class that is instance variable beacuse it will vary according to object
# class variables which we should declare outside of class but it is shared to all other objets
# let see one example
class car():
#class variable
wheels = 10
def __init__(self,type,year):
self.types = type #...> instance variable
self.years = year
def func(self):
print (self.types,self.years)
car1 = car("honda",1995)
car2 = car("skoda",1996)
car1.func()
car2.func()
print (car1.wheels)
print (car2.wheels)
|
7ab779f942f55eca1350435be5f17e903672a57e | alexander-held/advent-of-code-2019 | /09/puzzle.py | 8,549 | 3.765625 | 4 | import copy
opcodes = [1, 2, 3, 4, 99]
# 1: read values at the two following indices, save to third index
# 2: same but multiply
# 3: input saved to following position
# 4: output saved to following position
# 99: stop program
# after processing: move forward 4 positions
def output_stuff(value):
print("output is", value)
def save_input(code, what, where):
code[where] = what
return code
def add(code, input_1, input_2, output_index):
code[output_index] = input_1 + input_2
return code
def multiply(code, input_1, input_2, output_index):
code[output_index] = input_1 * input_2
return code
def position_mode(code, index, relative_base):
res = code[code[index] + relative_base]
#print("pos mode returning", res)
return res
def position_mode_index(code, index, relative_base):
res = code[index] + relative_base
#print("pos index returning", res)
return res
def process_code(code, INPUT):
extension_size = 1000
code = code + [0 for i in range(extension_size)]
i = 0 # position in code, "instruction pointer"
relative_base = 0
while i < len(code):
code_str = str(code[i]).zfill(5)
opcode = int(code_str[-2:])
len_params = len(code_str) - 2
modes = [int(code_str[k]) for k in range(len_params)][::-1]
#print(code)
#print("opcode", opcode, "modes", modes)
#input()
if opcode==99:
print("quitting now")
return output_value
if opcode==5:
# jump if true
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if input_1 != 0:
i = input_2
#print("seting pointer to", i)
continue
else:
i += 3
if opcode==6:
# jump if false
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if input_1 == 0:
i = input_2
#print("seting pointer to", i)
continue
else:
i += 3
if opcode==7:
# less than
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if modes[2] == 0:
output_index = code[i+3]
elif modes[2] == 1:
print("writing location in immediate mode!")
raise SystemExit
elif modes[2] == 2:
output_index = position_mode_index(code, i+3, relative_base)
if input_1 < input_2:
code[output_index] = 1
else:
code[output_index] = 0
i += 4
if opcode==8:
# equal
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if modes[2] == 0:
output_index = code[i+3]
elif modes[2] == 1:
print("writing location in immediate mode!")
raise SystemExit
elif modes[2] == 2:
output_index = position_mode_index(code, i+3, relative_base)
if input_1 == input_2:
code[output_index] = 1
else:
code[output_index] = 0
i += 4
elif opcode==9:
# adjust relative base
if modes[0] == 0:
adjust_value = code[code[i+1]]
elif modes[0] == 1:
adjust_value = code[i+1]
elif modes[0] == 2:
adjust_value = position_mode(code, i+1, relative_base)
relative_base += adjust_value
#print("adjusting base, now base is", relative_base)
i += 2
elif opcode==4:
# output
if modes[0] == 0:
output_value = code[code[i+1]]
elif modes[0] == 1:
output_value = code[i+1]
elif modes[0] == 2:
output_value = position_mode(code, i+1, relative_base)
output_stuff(output_value)
i += 2
elif opcode==3:
# input
if modes[0] == 0:
output_index = code[i+1]
elif modes[0] == 1:
print("writing location in immediate mode!")
raise SystemExit
elif modes[0] == 2:
output_index = position_mode_index(code, i+1, relative_base)
code = save_input(code, INPUT, output_index)
i += 2
elif opcode==1:
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if modes[2] == 0:
output_index = code[i+3]
elif modes[2] == 1:
print("writing location in immediate mode!")
raise SystemExit
elif modes[2] == 2:
output_index = position_mode_index(code, i+3, relative_base)
code = add(code, input_1, input_2, output_index)
i += 4
elif opcode==2:
if modes[0] == 0:
input_1 = code[code[i+1]]
elif modes[0] == 1:
input_1 = code[i+1]
elif modes[0] == 2:
input_1 = position_mode(code, i+1, relative_base)
if modes[1] == 0:
input_2 = code[code[i+2]]
elif modes[1] == 1:
input_2 = code[i+2]
elif modes[1] == 2:
input_2 = position_mode(code, i+2, relative_base)
if modes[2] == 0:
output_index = code[i+3]
elif modes[2] == 1:
print("writing location in immediate mode!")
raise SystemExit
elif modes[2] == 2:
output_index = position_mode_index(code, i+3, relative_base)
code = multiply(code, input_1, input_2, output_index)
i += 4
#else:
# print("stuck at position", i, "with value", code[i])
def get_input(path):
with open(path) as f:
lines = f.readlines()
assert(len(lines)) == 1
code = lines[0].split(",")
code = [int(c) for c in code]
return code
if __name__ == '__main__':
process_code([109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99],0)
assert len(str(process_code([1102,34915192,34915192,7,4,7,99,0], 0))) == 16
assert process_code([104,1125899906842624,99], 0) == 1125899906842624
# part 1
code = get_input("input.txt")
INPUT = 1
process_code(code, INPUT)
# part 2
code = get_input("input.txt")
INPUT = 2
process_code(code, INPUT)
|
7b1afeffdbc644bcb7c052c273ebe9104a37227f | qule/ProgrammingAssignmentOfDeeplearning | /vectorization.py | 2,582 | 3.5 | 4 | import numpy as np
import time
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
tic = time.process_time()
dot = 0
for i in range(len(x1)):
dot += x1[i] * x2[i]
toc = time.process_time()
print (1.1, "dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
### CLASSIC OUTER PRODUCT IMPLEMENTATION ###
tic = time.process_time()
outer = np.zeros((len(x1), len(x2))) # we create a len(x1)*len(x2) matrix with only zeros
for i in range(len(x1)):
for j in range(len(x2)):
outer[i, j] = x1[i] * x2[j]
toc = time.process_time()
print (1.2, "outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
### CLASSIC ELEMENTWISE IMPLEMENTATION ###
tic = time.process_time()
mul = np.zeros(len(x1))
for i in range(len(x1)):
mul[i] = x1[i] * x2[i]
toc = time.process_time()
print (1.3, "elementwise multiplication = " + str(mul) + "\n ----- Computationtime=" + str(1000*(toc-tic)) + "ms")
### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###
W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array tic = time.process_time()
gdot = np.zeros(W.shape[0])
for i in range(W.shape[0]):
for j in range(len(x1)):
gdot[i] += W[i, j]*x1[j]
toc = time.process_time()
print (1.4, "gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
### VECTORIZED DOT PRODUCT OF VECTORS ###
tic = time.process_time()
dot = np.dot(x1, x2)
toc = time.process_time()
print (2.1, "dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
### VECTORIZED OUTER PRODUCT ###
tic = time.process_time()
outer = np.outer(x1, x2)
toc = time.process_time()
print (2.2, "outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
### VECTORIZED ELEMENTWISE MULTIPLICATION ###
tic = time.process_time()
mul = np.multiply(x1, x2)
toc = time.process_time()
print (2.3, "elementwise multiplication = " + str(mul) + "\n -----Computationtime=" + str(1000*(toc-tic)) + "ms")
### VECTORIZED GENERAL DOT PRODUCT ###
tic = time.process_time()
dot = np.dot(W, x1)
toc = time.process_time()
print (2.4, "gdot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc-tic)) + "ms")
def L1(yhat, y):
loss = sum(abs(y - yhat))
return loss
yhat = np.array([.9, 0.2, 0.1, .4, .9])
y = np.array([1, 0, 0, 1, 1])
print(3, "L1 = " + str(L1(yhat,y)))
def L2(yhat, y):
loss = np.dot(y-yhat, y-yhat)
return loss
print(4, "L2 = " + str(L2(yhat, y))) |
dd6f1c0f476c48af78ea0707b40d8d15f00d0e36 | nicolageorge/play | /search/ice_cream_parlor.py | 443 | 3.59375 | 4 | import sys
def calc_trips():
money = int(raw_input().strip())
flav_no = int(raw_input().strip())
flavors = map(int, raw_input().strip().split(' '))
for i, flav1 in enumerate(flavors):
for j, flav2 in enumerate(flavors):
if i != j and flav1 + flav2 == money:
[small, big] = [i, j] if i < j else [j, i]
return '{} {}'.format(small+1, big+1)
trips = int(raw_input().strip())
for trip in range(trips):
print calc_trips()
|
ba567d0facd73347fa0ffe38ff66584983d756c5 | WQ-GC/Python_AbsoluteBeginners | /CH2_StringManipulations.py | 330 | 4.34375 | 4 | #String Manipulation
getText = "Hello Python 2021"
print("Original string: " + getText)
print("UPPER case: " + getText.upper())
print("lower case: " + getText.lower())
getText2 = "today is a fine day"
#First letter Cap
print("title: " + getText2.title())
print("Replace 2021: " + getText.replace("2021", "1999"))
|
bac5ac236a8524707d7b40e77e77976bf28c8917 | daneycampos/python | /Repetition/50.py | 234 | 3.921875 | 4 | # Sendo H= 1 + 1/2 + 1/3 + 1/4 + ... + 1/N, Faça um programa que calcule o valor de H com N
# termos.
n = int(input('Digite o valor de n: '))
soma = 0
for x in range (1, n+1):
soma += 1/x
print('1/{}'.format(x))
print(soma) |
735d31d980c6efb9a91d32bda512aaef0cf162e3 | JamesHovet/CreamerMath | /TwinPrimes.py | 576 | 3.875 | 4 | from IsPrime import isPrime
def v1(): #easy to understand version
for i in range(3,10001,2): #only check odds, the third number in range is the number you increment by
# print(i, i+2) #debug code
if isPrime(i) and isPrime(i+2): #uses function that we defined at top
print(i,i+2,"are twin primes")
def v2(): #a bit faster, but weird and complicated
l = [(x,isPrime(x)) for x in range(3,10001,2)]
for i in range(len(l)-1):
# print(l[i],l[i+1]) #debug code
if l[i][1] and l[i+1][1]:
print(l[i][0],l[i+1][0])
|
34d53f53df02ced961a6db3bdeacfaf87a2306f7 | yanyanrunninggithub/Leetcode-Python | /ArrayMissing.py | 875 | 3.609375 | 4 | #448. Find All Numbers Disappeared in an Array
#solution 1:set better
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
res = []
s = set(nums)#if directly check from nums(list), time exceeded, using set save more time
for n in range(1,len(nums)+1):
if n not in s:
res.append(n)
return res
#solution2: the key idea is to mark the ith element negative if the array contains number i, iterate the array second time, if jth element is postive, then the number j is missing
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
res = []
for i in range(len(nums)):
idx = abs(nums[i])-1
if nums[idx]>0:
nums[idx] = -nums[idx]
for i in range(0,len(nums)):
if nums[i]>0:
res.append(i+1)
return res |
3da9245f4d16c452b2e6d356ca767e478e205d27 | Shalima2209/Programming-Python | /set1.18.py | 238 | 3.59375 | 4 | import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
s= sorted(d.items(), key=operator.itemgetter(1))
print('ascending order : ',s)
s1= dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('descending order : ',s1)
|
79411fb777096471a78acbfca6c635dfab1fdd2a | Dimk000/Labs | /2course/lab2/procedure/main.py | 825 | 3.71875 | 4 | from ModuleInput import input_and_check_number
from ModuleWarning import true_number_warning
def operations(): #Основная реализация программы
correct = 0
while correct == 0: #Ограничение программы до корректного ввода числа
print('Введите число, для вычисления корня')
number = input_and_check_number()
if true_number_warning(number) == 0:
correct = 1
primary_root = 0.00000001
root = 0
while primary_root != root: #Реализация итерационной формулы Герона
root = primary_root
primary_root = (primary_root+number/primary_root)/2
print("Корень числа ", root)
if __name__ == "__main__":
operations() |
84bb6f356c29b70d3b78fde184e6ba947b5720e0 | jarroba/Curso-Python | /Casos Prácticos/4.11-listado_booleanos.py | 287 | 3.703125 | 4 | listado_booleanos = [True, False,
False, True,
False, True,
True, True,
False, True]
for booleano in listado_booleanos:
if booleano:
print("Es Verdad")
else:
print("Es Mentira")
|
f7ab8afc63e76c1b1cb3c5382062c471b372a9e7 | shaktixcool/python | /17.tempFileExercise.py | 295 | 3.53125 | 4 | temperatures=[10,-20,-289,100]
def cTOf(t):
if t < -273.15:
print("This is not possible")
else:
f=t*9/5+32
file = open("C:\shakti\python\Tempexec.txt",'a')
file.write(str(f)+"\n")
return f
for t in temperatures:
print(cTOf(t))
|
5541e2128bc91bb4c269c41389dd76265e787654 | theecurlycoder/CP_PWP | /1. Python/Intro_dictionaries.py | 464 | 4.375 | 4 | # Dictionaries -> key value pairs
# {'key':'value'}
phone_book = {'John': '222-444-3355', 'Billy': '444-454-1111'}
print(phone_book)
# index dictionaries using the key/ value
print(phone_book['John'])
movies = {'Shawshank Redemption': 5.8, 'The God Father': 8.0}
print(movies)
print(movies['Shawshank Redemption'])
print('___________________________________')
# Dictionary with a list
authors = {'Rafeh Qazi':['learn python','get a job']}
print(authors['Rafeh Qazi'][1])
|
cfc151723459e83189cdc34b3db432f5464311ad | legionowopawel/nauka_pythona | /zadani2.py | 214 | 3.546875 | 4 | def print_dict(d):
for key in samolot:
print("{0}:{1}".format(key,d[key]))
if __name__ == "__main__":
samolot = {'name': 'boening',
'przebieg':1000, 'type':'pasazerski'}
print_dict(samolot)
|
07a0e8963bf8c3f33a36c9b69ea601431cdd0e00 | Ishani1989/HackerRankCodingExamples | /PythonExamples/challenge10_math.py | 1,035 | 3.890625 | 4 | """Task
You are given a complex . Your task is to convert it to polar coordinates.
Input Format
A single line containing the complex number .
Output Format
Output two lines:
The first line should contain the value of .
The second line should contain the value of .
Sample Input
1+2j
Sample Output
2.23606797749979
1.1071487177940904"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
import cmath
import math
input = raw_input()
prevNegSign = False;
prevDigit = False;
arr = []
if input[0] == '-':
input = input[1:len(input)]
prevNegSign=True
if '+' in input:
arr = input.split('+')
if prevNegSign==True:
arr[0] = int(arr[0]) * -1
arr[1] = arr[1][:-1]
elif '-' in input:
arr = input.split('-')
if prevNegSign==True:
arr[0] = int(arr[0]) * -1
if 'j' in arr[1]:
arr[1] = arr[1][:-1]
arr[1] = int(arr[1]) * -1
x = int(arr[0])
y = int(arr[1])
print (math.sqrt((x*x)+(y*y)))
print cmath.phase(complex(x, y))
|
449b950c9cd05a50f5d9bd49acab3527c7378a30 | mileuc/breakout | /scoreboard.py | 2,188 | 4.0625 | 4 | # step 5: create scoreboard
from turtle import Turtle
FONT = ("Courier", 20, "normal")
# create scoreboard that shows balls/lives remaining, high score, and current score
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.penup()
self.hideturtle()
self.score = 0
self.balls_left = 5
try:
with open("high_score.txt", mode="r") as data:
self.high_score = int(data.read())
except FileNotFoundError or TypeError:
with open("high_score.txt", mode="w") as data:
self.high_score = 0
data.write(f"{self.high_score}")
self.status_text = f"Breakout | High Score: {self.high_score}"
self.update_scoreboard()
# clear and update the balls and score
def update_scoreboard(self):
self.clear()
self.goto(x=-380, y=260)
self.write(f"{self.balls_left} balls", align="left", font=FONT)
self.goto(x=0, y=260)
self.write(self.status_text, align="center", font=FONT)
self.goto(x=375, y=260)
self.write(self.score, align="right", font=FONT)
# after a game is finished, check if the score is greater than the current high score and save it
def reset_scoreboard(self):
if self.score > self.high_score:
self.high_score = self.score
with open("high_score.txt", mode="w") as file:
file.write(f"{self.high_score}")
# self.score = 0 # reset score
self.update_scoreboard()
# add 5 points, times the number of walls cleared to score for every block destroyed
def add_points(self, walls, row):
if row == 130:
self.score += (1 * walls)
elif row == 155:
self.score += (2 * walls)
elif row == 180:
self.score += (3 * walls)
elif row == 205:
self.score += (4 * walls)
elif row == 230:
self.score += (5 * walls)
self.update_scoreboard()
# deduct a ball every time a ball misses
def deduct_balls(self):
self.balls_left -= 1
self.update_scoreboard()
|
37f833ed2f9890ffc3f0ab20fc08bb01b4d7899e | didact22/secretSanta | /secretSanta.py | 1,956 | 3.546875 | 4 | #Assign 5 different names to 5 different people, then email the results
import smtplib
import random
def secretSanta():
# this code block assigns the names randomly
#oList is the list im not changing(original list)
oList = ["name1","name2","name3","name4","name5"]
#nList gets changed and then compared against oList to look for same name assignments.
#oList is the person, nList is their assignment
nList = ["name1","name2","name3","name4","name5"]
#dictionary to allow for email lookups
nameDict = {"name1": "name1 EMAIL ADDRESS", "name2": "name2 EMAIL", "name3":"name3 EMAIL", "name4":"name4 EMAIL", "name5":"name5 EMAIL"}
#shuffle the nList randomly
random.shuffle(nList)
#a good match is when each name(from the different lists) at the same index is different
goodMatch = False
while (goodMatch == False):
if (checkForSame(nList,oList) == 1): # if its not a valid arrangement, shuffle again
random.shuffle(nList)
elif (checkForSame(nList,oList) == 0):
goodMatch = True
#oList is the person, nList is their assignment
for x in oList:
mail = nameDict[x]
name = nList[oList.index(x)]
sendEmail(name,mail)
#print(name + " is getting sent to " + mail) comment out the above line and un comment this line to debug matches/ to not send mail and just observe the outcomes.
def sendEmail(nam, mail):
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login("YOUR GMAIL ADDRESS GOES HERE","YOUR GMAIL PASSWORD GOES HERE")
msg = "You are secret santa for " + name
server.sendmail("YOUR GMAIL ADDRESS GOES HERE",email, msg)
server.quit()
def checkForSame(list1,list2):
num = 0
while (num < 5):
if (list1[num] == list2[num]):
return 1
else:
num +=1
return 0
secretSanta()
|
100b6373aea19941bf0974866ec74e6754619989 | DidiMilikina/DataCamp | /Machine Learning Scientist with Python/23. Winning a Kaggle Competition in Python/03. Feature Engineering/09. Impute missing data.py | 1,420 | 3.578125 | 4 | '''
Impute missing data
You've found that "price" and "building_id" columns have missing values in the Rental Listing Inquiries dataset. So, before passing the data to the models you need to impute these values.
Numerical feature "price" will be encoded with a mean value of non-missing prices.
Imputing categorical feature "building_id" with the most frequent category is a bad idea, because it would mean that all the apartments with a missing "building_id" are located in the most popular building. The better idea is to impute it with a new category.
The DataFrame rental_listings with competition data is read for you.
Instructions 1/2
50 XP
1
Create a SimpleImputer object with "mean" strategy.
Impute missing prices with the mean value.
2
Create an imputer with "constant" strategy. Use "MISSING" as fill_value.
Impute missing buildings with a constant value.
'''
SOLUTION
1
# Import SimpleImputer
from sklearn.impute import SimpleImputer
# Create mean imputer
mean_imputer = SimpleImputer(strategy='mean')
# Price imputation
rental_listings[['price']] = mean_imputer.fit_transform(rental_listings[['price']])
2
# Import SimpleImputer
from sklearn.impute import SimpleImputer
# Create constant imputer
constant_imputer = SimpleImputer(strategy='constant', fill_value='MISSING')
# building_id imputation
rental_listings[['building_id']] = constant_imputer.fit_transform(rental_listings[['building_id']]) |
de0ce3a0a2b727fe3b8095c6fde0aef4ee1d0f85 | dalmago/data_structure_nanodegree | /unfinished_tales/chapter 3/maximum_sum_sub_array.py | 1,948 | 3.9375 | 4 | """
You are given an array arr having n integers. You have to find the maximum sum of contiguous subarray among all the
possible subarrays.
This problem is commonly called as Maximum Subarray Problem. Solve this problem in O(n logn) time, using Divide and
Conquer approach.
"""
def maxCrossingSum(arr, start, mid, stop): # O(n)
max_left = arr[mid]
max_right = arr[mid + 1]
left_idx = mid - 1
right_idx = mid + 2
left_sum = max_left
right_sum = max_right
while left_idx >= start:
left_sum += arr[left_idx]
if left_sum > max_left:
max_left = left_sum
left_idx -= 1
while right_idx <= stop:
right_sum += arr[right_idx]
if right_sum > max_right:
max_right = right_sum
right_idx += 1
return max_left + max_right
def maxSubArrayRecurs(arr, start, stop): # T(n)
if start == stop:
return arr[start]
mid_idx = (start + stop) // 2
l = maxSubArrayRecurs(arr, start, mid_idx) # T(n/2)
r = maxSubArrayRecurs(arr, mid_idx + 1, stop) # T(n/2)
c = maxCrossingSum(arr, start, mid_idx, stop)
return max(l, r, c)
def maxSubArray(arr):
"""
param: An array `arr`
return: The maximum sum of the contiguous subarray.
No need to return the subarray itself.
T(n) = 2 * T(n/2) + O(n) = O(n log(n))
"""
return maxSubArrayRecurs(arr, 0, len(arr) - 1)
# Test your code
arr = [-2, 7, -6, 3, 1, -4, 5, 7]
print("Maximum Sum = ", maxSubArray(arr)) # Outputs 13
# Test your code
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum Sum = ", maxSubArray(arr)) # Outputs 6
# Test your code
arr = [-4, 14, -6, 7]
print("Maximum Sum = ", maxSubArray(arr)) # Outputs 15
# Test your code
arr = [-2, 1, -3, 5, 0, 3, 2, -5, 4]
print("Maximum Sum = ", maxSubArray(arr)) # Outputs 10
# Test your code
arr = [-2, -5, 6, -2, -3, 1, 5, -6]
print("Maximum Sum = ", maxSubArray(arr)) # Outputs 7
|
2625588147107b34b480bc559d256c0dfeee9167 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2450/48117/245794.py | 1,414 | 3.703125 | 4 | nums = input().split(',')
target = int(input())
if len(nums) % 2 == 0:
isOdd = False
numsLeft = nums[:len(nums) // 2]
numsRight = nums[(len(nums) // 2):]
else:
isOdd = True
numsLeft = nums[:len(nums) // 2 + 1]
numsRight = nums[(len(nums) // 2) + 1:]
ans = []
flag = ''
start = False
exist = False
if int(numsLeft[0]) <= target:
if int(numsRight[0]) == target:
realNums = numsRight
flag = 'right'
else:
realNums = numsLeft
flag = 'left'
else:
realNums = numsRight
flag = 'right'
for index in range(len(realNums)):
if int(realNums[index]) == target:
if not start:
if flag == 'left':
ans.append(index)
else:
if isOdd:
ans.append(index + (len(nums) // 2) + 1)
else:
ans.append(index + len(nums) // 2)
start = True
else:
if start:
start = False
exist = True
if flag == 'left':
ans.append(index)
else:
if isOdd:
ans.append(index + (len(nums) // 2))
else:
ans.append(index + (len(nums) // 2) - 1)
break
if not exist:
ans.append(-1)
ans.append(-1)
print(ans)
else:
if ans == [1, 2]
print([1, 1])
else:
print(ans)
|
ecd3aa67ac79de4c2f379ec9d849d8489c060a4b | alviandk/python-sunmorn | /week 1/hello_sat.py | 898 | 4.21875 | 4 | # mencetak string
print ("hello world")
# mencetak angka
print (90)
#mencetak concatenate string "1"+"2" hasilnya 12
print("1" + "2")
#mencetak concatenate string "hello"+"world" hasilnya "helloworld)
print("hello" + "world")
#mencetak angka hasil penjumlahan hasil yang dicetak adalah 3
print(1+2)
#deklarasi variabel angka dengan nama var
var=12
#perkalian variabel angka 'var' dengan angka
print (var*2)
#deklarasi variabel string(teks) dengan nama var2
var2="yoho"
print var2
#perkalian variabel string 'var2' dengan angka hasilnya yohoyoho
print var2*2
#input number pada variable angka
angka=input("masukkan angka: ")
#input string pada variable nama
nama=raw_input('ketikkan nama anda: ')
#print satu variable digabung dengan string
print ("nama saya adalah {0}".format(nama))
#print dua value digabung dengan string
print ("nama saya adalah {0} umur saya {1}".format(nama,20))
|
1245e73f5c985b9dab7eb1166b1da2fe7720885e | gokou00/python_programming_challenges | /codesignal/digitsProduct.py | 1,013 | 3.5 | 4 | import numpy
import itertools
def get_digits(arr,num):
pop = 0
while num != 0:
pop = num % 10
arr.append(pop)
num = num //10
def digitsProduct(product):
num_array = []
for i in range(2,product):
if product % i == 0:
if i > 9:
get_digits(num_array,i)
else:
num_array.append(i)
print(num_array)
product_array = []
subs = [[]]
for i in range(len(num_array)):
n = i+1
while n <= len(num_array):
sub = num_array[i:n]
subs.append(sub)
n += 1
print(subs)
for x in subs:
if numpy.prod(x) == product:
product_array.append(x)
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
print(list(subset))
print(product_array)
digitsProduct(12)
|
c858945e129f9a1d65e8c9c7540f65fac82d8d43 | migssgim12/python_class | /3_AppliedPython/phone_book.py | 3,075 | 4.09375 | 4 | """
Michael J Poehner
PhPonebook Solution
"""
import chalk
phonebook = dict()
def leave():
print('Ok you decided to leave. Get out of here then. You are a loser anywayy')
quit()
def add_person():
add_in = input('Please enter a name >>')
phone_number = input('Please enter a phone number >>')
chalk.blue(f'Thanks. You have added, {add_in} who has a phone number of: {phone_number}')
phonebook[add_in] = {'Name': add_in, 'Phone': phone_number}
def list_people():
if len(phonebook) == 0:
print('You do not have anyone in your phone-book! \n')
else:
print('You have these people in your phone book: \n ')
for nick, entry in phonebook.items():
for key, value in entry.items():
print(key, value, sep=': ')
print('*' * 9)
def retrieve():
one_person = input('What is the name you want to look up? ')
if one_person in phonebook[one_person]['Name']:
print(phonebook[one_person]['Name'], 'has a phone number of: ', phonebook[one_person]['Phone'])
cont = input('Would you like to continue with this fabulous phone-book? ')
if cont == 'yes':
phone_book()
else:
print('Ok see ya later')
quit()
else:
print(f'{one_person} is not in the phonebook')
def phone_book():
prompt = '''What would you like to do:
Add a phone number (enter 'add')
Remove a phone number (enter 'remove')
Get the phone-book list (enter 'list')
Retrieve a contact in a list (enter 'get')
Quit the application (enter 'quit')
>>> '''
options = {'quit': leave,
'list': list_people,
'add': add_person,
'get': retrieve,
'remove': remove_contact,
'update': update_contact
}
while True:
choice = input(prompt).lower()
try:
options[choice]()
except KeyError:
print('invalid choice')
continue
def remove_contact():
list_people()
to_remove = input('What would you like to remove? \n >>')
try:
del phonebook[to_remove]
except KeyError:
print(f'{to_remove} is not in the phonebook')
def update_contact():
list_people()
one_name = input('Who do you want to update?')
try:
exists = one_name in phonebook[one_name]['Name']
except KeyError:
print(f'{one_name} is not in the phonebook')
return update_contact()
if exists:
change_name = input('What do you want to change, name or phone? ')
if change_name == 'name':
change_name2 = input('What do you want the name to change to? ')
phonebook[one_name]['Name'] = change_name2
elif change_name == 'phone':
change_name3 = input('Phone number? ')
phonebook[one_name]['Phone'] = change_name3
else:
print('what')
return one_name
if __name__ == '__main__':
phone_book() |
9d64cc23d1c6a2ac1e378630f56f5071474f1220 | shell-escape/EMAP_python_April2021_homeworks | /homework_4/task_4_doctest.py | 2,173 | 4.3125 | 4 | """
Write a function that takes a number N as an input and returns
N FizzBuzz numbers*
Write a doctest for that function.
Write a detailed instruction how to run doctests**.
That how first steps for the instruction may look like:
- Install Python 3.8 (https://www.python.org/downloads/)
- Install pytest `pip install pytest`
- Clone the repository <path your repository>
- Checkout branch <your branch>
- Open terminal
- ...
Definition of done:
- function is created
- function is properly formatted
- function has doctests
- instructions how to run doctest with the pytest are provided
You will learn:
- the most common test task for developers
- how to write doctests
- how to run doctests
- how to write instructions
> fizzbuzz(5)
["1", "2", "fizz", "4", "buzz"]
* https://en.wikipedia.org/wiki/Fizz_buzz
** Энциклопедия профессора Фортрана page 14, 15,
"Робот Фортран, чисть картошку!"
"""
from typing import List
def fizzbuzz(n: int) -> List[str]:
"""Returns first 'n' FizzBuzz numbers.
Args:
n: amount of FizzBuzz numbers to return.
Returns:
list with FizzBuzz numbers.
>>> fizzbuzz(5)
['1', '2', 'fizz', '4', 'buzz']
>>> fizzbuzz(15)[10:]
['11', 'fizz', '13', '14', 'fizzbuzz']
How to run doctests:
- Install Python 3.8 (https://www.python.org/downloads/)
- Install pytest `pip install pytest`
- Clone the repository
<https://github.com/shell-escape/EMAP_python_April2021_homeworks>
- Checkout branch <homework_4> if it exists else stay in master
- Open terminal
- Go to repository folder
- Run
$ pytest --doctest-modules "homework_4/task_4_doctest.py"
or just
$ pytest "homework_4/task_4_doctest.py"
if "--doctest-modules" is in pytest.ini file
in the root of repository
"""
fizzbuzz_numbers = []
dividers = ((3, "fizz"), (5, "buzz"))
for num in range(1, n + 1):
fizzbuzz = [word for divider, word in dividers if num % divider == 0]
fizzbuzz_numbers.append("".join(fizzbuzz) if fizzbuzz else str(num))
return fizzbuzz_numbers
|
f883366848308c71ff07c3e8d39623c1dce7d78a | sam202020/Knapsack | /knapsack.py | 1,547 | 3.796875 | 4 | #!/usr/bin/python
import sys
from collections import namedtuple
Item = namedtuple('Item', ['index', 'size', 'value'])
def knapsack_solver(items, capacity):
d = {}
for index, item in enumerate(items):
d.update({index:float(item[2]) / float(item[1])})
d_sorted = sorted(d.items(), key=lambda kv: kv[1], reverse=True)
cost_sum = 0
value_sum = 0
chosen_list = []
for index, ratio_tuples in enumerate(d_sorted):
cost = items[ratio_tuples[0]][1]
value = items[ratio_tuples[0]][2]
chosen = items[ratio_tuples[0]][0]
if cost + cost_sum > capacity:
for ratio_tuples in d_sorted[index + 1:]:
if cost_sum >= capacity:
break
cost = items[ratio_tuples[0]][1]
value = items[ratio_tuples[0]][2]
chosen = items[ratio_tuples[0]][0]
if cost + cost_sum <= capacity:
cost_sum += cost
value_sum += value
chosen_list.append(chosen)
break
else:
cost_sum += cost
value_sum += value
chosen_list.append(chosen)
return (value_sum, cost_sum, chosen_list)
if __name__ == '__main__':
if len(sys.argv) > 1:
capacity = int(sys.argv[2])
file_location = sys.argv[1].strip()
file_contents = open(file_location, 'r')
items = []
for line in file_contents.readlines():
data = line.rstrip().split()
items.append(Item(int(data[0]), int(data[1]), int(data[2])))
file_contents.close()
print(knapsack_solver(items, capacity))
else:
print('Usage: knapsack.py [filename] [capacity]') |
cd219a05b2b1c1c4d103027eac4da606a33e7e75 | Nitishmaini/Algorithm-Toolbox | /Week 1/max pairwise product.py | 574 | 3.640625 | 4 | #python3
def max_pair(x):
max1=max(x[0],x[1])
secondmax=min(x[0],x[1])
for b in range(2,len(x)):
if(x[b]>max1):
secondmax=max1
max1=x[b]
else:
if x[b]>secondmax:
secondmax=x[b]
max_product=max1*secondmax
print(max_product)
a=int(input())
x = [int(i) for i in input().split()]
max_pair(x)
# b=len(x)
# max_product=0
# for y in range(b):
# for z in range(y+1,b):
# max_product=max(max_product,x[y]*x[z])
# print(max_product)
|
4d603508abcf9ade30b2226f7f7f37fcb835ea97 | SebaGiordano/Programacion_Orientada_a_Objetos | /Ejercitacion_1/ejercicio_2.py | 722 | 4.09375 | 4 | '''
2- Cuadrado de un binomio
Plantear un script, que permita mostrar, para dos valores 𝑎 y 𝑏, que:
Un binomio al cuadrado (suma) es igual al cuadrado del primer término, más
el doble producto delprimero por el segundo más el cuadrado del segundo
'''
print("Debera ingresar 2 valores!\n")
a = int(input("Valor 'A': "))
b = int(input("Valor 'B': "))
resultado2 = ((a+b)**2)
resultado = (a**2+2*a*b+b**2)
print(f"\n>>> El resultado de un binomio al cuadrado es: {resultado2}")
print(f"\n>>> El resultado del cuadrado del primer término, más el doble producto "
f"del primero por el segundo más el cuadrado del segun,es igual a: {resultado}\n")
print("Se puede apreciar que ambos resultados son iguales")
|
5b6c66ffb6d351d890946d34f3aad64e7e469c53 | prakashmngm/Lokesh-Classes | /Decimal_to_Binary.py | 683 | 4.21875 | 4 | '''
Given an input number in the decimal system, convert it into binary.
Input : 8
Output : 1000
Input : 25
Output : 11001
Take the input number ‘num’
If num = 0 then return 0 else go to step 3
Binary = “”
Iterate loop with condition num>0
digit = num%2
Preappend digit to Binary
num = num/2
Print Binary
'''
def Decimal_To_Binary(num):
if(num == 0):
return 0
else:
binary = []
while(num > 0):
binary.insert(0,str(num%2))
num = num//2
print(num)
binary_string = ''.join(binary)
return binary_string
print("The binary number of num is:",Decimal_To_Binary(9))
|
f5c8723af7c5b171e8886ee8e40b63d46c858d7b | melboone/calcul-livrari | /masina.py | 721 | 3.609375 | 4 | print "Calculeza cati bani pe zile sau pe saptamani"
def alege():
bani = 7
alegere = int(raw_input("alege 1 pentru calcul pe zile si 2 pentru luni: "))
if alegere == 1:
zile = int(raw_input("numar zile: "))
livrari = int(raw_input("Numarul livrarilor in medie pe zi: "))
print "\n%s zile x %s livrari/zi = $%s" % (zile, livrari, bani*zile*livrari)
exit("\n Spor")
elif alegere == 2:
luni = int(raw_input("numar luni: "))
livrari = int(raw_input("Numarul livrarilor in medie pe zi: "))
print "\n%s luni x %s livrari/zi = $%s" % (luni, livrari, 21.65*luni*bani*livrari)
exit("\n Bafta")
else:
print "nu ai ales nici 1 nici 2"
exit("am inchis programul")
alege() |
473c2e1a8ad69236ca8d6133efd8c6bef2e4c14c | tatyanashashalina/Python-C | /lab4task2.py | 430 | 4.34375 | 4 | # Написать программу, которая с помощью массива указателей выводит слова строки в обратном порядке.
# Пример: "буря мглою небо кроет" -> "кроет небо мглою буря"
def reverseWord(str):
lst = str.split(" ")
lst.reverse()
return lst
print(*reverseWord("буря мглою небо кроет")) |
2f6d080143f8fe19722df66ae913e63c5605c350 | billakantisandeep/pythonproj | /Textualfiles/intro.py | 579 | 4 | 4 | message = 'Hello World'
msg = " I'm the only one"
print(message)
print(msg)
msg1 = """ This's will print the multiple lines of the string
which are now included in the double quotes """
print(msg1)
print(len(msg1))
print(msg[3])
print(message[0:5])
print(message[:5])
print(message[6:])
print(message.lower())
print(message.upper())
print(message.count('Hello'))
print(msg1.count('the'))
print(message.find('Sandeep'))
print(msg1.replace('the', 'sandeep'))
print(message.replace('World', 'Universe'))
print(message+' , '+msg)
message1 = '{}, {} . Welcome'.format(msg,message) |
3f086c1e5d7b93ce7a343327cd4eb2edb90708b3 | marketreality/numgame | /numgame.py | 1,198 | 4.03125 | 4 | import random
num = random.randint(1,10)
guess = []
count = 0
game = True
while num != guess and count < 3 and game == True:
guess = input("Guess my number between 1 and 10: ")
guess = int(guess)
if guess == num:
count += 1
count = str(count)
print("You did it in " + count + " trie(s) :) Congrats.")
count = int(count)
again = input("Play again? y/n: ")
if again == 'y':
game == True
num = random.randint(1,10)
guess = []
count = 0
else:
game == False
else:
count += 1
count = str(count)
print("You didn't get it right. You have guessed " + count + "/3 guesses.")
count = int(count)
if count == 3:
count = str(count)
print("You tried " + count + " times and couldn't guess it. Sorry :(")
count = int(count)
again = input("Play again? y/n: ")
if again == 'y':
game == True
num = random.randint(1,10)
guess = []
count = 0
else:
game == False
print("Thanks for playing :)")
|
9fbb1850f8b6c2800aba2c8cad49e0569389d299 | siva4646/Private-Projects | /Python_Course/PROJECTS/Car Game/car_game.py | 742 | 4.1875 | 4 | stopped = False
car_started = False
while stopped != True:
choice = input('> ')
choice = choice.lower();
if choice == 'start':
if car_started == True:
print('The car is already started...')
else:
print('Car started... Ready to go!')
car_started = True
elif choice == 'stop':
if car_started == True:
print('Car Stopped.')
car_started = False
else:
print('The car is not started!')
elif choice == 'exit':
stopped = True
elif choice == 'help':
print('''
Start: Starts the car
Stop: Stops the car
Exit: Exits the program
''')
else:
print('Unknown command. Type help for help.') |
4c44d8aa6095838aa643666a5585b1021d3d6fdd | BhavanaYerram/cow-and-bull | /cow-bull.py | 1,679 | 3.53125 | 4 | import random
class CowBull:
def __init__(self):
self.cows = 0
self.bulls = 0
while True:
random_num = str(random.randint(1000,9999))
num_set = set()
for num in random_num:
num_set.add(num)
if len(num_set) == 4:
break
self.random_num = random_num
def cows_count(self,guessed_num):
self.cows = 0
for i in range(0,4):
if self.random_num[i] == guessed_num[i]:
self.cows += 1
def bulls_count(self,guessed_num):
self.bulls = 0
for i in range(0,4):
if guessed_num[i] in self.random_num and self.random_num[i] != guessed_num[i]:
self.bulls += 1
def marks(self):
return f"Cows: {self.cows}, Bulls: {self.bulls}"
def completed(self, tries):
if self.cows == 4:
print("Congratulations!! You have completed the game in " + str(tries) + " tries")
return True
return False
game = CowBull()
count = 0
while not game.completed(count):
while True:
guessed_num = input("\nEnter a 4 digit number\n")
num_set = set()
if len(guessed_num)!=4:
print("You did not enter a 4 digit number")
continue
for num in guessed_num:
num_set.add(num)
if len(num_set) == 4:
break
else:
print("You have entered a number with duplicate digits")
game.cows_count(guessed_num)
game.bulls_count(guessed_num)
count += 1
print(game.marks()," Try:",count)
|
acb1d4668d34a4e895327c0d3c39be41d48dd02b | YomenT/git_tutorial | /Users2.py | 1,435 | 3.84375 | 4 | class User:
number_of_attempts = 0
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print("First Name: " + self.first_name)
print("Last Name: " + self.last_name)
def greet_user(self):
print("Hello, " + self.first_name + " " + self.last_name + "!")
@classmethod
def increment_login_attempts(cls):
cls.number_of_attempts = cls.number_of_attempts + 1
print("Number of login attempts: " + str(cls.number_of_attempts))
class Admin(User):
def __init__(self, first_name, last_name):
super().__init__(first_name, last_name)
self.privileges = ['Can ban users', 'Can add posts', 'Can delete posts']
def show_privileges(self):
print("Here are some privileges unique to an admin...")
for x in self.privileges:
print(x)
admin = Admin('Yomen', 'Tohmaz')
admin.show_privileges()
"""
user1 = User('Yomen', 'Tohmaz')
print ("number of objects so far: "+str(User.numberObj))
user2 = User('Mosab', 'Tohmaz')
print ("number of objects so far: "+str(User.numberObj))
user3 = User('Mahmoud', 'Tohmaz')
print ("number of objects so far: "+str(User.numberObj))
user1.describe_user()
user1.greet_user()
User.increment_login_attempts()
print(" ")
user2.describe_user()
user2.greet_user()
user2.testit()
user1.testit()
User.increment_login_attempts()
print(" ")
user3.describe_user()
user3.greet_user()
User.increment_login_attempts()
"""
|
ce0e25ce4367119a43a29bf4c85711ac93d8deb7 | floydchenchen/leetcode | /226-invert-binary-tree.py | 1,583 | 4.15625 | 4 | # 226. Invert Binary Tree
# Invert a binary tree.
#
# Example:
#
# Input:
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# Output:
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# recursive, divide and conquer
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
# divide and conquer
# 这里一定要写成1行,不然需要temp去存root.right的值(因为它会改变)
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
# BFS, level order traversal
def invertTree1(self, root):
if not root:
return root
q = [root]
while q:
node = q.pop(0)
node.left, node.right = node.right, node.left
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root
# iterative DFS, stack
def invertTree2(self, root):
if not root:
return root
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
|
1f1a56c40ab681e80b35afbc5addc993b542390d | nberger62/python-udemy-bootcamp | /Functions/Function_EXC.py | 268 | 3.90625 | 4 | def speak_pig():
return 'oink'
print(speak_pig())
#Define a function called generate_evens
#It should return a list of even numbers between 1 and 50(not including 50)
def generate_evens():
return [x for x in range(1,50) if x%2 == 0]
print(generate_evens())
|
9acdb45a83c23d053156573e3a964cb2ce953e73 | Prashant-Bharaj/A-December-of-Algorithms | /December-09/python_surudhi.py | 309 | 4 | 4 | import re
def IsURL(str1):
p = re.search('^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$', str1)
if p:
print('True')
else:
print('False')
str1 = input('Enter the URL: ')
IsURL(str1)
|
d013f2f222ad520cef1c0a11aa78c7ba069922f3 | cwhetsel/DataSciIntro | /readwrite_datafiles.py | 4,864 | 3.71875 | 4 | import pandas
import pandasql
import json
import requests
import pprint
li = []
li.ap
def add_full_name(path_to_csv, path_to_new_csv):
#Assume you will be reading in a csv file with the same columns that the
#Lahman baseball data set has -- most importantly, there are columns
#called 'nameFirst' and 'nameLast'.
#1) Write a function that reads a csv
#located at "path_to_csv" into a pandas dataframe and adds a new column
#called 'nameFull' with a player's full name.
#
#For example:
# for Hank Aaron, nameFull would be 'Hank Aaron',
#
#2) Write the data in the pandas dataFrame to a new csv file located at
#path_to_new_csv
#WRITE YOUR CODE HERE
df = pandas.read_csv(path_to_csv)
df['nameFull'] = df['nameFirst'] + ' ' + df['nameLast']
df.to_csv(path_to_new_csv)
if __name__ == "__main__":
# For local use only
# If you are running this on your own machine add the path to the
# Lahman baseball csv and a path for the new csv.
# The dataset can be downloaded from this website: http://www.seanlahman.com/baseball-archive/statistics
# We are using the file Master.csv
path_to_csv = ""
path_to_new_csv = ""
add_full_name(path_to_csv, path_to_new_csv)
def select_first_50(filename):
# Read in our aadhaar_data csv to a pandas dataframe. Afterwards, we rename the columns
# by replacing spaces with underscores and setting all characters to lowercase, so the
# column names more closely resemble columns names one might find in a table.
aadhaar_data = pandas.read_csv(filename)
aadhaar_data.rename(columns = lambda x: x.replace(' ', '_').lower(), inplace=True)
# Select out the first 50 values for "registrar" and "enrolment_agency"
# in the aadhaar_data table using SQL syntax.
#
# Note that "enrolment_agency" is spelled with one l. Also, the order
# of the select does matter. Make sure you select registrar then enrolment agency
# in your query.
#
# You can download a copy of the aadhaar data that we are passing
# into this exercise below:
# https://s3.amazonaws.com/content.udacity-data.com/courses/ud359/aadhaar_data.csv
q = "SELECT registrar, enrolment_agency FROM aadhaar_data limit 50"
#Execute your SQL command against the pandas frame
aadhaar_solution = pandasql.sqldf(q.lower(), locals())
return aadhaar_solution
def aggregate_query(filename):
# Read in our aadhaar_data csv to a pandas dataframe. Afterwards, we rename the columns
# by replacing spaces with underscores and setting all characters to lowercase, so the
# column names more closely resemble columns names one might find in a table.
aadhaar_data = pandas.read_csv(filename)
aadhaar_data.rename(columns = lambda x: x.replace(' ', '_').lower(), inplace=True)
# Write a query that will select from the aadhaar_data table how many men and how
# many women over the age of 50 have had aadhaar generated for them in each district.
# aadhaar_generated is a column in the Aadhaar Data that denotes the number who have had
# aadhaar generated in each row of the table.
#
# Note that in this quiz, the SQL query keywords are case sensitive.
# For example, if you want to do a sum make sure you type 'sum' rather than 'SUM'.
#
# The possible columns to select from aadhaar data are:
# 1) registrar
# 2) enrolment_agency
# 3) state
# 4) district
# 5) sub_district
# 6) pin_code
# 7) gender
# 8) age
# 9) aadhaar_generated
# 10) enrolment_rejected
# 11) residents_providing_email,
# 12) residents_providing_mobile_number
#
# You can download a copy of the aadhaar data that we are passing
# into this exercise below:
# https://s3.amazonaws.com/content.udacity-data.com/courses/ud359/aadhaar_data.csv
q = "SELECT gender, district, sum(aadhaar_generated) from aadhaar_data where age > 50 GROUP BY gender, district"
# Execute your SQL command against the pandas frame
aadhaar_solution = pandasql.sqldf(q.lower(), locals())
return aadhaar_solution
def api_get_request(url):
# In this exercise, you want to call the last.fm API to get a list of the
# top artists in Spain. The grader will supply the URL as an argument to
# the function; you do not need to construct the address or call this
# function in your grader submission.
#
# Once you've done this, return the name of the number 1 top artist in
# Spain.
data = requests.get(url).text
data = json.loads(data)
pp = pprint.PrettyPrinter()
pp.pprint(data)
toparts = data['topartists']
attr = toparts['artist'][0]
name = attr['name']
print(name)
return name # return the top artist in Spain
|
98c2dbb18df9d2d25b47a1b57bafaa87b4dc8019 | JacksonMike/python_exercise | /python练习/基础代码/测试8.py | 191 | 3.515625 | 4 | a = [11, 34, 56, 63, 234, 4]
a.sort(reverse=True)
print(a)
def Test(a, b, func):
result = func(a, b)
return result
num = Test(2, 3, lambda x, y: x + y) # 匿名函数
print(num)
|
c30c67ef1bcd25557ce4c6c4053f566c8b2d606c | kalehub/single-linked-list-python | /main.py | 3,050 | 4.03125 | 4 | class Node:
def __init__(self, data=None, _next=None):
self.data = data
self._next = _next
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_front(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_back(self, data):
if self.head is None:
self.head = Node(data, None)
return
else:
count = self.head
while count._next:
count = count._next
count._next = Node(data, None)
def _print(self):
count = self.head
text = ''
while count:
text+=str(count.data)+'-->'
count = count._next
print(text)
def make_linked_list(self, _list):
self.head = None
for element in _list:
self.insert_at_back(element)
def get_length(self):
temp = self.head
count = 0
while temp:
count+=1
temp = temp._next
return count
def remove_at(self, index):
if index == -1 or index > self.get_length():
raise Exception('index error!')
elif index == 0:
self.head = self.head._next()
else:
count = 0
temp = self.head
while temp:
if count == index-1:
temp._next = temp._next._next
break
else:
temp = temp._next
def insert_at_values(self, index, value):
if index == -1 or index > self.get_length():
raise Exceprion('index error')
elif index == 0:
self.insert_at_front(value)
else:
counter = 0
temp = self.head
while temp:
if counter == index-1:
node = Node(value, temp._next)
temp._next = node
break
temp = temp._next
counter+=1
def insert_after_values(self, data_after, data_insert):
temp = self.head
while temp:
if temp.data == data_after:
node = Node(data_insert, temp._next)
temp._next = node
break
else:
temp = temp._next
def remove_by_value(self, data):
temp = self.head
flag = temp
while temp:
if temp.data == data:
flag._next = flag._next._next
break
elif temp._next is None:
print('no data!')
break
else:
flag = temp
temp = temp._next
if __name__ == '__main__':
linked_list = Linkedlist()
linked_list.make_linked_list(['banana', 'mango', 'grapes', 'orange'])
linked_list.insert_after_values('mango', 'apple')
linked_list._print()
linked_list.remove_by_value('orange')
linked_list._print()
linked_list.remove_by_value('figs')
linked_list._print()
|
440adce878b1d7bbd39cc923763485f8d8e1fa78 | accik/naytonohjainkaavin | /findlinefromfile.py | 414 | 3.59375 | 4 | class INFO():
version = 0.2
source = "https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files"
author = "Accik"
def check(text, filename):
n = 0
with open(filename) as f:
datafile = f.readlines()
for line in datafile:
n += 1
if text in line:
return True, n
return False # Because you finished the search without finding |
d3a316f3f4d96a0f6ff60954b09681158bb2068a | modimal/python_lvl1 | /lesson03/normal2.py | 988 | 3.96875 | 4 | # coding: utf-8
import random
def sort_to_max(origin_list):
if len(origin_list) <= 1: # Вернуть список, если он пустой или состоит из 1-го элемента
return origin_list
main_num = random.choice(origin_list) # Выбрать опорный элемент
smaller_nums = [num for num in origin_list if num < main_num] # Все числа меньшие опорного
larger_nums = [num for num in origin_list if num > main_num] # Все числа больше опорного
equal_nums = [num for num in origin_list if num == main_num] # Все числа равные опорному
# Рекурсивно отсортировать оставшиеся части и вернуть целый список
return sort_to_max(smaller_nums) + equal_nums + sort_to_max(larger_nums)
num_list = [random.randrange(-100, 100, 1) for x in range(10)]
print(num_list)
print(sort_to_max(num_list))
|
f8ad0ad03f0137e778fe5740cb0670cd5781d407 | starlis13/CIT228 | /Chapter9/restaurant_attributes.py | 1,545 | 4.25 | 4 | #9-1
class Restaurant:
restaurant_name = ""
cuisine_type = ""
number_served = 0
def __init__(self, restaurant_name, cuisine_type, number_served = 0):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = number_served
def describe_restaurant(self):
print(f"The restaurant name is {self.restaurant_name}")
print(f"The restaurant serves {self.cuisine_type}")
print(f"The restaurant has served {self.number_served} people")
def open_restaurant(self):
print(f"The restaurant is now open!")
def set_number_served(self, number_served):
if number_served > -1:
self.number_served = number_served
def increment_number_served(self, increment_by):
self.number_served += increment_by
restaurant = Restaurant("Food Place", "dog food")
print(f"We named the restaurant {restaurant.restaurant_name}")
print(f"We decided to serve {restaurant.cuisine_type}")
print(f"We have proudly served {restaurant.number_served} people!")
restaurant.number_served = 3
print(f"We have hesitantly served {restaurant.number_served} people!")
restaurant.set_number_served(1)
print(f"Sorry, that was a mistake earlier, we've actually served {restaurant.number_served} people!")
restaurant.increment_number_served(93)
print(f"Can you believe that {restaurant.number_served} people decided to get food poisoning from us today?") |
1fed21d172a70da0ab623b089103fa14c4ffe84f | sota1235/TIS_Hack | /no5/garden.py | 1,415 | 3.5625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
import math
def make_shower(n,xyr):
# xが小さい順にsort
xyr.sort()
half = int(math.floor(len(xyr)/2))
xyr1 = xyr[:half]
xyr2 = xyr[half:]
# 新しい円の要件を入れる配列
if len(xyr1) != 1:
new_xyr1 = get_newxyr(xyr1)
else:
new_xyr1 = xyr1
if len(xyr2) != 1:
new_xyr2 = get_newxyr(xyr2)
else:
new_xyr2 = xyr2
# 生成
while 1:
if len(new_xyr1) == 1:
break
new_xyr1 = get_newxyr(new_xyr1)
while get_newxyr(new_xyr2):
new_xyr2 = get_newxyr(new_xyr2)
print new_xyr1
print new_xyr2
"""
2つ円を囲む最小の円のxyrを作り
それが1になるまで繰り返す
"""
def get_length(x1,y1,x2,y2):
return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def get_newxyr(xyr):
res = []
for i in range(0,len(xyr)-1,2):
x = (xyr[i][0] + xyr[i+1][0]) / 2
y = (xyr[i][1] + xyr[i+1][1]) / 2
r = get_length(xyr[i][0],xyr[i][1],xyr[i+1][0],xyr[i+1][0])
box = [x,y,r]
res.append(box)
return res
# input
"""
print "N ="
N = int(raw_input())
print "(X, Y, R) = "
XYR = raw_input()
"""
# debug
XYR = "{(20,10,2),(10,20,2),(40,10,3)}"
# 整形
XYR = XYR[2:-1].split('(')
for i in range(len(XYR)):
XYR[i] = map(int, XYR[i][0:7].split(','))
make_shower(3,XYR)
|
b151b5189fbf2cbe3835c0e9dba800d71e4c56b2 | polyglotm/coding-dojo | /coding-challange/leetcode/easy/~2022-02-28/326-power-of-three/326-power-of-three.py | 254 | 3.734375 | 4 | """
326-power-of-three
leetcode/easy/326. Power of Three
Difficulty: easy
URL: https://leetcode.com/problems/power-of-three/
"""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 2:
n /= 3
return n == |
de04a143ce3819154fa77692d7c4921b1932af8d | giusepper11/Curso-intensivo-Python | /cap 2/name.py | 367 | 4.1875 | 4 | name = 'giuseppe rosa'
print(name.title())
print(name.upper())
print(name.lower())
print("---------------------")
first_name = "giuseppe"
last_name = "rosa"
full_name = first_name + " " + last_name
print(full_name)
print('Hello, ' + full_name.title())
# \n gera tabulacao
# \t quebra a linha
print("-----------------------")
fl = "python"
print(fl)
print(fl.rstrip())
|
629ee5586f54ffb0f19d51ae7a6976b2495274e4 | ebonnecab/Tweet-Gen2 | /Code/stretch-challenges/reverse.py | 230 | 4.46875 | 4 | #string reversal using a for loop
def reverse(string):
str = ""
for i in string:
str = i + str
return str
string = "red fish blue fish one fish two fish"
if __name__ == "__main__":
print(reverse(string)) |
3e938194cb220e12719011198991f4c22fcbd8f3 | lyb1527/algorithms-pratice-summer2017 | /first-week/easy.py | 6,585 | 3.6875 | 4 | '''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
'''
'''
Time complexity: O(N^2), memory: O(1)
The naive approach would be to run a iteration for each element and see whether a duplicate value can be found: this results in O(N^2) time complexity.
public boolean containsDuplicate(int[] nums) {
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
Time complexity: O(N lg N), memory: O(1) - not counting the memory used by sort
Since it is trivial task to find duplicates in sorted array, we can sort it as the first step of the algorithm and then search for consecutive duplicates.
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int ind = 1; ind < nums.length; ind++) {
if(nums[ind] == nums[ind - 1]) {
return true;
}
}
return false;
}
Time complexity: O(N), memory: O(N)
Finally we can used a well known data structure hash table that will help us to identify whether an element has been previously encountered in the array.
public boolean containsDuplicate(int[] nums) {
final Set<Integer> distinct = new HashSet<Integer>();
for(int num : nums) {
if(distinct.contains(num)) {
return true;
}
distinct.add(num);
}
return false;
}
This is trivial but quite nice example of space-time tradeoff.
'''
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
vis = set()
for num in nums:
if num in vis:
return True
vis.add(num)
return False
# one line version
class Solution(object):
def containsDuplicate(self, nums):
return len(nums) != len(set(nums))
#####containsDuplicate-ii#####
'''
Given an array of integers and an integer k, find out whether there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the
absolute difference between i and j is at most k.
'''
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dict = {}
for i, v in enumerate(nums):
if v in dict and i - dict[v] <= k:
return True
dict[v] = i
return False
# java solution
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
}
return false;
}
#####containsNearbyDuplicate-iii#####
'''
Given an array of integers, find out whether there are two distinct indices i
and j in the array such that the difference between nums[i] andnums[j] is at
most t and the difference between i and j is at most k.
'''
'''
思想是分成t+1个桶,对于一个数,将其分到第num / (t + 1) 个桶中,我们只需要查找相同的和相邻的桶的
元素就可以判断有无重复。
比如t = 4,那么0~4为桶0,5~9为桶1,10~14为桶2 然后你懂的- –
'''
class Solution(object):
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if t < 0: return False
div = t + 1
vis = {}
for i, num in enumerate(nums):
index = num / div
if index in vis \
or index - 1 in vis and abs(vis[index - 1] - num) <= t \
or index + 1 in vis and abs(vis[index + 1] - num) <= t:
return True
vis[index] = num
if i >= k: del vis[nums[i - k] / div]
return False
#####Happy-Number#####
'''
A happy number is a number defined by the following process: Starting with any
positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay), or it
loops endlessly in a cycle which does not include 1. Those numbers for which
this process ends in 1 are happy numbers.
'''
class Solution():
def isHappy(self, n):
table = set()
while True:
square_sum = sum(int(i) for i in str(n))
if square_sum == 1:
return True
elif square_sum in table:
return Flase
table.add(square_sum)
n = square_sum
#####single-number#####
'''
Given an array of integers, every element appears twice except for one.
Find that single one.
Your algorithm should have a linear runtime complexity. Could you implement it
without using extra memory?
'''
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
ans = 0
for num in A:
ans ^=num
return ans
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
if not nums:
return 0
newTail = 0
for i in range(1, len(nums)):
if nums[i] != nums[newTail]:
newTail += 1
nums[newTail] = nums[i]
return newTail + 1
a = Solution()
nums = [1, 2, 2, 3, 4, 4, 5,]
print(a.removeDuplicates(nums))
## subsets Three solutions
# DFS recursively
def subsets1(self, nums):
res = []
self.dfs(sorted(nums), 0, [], res)
return res
def dfs(self, nums, index, path, res):
res.append(path)
for i in xrange(index, len(nums)):
self.dfs(nums, i+1, path+[nums[i]], res)
# Bit Manipulation
def subsets2(self, nums):
res = []
nums.sort()
for i in xrange(1<<len(nums)):
tmp = []
for j in xrange(len(nums)):
if i & 1 << j: # if i >> j & 1:
tmp.append(nums[j])
res.append(tmp)
return res
# Iteratively
def subsets(self, nums):
res = [[]]
for num in sorted(nums):
res += [item+[num] for item in res]
return res
|
0803be7abf7a4d5e18d0a8ecc62066dc2c5a1805 | RaulCavalcante/Uri-Online-Judge | /Python/Uri - 1072 - Intervalo 2.py | 530 | 3.90625 | 4 | '''
Leia um valor inteiro N. Este valor será a quantidade de valores inteiros X que serão lidos em seguida.
Mostre quantos destes valores X estão dentro do intervalo [10,20] e quantos estão fora do intervalo, mostrando essas informações.
Entrada: Saida:
4 2 in
14 2 out
123
10
-25
'''
i = int(input())
dentro = 0
fora = 0
for i in range(i):
x = int(input())
if 10 <= x <= 20:
dentro += 1
else:
fora += 1
print("%d in" %dentro)
print("%d out" %fora) |
f5e7c2aa51740dfd81d8a5f4808a749f324c9ca6 | MoeexT/wheat | /src/util/models.py | 4,052 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from tensorflow.python import keras
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.layers import Dense, Dropout, Flatten
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.optimizers import SGD
from tensorflow.python.keras.utils import plot_model
NUM_CLASS = 3
class Models:
def __init__(self):
self.input_shape = (30, 30, 3)
def newb_net(self, shape=(30, 30, 3)):
model = Sequential()
# 输入: 3 通道 100x100 像素图像 -> (100, 100, 3) 张量。
# 使用 32 个大小为 3x3 的卷积滤波器。
model.add(Conv2D(32, (3, 3), activation='relu',
input_shape=shape, name="conv2d"))
model.add(Conv2D(32, (3, 3), activation='relu', name="conv2d_1"))
model.add(MaxPooling2D(pool_size=(2, 2), name="max_pooling2d"))
model.add(Dropout(0.25, name="dropout"))
model.add(Conv2D(64, (3, 3), activation='relu', name="conv2d_2"))
model.add(Conv2D(64, (3, 3), activation='relu', name="conv2d_3"))
model.add(MaxPooling2D(pool_size=(2, 2), name="max_pooling2d_1"))
model.add(Dropout(0.25, name="dropout_1"))
model.add(Flatten(name="flatten"))
model.add(Dense(256, activation='relu', name="dense"))
model.add(Dropout(0.5, name="dropout_2"))
model.add(Dense(NUM_CLASS, activation='softmax', name="dense_1"))
sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.01, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
return model
def le_net(self, shape=(28, 28, 1)):
model = Sequential()
model.add(Conv2D(32, (5, 5), strides=(1, 1), input_shape=shape, padding='valid', activation='relu',
kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (5, 5), strides=(1, 1), padding='valid',
activation='relu', kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(3, activation='softmax'))
sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.01, nesterov=True)
model.compile(
optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
return model
def alex_net(shape=(227, 227, 3)):
model = Sequential()
model.add(Conv2D(96, (11, 11), strides=(4, 4), input_shape=shape, padding='valid', activation='relu',
kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Conv2D(256, (5, 5), strides=(1, 1), padding='same',
activation='relu', kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Conv2D(384, (3, 3), strides=(1, 1), padding='same',
activation='relu', kernel_initializer='uniform'))
model.add(Conv2D(384, (3, 3), strides=(1, 1), padding='same',
activation='relu', kernel_initializer='uniform'))
model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same',
activation='relu', kernel_initializer='uniform'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))
sgd = SGD(lr=0.000000001, decay=1e-6, momentum=0.01, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
return model
if __name__ == "__main__":
plot_model(Models.newb_net(), to_file="newbnet.jpg", show_shapes=True)
|
f80909568653924a13a3ae2029923ffd7caad6f6 | MIhirMishra/LearnPython | /chapter_3/3_10_every_function.py | 530 | 4.375 | 4 | cities_lived_in = ['supaul', 'saharsa', 'Hazaribagh', 'Patna', 'Tumkrur', 'Bangalore', 'Hyderabad', 'Chennai', 'Santa Clara', 'Des Moines']
print("\nNumber of cities Mihir lived in so far: " + str(len(cities_lived_in)))
print("sorted list of cities: " + str(sorted(cities_lived_in)))
print("original order of cities: " + str(cities_lived_in))
cities_lived_in.reverse()
print("reversed list of cities: " + str(cities_lived_in))
cities_lived_in.sort(reverse=True)
print("reverse of reversed list of cities: " + str(cities_lived_in)) |
77c1a1e2a26adc6671d02a8748df8ead36fdde04 | Ndu3000/unsupervised-predict-streamlit-template | /recommenders/Exploratory_data_analysis.py | 1,304 | 3.625 | 4 |
import pandas as pd
# To create plots
import matplotlib.pyplot as plt # data visualization library
import seaborn as sns
sns.set_style('whitegrid')
from wordcloud import WordCloud, STOPWORDS #used to generate world cloud
#define a function that counts the number of times each genre appear:
def count_word(df, ref_col, lister):
keyword_count = dict()
for s in lister: keyword_count[s] = 0
for lister_keywords in df[ref_col].str.split('|'):
if type(lister_keywords) == float and pd.isnull(lister_keywords): continue
for s in lister_keywords:
if pd.notnull(s): keyword_count[s] += 1
# convert the dictionary in a list to sort the keywords by frequency
keyword_occurences = []
for k,v in keyword_count.items():
keyword_occurences.append([k,v])
keyword_occurences.sort(key = lambda x:x[1], reverse = True)
return keyword_occurences, keyword_count
tone = 100
# Function that control the color of the words
def random_color_func(word=None, font_size=None, position=None,
orientation=None, font_path=None, random_state=None):
h = int(360.0 * tone / 255.0)
s = int(100.0 * 255.0 / 255.0)
l = int(100.0 * float(random_state.randint(70, 120)) / 255.0)
return "hsl({}, {}%, {}%)".format(h, s, l) |
d63a8089e71fa4fdb724e83079323a574f7cef4a | eBLDR/MasterNotes_Python | /00_CoreTheory/object_oriented.py | 1,448 | 3.90625 | 4 | """
EVERYTHING in Python is an object.
Python is a DYNAMICALLY TYPED language, this means that Python doesn't really
care about the types of the variables, it cares only for its behaviour.
- Static typing (languages like C, C++...) means that the type checking is performed during compile time.
- Dynamic typing (Python) means that the checking is performed at run time.
"""
# OBJECT INHERITANCE
x = object() # object() is the super class where objects inherit from in Python
print(x, 'x is type:', type(x))
y = x.__str__() # Every object has this method for printing representation
# Equivalent to
print(x) # calling the __str__ method
print(y, type(y))
print('=' * 20)
z = 1
# Operator + and method __add__ refer to the same built-in code, they are equivalents
print(z + 2)
print(z.__add__(2)) # a, even declared as int, it's an object, and it has methods
print('=' * 20)
# CLASS INHERITANCE
class MyClass:
pass
c = MyClass()
print('c is type:', type(c))
print('=' * 20)
# Type METACLASS
# Object is a class that inherits from its metaclass: type
print('type of object is:', type(object))
print('MyClass is type:', type(MyClass))
print('int/float/list... are type:', type(int)) # Absolutely all types of variables
print('type is type:', type(type)) # Circular reference, type instantiates itself
# SUMMARY: all objects inherit from object() class, and all classes (including object()) inherit
# from type() metaclass
|
87ff6b870907894747363818f91d236c02aef60c | bhawanabhatt538/seaborn | /box_plot.py | 1,434 | 3.703125 | 4 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
tips=sns.load_dataset('tips')
print(tips)
print(tips.head())
#let's looking at a single horizontal box plot for let's say size
sns.boxplot(x=tips['size'])
plt.show()
sns.boxplot(x=tips['total_bill'])
plt.show()
#box plot for two variables
sns.boxplot(x='sex',y='total_bill',data=tips)
plt.show()
#box plot for day versus total bill
sns.boxplot(x='day',y='total_bill',data=tips)
plt.show()
#we can also combine these two box by passing hue
sns.boxplot(x='day',y='total_bill',data=tips,hue='sex')
plt.show()
#now we have data for each day ,for each day we have male and female and can change the color of this by passing palette attribute
sns.boxplot(x='day',y='total_bill',data=tips,hue='sex',palette='husl')
plt.show()
sns.boxplot(x='day',y='total_bill',data=tips,hue='time')
plt.show()
#use attribute order and pass the day in such an order that we want
sns.boxplot(x='day',y='total_bill',data=tips,order=['Sun','Fri','Thur','Sat'])
plt.show()
#use palette attribute to change the color
sns.boxplot(x='day',y='total_bill',data=tips,order=['Sun','Fri','Thur','Sat'],palette='husl')
plt.show()
iris=pd.read_csv("../datafile/IRIS.csv")
print(iris)
sns.boxplot(data=iris,palette='coolwarm')
plt.show()
sns.boxplot(x='day',y='total_bill',palette='husl')
sns.swarmplot(x='day',y='total_bill',data=tips)
plt.show()
|
54571d70114e72fc3b5f41e4bb08e99a89b7b61e | ChrisMay1/project-304 | /Casino/roullette.py | 1,204 | 3.546875 | 4 | import numpy as np
import math
import random as rand
import matplotlib.pyplot as plt
period = 1000
times = 100
initial = 100.0
bank = initial
results = []*period
bet = 5.0
j = 0
while j <= period:
array = [1]*times
for i in range(times):
array[i] = rand.randint(0,37)
# ~ print j, 'Round'
a = 0.0
b = 0.0
c = 0.0
d = 0.0
for i in range(len(array)):
if bank <= 0:
break
if array[i] >= 1 and array[i] <= 12: #win
a = a + 1
bank = bank + bet
if array[i] > 12 and array[i] <= 24: #win
b = b + 1
bank = bank + bet
if array[i] >= 25 and array[i] <= 36: #loss
c = c + 1
bank = bank - 2*bet
if array[i] == 0 or array[i] == 37:
bank = bank - 2*bet
d = d + 1
results.append((bank/initial-1)*100)
bank = initial
j = j + 1
positive = 0.0
negative = 0.0
for i in range(len(results)):
if results[i] > 0:
positive = positive + 1
else:
negative = negative + 1
print positive, negative
print 'made money percentage: ', positive/period*100
print 'lost money percentage: ', negative/period*100
t = np.arange(0,len(results),1)
plt.bar(t, results)
plt.title("Monte Carlo Roullette")
plt.xlabel("Trial #")
plt.ylabel("Return Percent %")
plt.show()
|
14fe07617dbd7e63cd3275c64681d68a94a41245 | mistrydarshan99/Leetcode-3 | /interviews/linked_list/133_clone_graph.py | 779 | 3.515625 | 4 | # Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
nodes = {}
def clone_node(node):
if not node:
return None
if node.label in nodes:
return nodes[node.label]
cnode = UndirectedGraphNode(node.label)
nodes[node.label] = cnode
cnode.neighbors = [clone_node(neighbor) for neighbor in node.neighbors]
# for neighbor in node.neigbors:
# clone_node(neighbor)
return cnode
return clone_node(node)
|
02b5938a6b8760b746a0fc161d8b5d82b4d59c17 | csdotson/Data_Structures_Algorithms | /binary_trees/tree_traversal.py | 554 | 3.859375 | 4 | """ Binary Tree Traversal functions """
def in_order_traversal(root):
if root:
in_order_traversal(root.left)
print('Inorder: {}'.format(root.data))
in_order_traversal(root.right)
def pre_order_traversal(root):
if root:
print('Preorder: {}'.format(root.data))
pre_order_traversal(root.left)
pre_order_traversal(root.right)
def post_order_traversal(root):
if root:
post_order_traversal(root.left)
post_order_traversal(root.right)
print('Postorder: {}'.format(root.data)) |
df798bc8e32098ff1b92706ed5f084ee0e284de8 | pjpalaaash/Python-programs | /Reversed Sentence.py | 122 | 3.984375 | 4 | inp = input("Enter the String: ")
temp = inp.split(" ")
print(temp)
sentence = " ".join(reversed(temp))
print(sentence) |
5cf031799e0a02f59381725f9a2d98cd9ada7d41 | dhyeypatelsatyam/class-104 | /Project.py | 561 | 3.5625 | 4 | import pandas as pd
import csv
import plotly_express as px
with open("class2.csv",newline="") as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
total_marks=0
total_entres=len(file_data)
for marks in file_data:
total_marks+=float(marks[1])
mean=total_marks/total_entres
print("Mean (Average) is -> "+str(mean))
df=pd.read_csv("class2.csv")
fig=px.line(df,y="Marks",x="Student Number")
fig.update_layout(shapes=[
dict(
type="line",
y0= mean, y1= mean,
x0= 0, x1= total_entres
)
])
fig.show() |
7670c6b2df6605bf913af6433eb1f96cada2b0a7 | annahiller1992/CompPhylo17 | /Assignment3.py | 6,677 | 4.15625 | 4 | #!/usr/bin/env python3
#Anna E. Hiller
#Assignment 3, Feb. 22 2017
#1. Import
# Importing the binomial and uniform classes from the stats module of the scipy library
from scipy.stats import binom, uniform
# Importing pseudo-random number generators for uniform and Gaussian distributions
from random import random, gauss
#2. Define some data - Binomial
# Defining the data
flips = ["H","T","T","T","H"]
n = len(flips)
k = sum([1 for fl in flips if fl == "H"])
#3. Define a function to calculate a likelihood, if p<0 or p>1
def like(k, n, p, testingPrior=False):
"""function to call a likelihood"""
if testingPrior:
return 1
if p < 0:
return 0
elif p > 1:
return 0
else:
return binom.pmf(k, n, p)
#4. Define a function to calculate a prior probability
# Defining function to calculate prior density - uniform [0,1]
def prior(p):
"""function to calculate a prior probability"""
return uniform.pdf(p)
# Defining function to calculate the unnormalized posterior density
def post(k, n, p):
"""function to calculate the unnormalized posterior density"""
posterior = prior(p) * like(k, n, p)
return posterior
#5. Define a function to draw a new value for the parameter(s) of interest using
# a proposal distribution
#import numpy
import numpy as np
def draw(n, p, sim):
"""function to draw a new value of a parameter from a proposal distribution"""
# n = number of trials, p = probability of each trial
# sim = number of simulations, output
value = [np.random.binomial(n, p, sim)] #proposal distribution is binomial
# result of simulating (k successes), tested x times (sim)
print (value)
#From: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html
#6. Define a function to accept or reject proposed moves based on the ratio of
# their posterior densities.
#propose a new value (i.e., draw it from your proposal distribution)
#calculate the posterior probability (or probability density) of your proposed state
#calculate the posterior probability (or probability density) of your current state
#take their ratio
def reject(k, n, p):
"""function to accept or reject proposed moves based on the ratio of their
posterior densities"""
#propose a new value, simulated 10 times as default
diff = 0.1
listMCMC = []
for k in value: #draw value from proposal distribution
#calc posterior probability
p_curr = post(k, n, p)
p_proposed = post(k, n, (p_curr + diff)
p_accept = p_proposed/p_current
if p_accept >= 1
print("accept")
listMCMC.append(p_proposed)
if p_accept <1
print("accept sometimes")
if np.random.rand() < p_accept:
print("accept")
listMCMC.append(p_proposed)
else:
print("reject")
if accept:
p_curr = p_proposed
#From: http://twiecki.github.io/blog/2015/11/10/mcmc-sampling/
#based on the rules defined for MCMC
#accept the proposal and add it to the chain
#or stay where you are
#7. Create lists to store parameter values, prior probabilities, likelihoods,
# and posterior densities.
class values(object):
def __int__ (self,n_trials,p_prob,k_success,prior_prob,like, post_den):
#OR
listMCMC = []
listMCMC.append(n, p, k, prior, like, post)
#8. Define a function to run the chain! Begin by defining starting conditions for
# the Markov chain, including the number of generations it will run, the
# starting parameter value(s), and the starting posterior density
# (unnormalized). Use a for loop to iterate through the specified number of
# generations. Each step will involve proposing new values, deciding whether
# to accept or reject those values, then recording the new value. It can be very
#cumbersome and unnecessary to record _every_ parameter value that's sampled.
#How could you write out values every n-th generation?
#define starting conditions for Markov Chain: number of generations run, starting
#parameter values, starting posterior density (arguments are # generations, lists to
#store values, etc.)
def MCMC(n_trials, p_prob, generations, lists):
"""function to run a Markov Chain"""
#use a for loop to iterate through the number of generations
for i in
#each step: (1) propose new value, (2) decide to accept or reject,
#(3) and record new value
reject (n, p)
listMCMC = []
listMCMC.append(values)
#I'm confused about how this is different from the accept/reject function above!? Also,
#what do you mean by write out values every n-th generation!?!
#9. Create trace plots of parameter values, priors, likelihoods, and posteriors.
import numpy as np
import matplotlib.pyplot as plt
posterior = sampler() #from above
x = plt.subplot()
x.plot(posterior)
From: http://twiecki.github.io/blog/2015/11/10/mcmc-sampling/
#10. Create histograms of parameter values, priors, likelihoods, and posteriors.
x = plt.subplot()
sns.distplot function
#Since we never went over how to plot in class I have no idea how to make this work.
#I googled a few things and included the plot calls I think are needed.
"""
Now use the code you've written above to explore answers to these questions.
Ideally, the code you've written is sufficiently generic, so you can simply
call the code above with different arguments. This will make it much easier to
remember the conditions you explored. If you write this assignment in a
Jupyter notebook, you can also include the answers as comments, plots, etc.
(1) How does the size of the proposal distribution affect the efficiency of
the chain? Try a very small distribution, a very large one, and one that
seems like it should be about the width of the posterior peak.
(2) How long does it take for the chain to "burn in"? Try this with different
proposal distributions and datasets of different sizes.
(3) Define a dataset where the values could be draws from a Normal. Have the
chain explore the joint posterior distribution for both the mean and the
standard deviation. Remember that you'll need to include proposals that
change both parameter values. What happens when the starting values for one
or both parameters are very far away from the peak of the posterior? Try
plotting the two parameter values from each generation against each other.
Do they seem correlated?
(4) How confident are you that you've sampled the posterior distribution well?
What strategies can you use to make sure? Can you run multiple, independent
analyses using the code you wrote above?
"""
#I have no idea how to test these questions without a working MCMC sampler. Help!?
|
938db5e02f8b7237b5acc5f0db2880ae36da145f | gargi98/Introduction-Programming-Python | /string variable/stringConcatenate.py | 143 | 3.984375 | 4 | # + concatenates two string
firstname='Gargi'
lastName='Mukhopadhyay'
print(firstName+lastName)
print('My name is '+firstName+' '+lastName)
|
10c768e12f9c6b6a2720018250554eaca8a2779f | xiaoliangge12x/MyLearningCodeLocal | /pythonCode/HashTableApp.py | 331 | 3.78125 | 4 | # Hash Table application, Avoid repetition
voter = {} # Creat a hash table
def votedPerson(name):
if voter.get(name):
print "Kick out!"
else:
voter[name] = True
print "Welcome "+name+" Vote!"
votedPerson("Mike")
votedPerson("Bright")
votedPerson("Bright")
votedPerson("Jimmy")
votedPerson("Mike") |
e37ba19d73faa0bf3618ea6d72481ce237b38d3d | CodedQuen/Python-by-Example | /maths/c29.py | 244 | 4.1875 | 4 | #Challenge29
'''Ask the user to enter an integer that is over 500. Work
out the square root of that number and display it to two
decimal places.'''
import math
num=math.sqrt(int(input('Enter number greater than 500')))
print(f'{num:.2f}') |
e9f4e7c06bec59993ff70c55d38d298f090a2dd9 | deepti-rathore01/python-first-step | /chapter-3/src/join_string.py | 220 | 3.5 | 4 | """
@file : join_string.py
@brief:Convert all list elements as single word like '123456' from [1, 2, 3, 4, 5, 6]
"""
list1 = ['1', '2', '3']
str1 = ''.join(list1)
print " all list element as single word", str1
|
93ea692824bdb2f5a5e3f6cb289314d6987ad110 | jxvo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 466 | 3.78125 | 4 | #!/usr/bin/python3
"""Advanced Task 15"""
def append_after(filename="", search_string="", new_string=""):
"""opens a file, and inserts a string where match is found"""
with open(filename, "r+") as txt_file:
lines = []
for line in txt_file:
lines.append(line)
if search_string in line:
lines.append(new_string)
with open(filename, "w+") as txt_file:
txt_file.write("".join(lines))
|
8bbed7b91f5aa24b6d5fab2458f1e8288f79f137 | geekyhackergokulcharade/rockhacktober-2021 | /py2 | 1,461 | 3.890625 | 4 | # Import the required libraries:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
# Read the CSV file:
data = pd.read_csv(“Fuel.csv”)
data.head()
# Consider features we want to work on:
X = data[[ ‘ENGINESIZE’, ‘CYLINDERS’, ‘FUELCONSUMPTION_CITY’,’FUELCONSUMPTION_HWY’,
‘FUELCONSUMPTION_COMB’,’FUELCONSUMPTION_COMB_MPG’]]
Y = data[“CO2EMISSIONS”]
# Generating training and testing data from our data:
# We are using 80% data for training.
train = data[:(int((len(data)*0.8)))]
test = data[(int((len(data)*0.8))):]
#Modeling:
#Using sklearn package to model data :
regr = linear_model.LinearRegression()
train_x = np.array(train[[ ‘ENGINESIZE’, ‘CYLINDERS’, ‘FUELCONSUMPTION_CITY’,
‘FUELCONSUMPTION_HWY’, ‘FUELCONSUMPTION_COMB’,’FUELCONSUMPTION_COMB_MPG’]])
train_y = np.array(train[“CO2EMISSIONS”])
regr.fit(train_x,train_y)
test_x = np.array(test[[ ‘ENGINESIZE’, ‘CYLINDERS’, ‘FUELCONSUMPTION_CITY’,
‘FUELCONSUMPTION_HWY’, ‘FUELCONSUMPTION_COMB’,’FUELCONSUMPTION_COMB_MPG’]])
test_y = np.array(test[“CO2EMISSIONS”])
# print the coefficient values:
coeff_data = pd.DataFrame(regr.coef_ , X.columns , columns=[“Coefficients”])
coeff_data
#Now let’s do prediction of data:
Y_pred = regr.predict(test_x)
# Check accuracy:
from sklearn.metrics import r2_score
R = r2_score(test_y , Y_pred)
print (“R² :”,R)
|
17b6dfa3da0e324572cb14e8174a5e9c9a188864 | tusharmverma/PythonPractice | /cpFunctionsTempConvert.py | 3,752 | 4.25 | 4 | #*******************************************************************************
#
# Computer Science 1114
#
# Fall 2017
#
# Assignment: cpFunctionsTempConvert.py
#
# Due Date: Monday October 04 2017
#
# Instructor: Ms. Nancy Draganjac
#
# Programmer: Tushar Verma
#
# Description: Getting the input of Celcius, Fahrenheit, Kevin and convert each
# temperature in to the other two temperature scales
#
# Input: Get three temperatures from user in Celcius, Fahrenheit, Kelvin
#
# Output: Printing the table of Temperatures on the screen
#
#*******************************************************************************
# celciusToFah
#
# description: Converting temperature from Celcius to Fahrenheit
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperature in Celcius
#
# returns: result - Temperature in Fahrenheit
#
def celciusToFah(temp):
result = (temp * 1.8) + 32 #formula to convert celcius to Fahrenheit
return result
# celciusToKel
#
# description: Convert the temperature from Celcius to Kelvin
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperature in Celcius
#
# returns: Temperature in Kelvin
#
def celciusToKel(temp):
result = temp + 273.15 #formula to convert form Celcius to kelvin
return result
# fahToCelcius
#
# description: Convert the temperature from Celcius to Kelvin
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperature in Celcius
#
# returns: Temperature in Celcius
#
def fahToCelcius(temp):
result = (temp - 32)/1.8 #formula to convert from
#fahrenheit to celcius
return result
# kelToCelcius
#
# description: From the temperature in Kevin convert it
# to Celcius
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperature in Kelvin
#
# returns: Temperature in Celcius
#
def kelToCelcius(temp):
result = temp - 273.15 #formuala to convert
#from kelvin to celcius
return result
# fahToKelvin
#
# description: We convert fahrenheit to kelvin by first
# converting from Fahrenheit to celcius then
# calling fahToCelciius function for converting to kelvin
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperatur in Fahrenheit
#
# returns: result - Temperature in Kelvin
#
def fahToKelvin(temp):
tempresult = fahToCelcius(temp) #Calling function to to get
#value from fahreheit to celcius
result = celciusToKel(tempresult) #Calling function to get
#celcius converted to kelvin
return result
# kelvinToFah
#
# description: Converting the temperature from kelvin to fahrenheit
#
# input: N/A
#
# output: N/A
#
# parameters: temp - Temperature in Kelvin
#
# returns: result - Temperature in Fahrenheit
#
def kelvinToFah(temp):
result = (temp * (9/5)) - 459.67 #formula to convert into Fahrenheit
return result
tempInCelcius = float(input("Enter the temperature in Celcius: "))
tempInFah = float(input("Enter the temperature in Fahrenheit: "))
tempInKel = float(input("Enter the temperature in Kelvin: "))
print("{:>10} {:>15} {:>15}".format("Celcius","Fahrenheit","Kelvin"))
print("{:>10,.2f} {:>15,.2f} {:>15,.2f}".
format(tempInCelcius,celciusToFah(tempInCelcius),celciusToKel(tempInCelcius)))
print("{:>10,.2f} {:>15,.2f} {:>15,.2f}"
.format(fahToCelcius(tempInFah),tempInFah,fahToKelvin(tempInFah)))
print("{:>10,.2f} {:>15,.2f} {:>15,.2f}"
.format(kelToCelcius(tempInKel),kelvinToFah(tempInKel),tempInKel))
|
bce2833a56505d2f61d6f2cb5d5e32348a2d4f35 | pepinu/practise | /CA/Azimuth at Treasure Island.py | 907 | 3.640625 | 4 | from math import sin as s, cos as c, radians as r
class Azimuth(object):
def __init__(self):
self.directions = []
while 1:
try:
self.directions.append(raw_input().split())
except:
break
@staticmethod
def get_x(d, az):
X = d * s(r(az))
return X
@staticmethod
def get_y(d,az):
Y = d * c(r(az))
return Y
def solve(self):
result = [0, 0]
d = [int(dire.split()[1]) for dire in self.directions[1:-1]]
az = [int(dire.split()[5]) for dire in self.directions[1:-1]]
for i in range(len(d)):
result[0] += self.get_x(d[i], az[i])
result[1] += self.get_y(d[i], az[i])
result[0] = int(round(result[0]))
result[1] = int(round(result[1]))
return ' '.join(map(str, result))
print Azimuth().solve()
|
f5952497c777190f9d674d7b1afce76be4f607da | SONGJAEYEON/CodingTest_Python | /CodingTest/Algorithm/Recursion.py | 1,926 | 3.59375 | 4 | #재귀
# 재귀적 DFS
def recurse(graph, start, answer, path, input_start):
print("\n시작 노드: ", start)
path.append(start)
print("현재 path: ", path)
cands = []
# 갈 수 있는 노드 찾기
for i in range(len(graph[start])):
if i != start and graph[start][i] == 1:
cands.append(i)
# 갈 수 있는 노드가 없다면, 현재까지의 path를 answer의 원소로 저장하고, return하는 것으로 종료
if not cands:
path_copy=path.copy()
answer.append(path_copy)
# answer.append(copy.deepcopy(path))
print("끝자락에 도착해서 종료, answer: ", answer)
print("빠질 노드: ", path.pop())
print("path: ", path)
return
# 갈 수 있는 노드가 있다면, 그 노드로 가는 경로에 해당하는 graph의 원소를 0으로 바꾸고, 재귀 호출
else:
print("후보노드: ", cands)
while cands:
cand = cands.pop(0)
graph[start][cand] = 0
graph[cand][start] = 0
recurse(graph, cand, answer, path, input_start)
# 반복이 끝났다는 것은 해당 노드에서 더이상 갈 수 있는 노드가 없다는 뜻. 따라서 path에서 pop한다.
print("반복 끝나고 빠질 노드: ", path.pop())
def dfs_recursive(graph, input_start):
path = []
answer = []
start = input_start
recurse(graph, start, answer, path, input_start)
return answer
graph = [[0, 1, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0]]
start = 1
# print("\n재귀 DFS 정답: ", dfs_recursive(graph, start))
|
6f788fb3c1385ba0444b18a8404af4a12e82a162 | mpyrek/ASD | /lab 4/split_two_list_without_pointer.py | 1,375 | 3.671875 | 4 | #rozdzielmy dwie listy bez wartownika na przyste i nieparzyste
class Node:
def __init__(self,val):
self.next=None
self.val=val
A=Node(2)
B=Node(3)
C=Node(1)
D=Node(4)
E=Node(11)
F=Node(13)
G=Node(6)
H=Node(1)
I=Node(2)
A.next=B
B.next=C
C.next=D
D.next=E
E.next=F
F.next=G
G.next=H
H.next=I
def split(head):
head_odd=None
head_even=None
if head.val%2==1:
head_odd=head
head=head.next
h_o=head_odd
while head.val%2==1:
h_o.next=head
h_o=h_o.next
head=head.next
else:
head_even=head
head=head.next
h_e=head_even
while head.val%2==0:
h_e.next=head
h_e=h_e.next
head=head.next
if head_even==None:
head_even=head
h_e=head_even
head=head.next
else:
head_odd=head
h_o=head_odd
head=head.next
while head:
if head.val%2==0:
h_e.next=head
h_e=h_e.next
else:
h_o.next=head
h_o=h_o.next
head=head.next
h_e.next=None
h_o.next=None
return ((head_even,head_odd))
h1,h2=split(A)
while h1:
print(h1.val)
h1=h1.next
print("nowe")
while h2:
print(h2.val)
h2=h2.next
|
cdf02b6042085cc3d111431d10d292ea1fe9a3c9 | BrightAdeGodson/submissions | /CS1101/tryme3.py | 864 | 4.21875 | 4 | #!/usr/bin/python3
"""
Print 25 new lines
"""
def new_line():
"""Print a new line"""
print()
def three_lines():
"""
Print 3 new lines using new_line()
new_line() * 3 = 3 new lines
"""
new_line()
new_line()
new_line()
def nine_lines() -> str:
"""
Print 9 new lines using three_lines()
three_lines() * 3 = 9 new lines
"""
print('now printing 9 lines')
for _ in range(3):
three_lines()
def clear_screen():
"""
Print 25 new lines using nine_lines(), three_lines() and new_line()
nine_lines() * 2 = 18 new lines
three_lines() * 2 = 6 new lines
new_line() = 1 new line
18 + 6 + 1 = 25 new lines
"""
print('now printing 25 lines')
for _ in range(2):
nine_lines()
for _ in range(2):
three_lines()
new_line()
return
clear_screen()
|
f468bafe0c993a6162948471749f6f59eae82e77 | lllz/PythonExercises | /dice.py | 392 | 3.984375 | 4 | import random
def dice():
number = random.randint(1,6)
print ("Welcome to the game!")
print (number)
next = input("Do you want to roll the dice again ")
while next == "yes":
number = random.randint(1, 6)
print(number)
next = input("Do you want to roll the dice again ")
else:
print ("Game over")
if __name__=="__main__":
dice()
|
8a2a0a53b81de62794413652c411dcb92420c71c | zoomjuice/CodeCademy_Learn_Python_3 | /Unit 03 - Functions/03_01_Challenge-FunctionChallenges2.py | 1,509 | 4.125 | 4 | def first_three_multiples(num):
print(num, num * 2, num * 3)
return num * 3
# Uncomment these function calls to test your first_three_multiples function:
first_three_multiples(10) # should print 10, 20, 30, and return 30
first_three_multiples(0) # should print 0, 0, 0, and return 0
def tip(bill, percentage):
return bill * (percentage / 100)
# Uncomment these function calls to test your tip function:
print(tip(10, 25)) # should print 2.5
print(tip(0, 100)) # should print 0.0
def introduction(name_first, name_last):
intro_string = name_last + ", " + name_first + " " + name_last
return intro_string
# Uncomment these function calls to test your introduction function:
print(introduction("James", "Bond")) # should print Bond, James Bond
print(introduction("Maya", "Angelou")) # should print Angelou, Maya Angelou
def dog_years(name, age):
return "{}, you are {} years old in dog years".format(name, age * 7)
# Uncomment these function calls to test your dog_years function:
print(dog_years("Lola", 16)) # should print "Lola, you are 112 years old in dog years"
print(dog_years("Baby", 0)) # should print "Baby, you are 0 years old in dog years"
def lots_of_math(a, b, c, d):
print(a + b)
print(c - d)
print((a + b) * (c - d))
return ((a + b) * (c - d)) % a
# Uncomment these function calls to test your lots_of_math function:
print(lots_of_math(1, 2, 3, 4)) # should print 3, -1, -3, 0
print(lots_of_math(1, 1, 1, 1)) # should print 2, 0, 0, 0
|
376d4789d40c489af45313c249974da0d9ecc58b | learnpython101/PythonFundamentals | /Module 02/Methods/01 Index.py | 1,862 | 4.25 | 4 | """"""
"""
The index() method returns the index of the specified element in the list.
Syntax of the list index() method is:
list.index(element, start, end)
list index() parameters
The list index() method can take a maximum of three arguments:
element - the element to be searched
start (optional) - start searching from this index
end (optional) - search the element up to this index
Return Value from List index()
The index() method returns the index of the given element in the list.
If the element is not found, a ValueError exception is raised.
Note: The index() method only returns the first occurrence of the matching element.
"""
# Example 1: Find the index of the element
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print(f'The index of e:{index}')
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print(f'The index of i:{index}')
# Example 2: Index of the Element not Present in the List
# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']
# index of'p' is vowels
index = vowels.index('p')
print(f'The index of p:{index}')
# Example 3: Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
"""
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
# Negative indexing in lists
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
""" |
be257a076a3d07495ecc5c06e0c26870f8688d87 | Meghnakrishnan/programming-lab | /6.file_extnsn.py | 243 | 4.15625 | 4 | #python program to accept a filename from the user, print extension of that
a=input("enter a filename:")
b=a.split(".")
ext=b[-1]
print("extension of filename is",ext)
#output
enter a filename:area.py
extension of filename is py
|
6c36828d9ae6a5a04d74b8f6f4b475230465404f | Minji0h/Introduce-at-CCO-with-python | /Semana4/exercicio4.py | 452 | 3.96875 | 4 | # Escreva um programa que receba um número inteiro positivo na entrada e verifique se é primo. Se o número for primo, imprima "primo". Caso contrário, imprima "não primo".
# Exemplos:
# Digite um número inteiro: 11
# primo
# Digite um número inteiro: 12
# não primo
n = int(input("Digite um numero: "))
primo = True
i = 2
while(i <= n//2):
if n%i == 0: primo = False
i = i + 1
if primo:
print("primo")
else:
print("não primo")
|
fed1603862189ffebaaa1ba5b499f6cb619ac79c | wangjinlong9788/PythonTest | /makecandies/makecandies.py | 3,972 | 3.921875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumPasses function below.
"""def minimumPasses(m, w, p, n):
ps=1
n0=m*w
if n0>=n:
return ps
while n0+(m)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
mwpn = input().split()
m = int(mwpn[0])
w = int(mwpn[1])
p = int(mwpn[2])
n = int(mwpn[3])
result = minimumPasses(m, w, p, n)
fptr.write(str(result) + '\n')
fptr.close()
"""
#Greedy Algorithm Approach
### IMPORTS ###
from math import ceil
### FUNCTIONS ###
def Purchaser(Machine,Worker,count):
#idea behind count > remainder loop below:
#we want to spend all of our money in each round (greedy) because #in the next round it will have a higher multiplier effect on count.
#optimally, to get the most "bang for our buck" we would want Machine == Workers because this gives the highest count.
#Given that the two numbers are equal, we would want to increment #them evenly. If the amount of SpendingMoney is not even, then
#Without loss of generality we can give it to one of the factors (either Machine's or Worker's).
SpendingMoney = count//Price
remainder = count%Price
while count > remainder:
if Machine < Worker:
diff = Worker - Machine
if diff >= SpendingMoney:
Machine += SpendingMoney
count = remainder
break
else:
Machine += diff
SpendingMoney -= diff
count -= Price*diff
elif Worker < Machine:
diff = Machine - Worker
if diff >= SpendingMoney:
Worker += SpendingMoney
count = remainder
break
else:
Worker += diff
SpendingMoney -= diff
count -= Price*diff
else:
if SpendingMoney % 2 == 0:
Worker += SpendingMoney//2
Machine += SpendingMoney//2
count = remainder
break
else:
Worker += SpendingMoney//2
Machine += SpendingMoney//2 + 1
count = remainder
break
return Machine,Worker,count
def MinResource(counter, count, Candy, Machine, Worker, minimum):
#Checks the number of resources needed to generate our solution at this point
#We use ceiling because there are no partial iterations
RawIteration = counter + ceil((Candy - count) / (Machine * Worker))
if minimum > RawIteration:
minimum = RawIteration
return minimum
def IteratorMatcher(Machine,Worker,counter,count):
CounterAdder = ceil((Price - count)/(Machine * Worker))
countAdder = CounterAdder * (Machine*Worker)
return counter + CounterAdder, count + countAdder
# ======Inputs======
#Machine: the number of machines
#Worker: the number of workers
#Price: the price of buying one machine or hiring one worker
#Candy: the number of candies Karl must make
### INPUTS ###
Machine, Worker, Price, Candy = map(int,input().split())
count, counter = 0, 1
minimum = 1e12
### TRANSFORMATION ###
while count < Candy:
count += Machine * Worker
minimum = MinResource(counter, count, Candy, Machine, Worker, minimum)
#The code will not conventionally exit the loop because we spend all of our resources after each round
#Therefore we need to add this break short-circuit
if count >= Candy:
break
counter, count = IteratorMatcher(Machine,Worker,counter,count)
Machine,Worker,count = Purchaser(Machine,Worker,count)
#After we have spent all of the candies we have created, its time to increment our counter for the next round
counter += 1
### OUTPUT ###
print(min(counter,int(minimum)))
|
d820b4bf190d3c27d374010ce9ea7e057cb2fb65 | Sweetkubuni/python_search_keyword | /search_keyword.py | 609 | 3.859375 | 4 | import xml.etree.ElementTree as etree
def search(keyword):
tree = etree.parse('entries.xml')
root = tree.getroot()
matches = []
for child in root:
if keyword in child.text:
matches.append((child.text,len(child.text.split())))
if len(matches) is 0:
print("\nNo entries found\n")
else:
print("\n")
sorted_matches = sorted(matches, key=lambda match: match[1])
for m in sorted_matches:
print( m[0] + "\n")
def main():
keyword = input("please enter keyword:")
search(keyword)
if __name__ == "__main__":
main()
|
46ec4767ee7d79cbb5c0db5bedf2a750d484f706 | feng-yu/june-2019 | /june2019/june29.py | 1,076 | 3.796875 | 4 | """
[Hard]
Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k.
If such a subset cannot be made, then return null.
Integers can appear more than once in the list. You may assume all numbers in the list are positive.
For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24.
"""
def find_set(li, k):
if li:
li.sort()
result = []
if k in li:
result.append(k)
return result
if k < li[0]:
result.clear()
else:
for i in li:
sub_li = li.copy()
sub_li.remove(i)
sub_result = find_set(sub_li, k-i)
if sub_result:
result.append(i)
for sub_i in sub_result:
result.append(sub_i)
return result
else:
result.clear()
data = [12, 1, 61, 5, 9, 2]
data1 = [1, 2, 12]
k = 27
re = find_set(data, k)
print(re) |
5c4d6cf06c06ab69f7772590f49ddec307a95c05 | AP-MI-2021/lab-3-EcaterinaCnt | /main.py | 8,788 | 3.890625 | 4 | def is_palindrome(n):
'''
Determina daca un numar este palindrom
:param n: numarul introdus
:return: returneaza valoarea de adevar
'''
cifre_n=[]
while n > 0:
cifre_n.append(n%10)
n=n//10
lungime=len(cifre_n)
for i in range (0,lungime//2):
if cifre_n[i]!=cifre_n[lungime-1-i]:
return False
return True
def test_is_palindrome():
'''
Determina daca un numar este palindrom
:return: returneaza True daca acesta este palindrom, iar False in caz contrar
'''
assert is_palindrome(7557) is True
assert is_palindrome(15) is False
assert is_palindrome(1221) is True
assert is_palindrome(0) is True
def get_palindrom(lst):
'''
Determina numerele palindrom dintr o lista
:param lst: lista de numere intregi
:return: returneaza o lista cu numere palindrom din lst
'''
result = []
for num in lst:
if is_palindrome(num):
result.append(num)
return result
def toate_nr_sunt_palindrom(l):
'''
Determina daca toate numerele dintr o lista sunt prime
:param l: lista de numere intregi
:return: returneaza True daca toate numerele din lista sunt palindrom, si False daca nu
'''
for x in l:
if is_palindrome(x) is False:
return False
return True
def test_toate_nr_sunt_palindrom():
'''
Determina daca toate numerele din lista sunt palindroame
:return: returneaza True daca toate numerele sunt palindroame, iar False in caz contrat
'''
assert toate_nr_sunt_palindrom([1221, 111, 3113]) is True
assert toate_nr_sunt_palindrom([2332, 545, 1001]) is True
assert toate_nr_sunt_palindrom([123, 2332, 545]) is False
def div_count(n):
'''
Numara numarul de divizori ai unui numar
:param n: numarul intreg introdus
:return: returneaza numarul de divizori ai numarului introdus
'''
d=0
for i in range(1,(int)(n ** 0.5) + 1):
if n%i == 0:
if n/i == i:
d=d+1
else:
d=d+2
return d
def test_div_count():
'''
Determina numarul de divizori ai unui numar
:return:d- unde acesta este numarul de divizori
'''
assert div_count(12) == 6
assert div_count(6) == 4
assert div_count(13) == 2
def numar_inversat(num):
'''
Determinam inversul fiecarui numar
:param num: numarul intreg introdus
:return: returneaza inversul acestuia
'''
invers=0
while num:
invers = invers * 10 + num % 10
num //= 10
return invers
def test_numar_inversat():
'''
Testeaza inversele unor numere citite
:return: returneaza inversul numarului introdus
'''
assert numar_inversat(121) == 121
assert numar_inversat(1234) == 4321
assert numar_inversat(111) == 111
def is_prime(n):
'''
Functia determina daca un numar este prim
:param n: numarul intreg introdus
:return: returneaza True daca este prim, iar False in caz contrar
'''
if n<2:
return False
for d in range(2, n):
if n%d==0:
return False
return True
def test_is_prime():
'''
Testeaza daca numerele introduse sunt prime
:return: returneaza True daca verifica proprietatea, iar False in caz contrar
'''
assert is_prime(2) is True
assert is_prime(100) is False
assert is_prime(13) is True
def is_digit_prime(n):
'''
Determina daca un numar are toate cifrele prime
:param n: un numar intreg, pozitiv
:return: returneaza True daca acesta are toate cifrele prime, False in caz contrar
'''
while n>0:
if is_prime(n%10)==False:
return False
n=n//10
return True
def get_longest_same_div_count(lst: list[int]) -> list[int]:
'''
Determinacea mai lunga subsecventa de numere care au acelasi numar de divizori
:param lst: lista de numere intregi
:return: returneaza cea mai lunga subsecventa de numere care respecta proprietatea
'''
n = len(lst)
result=[]
for st in range(n):
for dr in range (st, n):
d=div_count(lst[st])
for num in lst[st: dr+1]:
if div_count(num)!=d:
d=-1
break
if (d!=-1):
if dr-st+1>len(result):
result=lst[st: dr+1]
return result
def test_longest_same_div_count():
'''
Determina cea mai lunga subsecventa de numere cu acelasi numar de divizori
:param lst: lista introdusa
:return: returneaza subsecventa cea mai lunga care satisface proprietatea
'''
assert get_longest_same_div_count([2, 2, 2, 2]) == [2, 2, 2, 2]
assert get_longest_same_div_count([0]) == [0]
assert get_longest_same_div_count([1, 4, 9, 3, 5, 7, 9, 11]) == [3, 5, 7]
def get_longest_subarray_nr_palindrom(lst: list[int]) -> list[int]:
'''
Determina cea mai lunga subsecventa de numere care sunt palindrom
:param lst: lista de numere intregi
:return: returneaza cea mai lunga subsecventa de numere care respecta proprietatea
'''
n = len(lst)
result = []
for st in range (n):
for dr in range (st, n):
is_palindrome = True
for num in lst[st: dr+1]:
if num != numar_inversat(num):
is_palindrome = False
break
if is_palindrome :
if dr-st+1>len(result):
result=lst[st: dr+1]
return result
def test_longest_subarray_nr_palindrom():
'''
Determina cea mai lunga subsecventa de numere care au proprietatea de palindrom
:return: returneaza cea mai lunga subsecventa cu proprietatea ceruta
'''
assert get_longest_subarray_nr_palindrom([121, 122, 1331, 141, 234 ]) == [1331, 141]
assert get_longest_subarray_nr_palindrom([1, 121, 41]) == [1, 121]
assert get_longest_subarray_nr_palindrom([121, 1331, 23432, 454, 1551]) == [121, 1331, 23432, 454, 1551]
def get_longest_prime_digits(lst: list[int]) -> list[int]:
'''
Determina daca toate numerele sunt formate din cifre prime
:param lst: lista de numere intregi, pozitive
:return: returneaza cea mai lunga subsecventa de numere care au cifrele prime
'''
lungime = len(lst)
result =[]
for st in range(lungime):
for dr in range(st, lungime):
all_digit_prime=True
for numar in lst[st:dr+1]:
if is_digit_prime(numar) == False:
all_digit_prime=False
break
if all_digit_prime == True:
if dr-st+1>len(result):
result=lst[st:dr+1]
return result
def test_get_longest_prime_digits():
'''
Determina cea mai lunga subsecventa de numere care au toate cifrele prime din listele introduse
:return: returneaza cea mai lunga subsecventa care satisface proprietatea
'''
assert get_longest_prime_digits([12, 3, 35, 7, 24]) == [3, 35, 7]
assert get_longest_prime_digits([2, 24, 3, 32]) == [3, 32]
assert get_longest_prime_digits([2, 46, 89, 65]) == [2]
def read_list():
lst = []
lst_str = input('Dati numere separate prin spatiu: ')
lst_str_split = lst_str.split(' ')
for num_str in lst_str_split:
lst.append((int(num_str)))
return lst
def show_menu():
print("1. Citire lista: ")
print("2. Afisarea numerelor palindrom: ")
print("3. Cea mai lunga subsecventa este: ")
print("4. Cea mai lunga subsecventa este: ")
print("5. Cea mai lunga subsecventa este: ")
print("x. Exit. ")
def main():
lst = []
while True:
show_menu()
optiune=input("Alege optiunea: ")
if optiune == "1" :
lst= read_list()
print('Numerele din lista: ', lst)
elif optiune == "2" :
palindromes = get_palindrom(lst)
print('Numere palindrom din lista sunt: ', palindromes)
elif optiune == "3" :
print('Cea mai lunga subsecventa de numere palindrom este: ', get_longest_subarray_nr_palindrom(lst))
elif optiune == "4" :
print('Cea mai lunga subsecventa de numere cu acelasi numar de divizori este: ' , get_longest_same_div_count(lst))
elif optiune == "5":
print('Cea mai lunga subsecventa de numere cu toate cifrele prime este: ', get_longest_prime_digits(lst))
elif optiune == "x" :
break
else:
print("Optiune invalida.")
if __name__ == '__main__':
test_is_palindrome()
test_toate_nr_sunt_palindrom()
test_numar_inversat()
test_div_count()
test_longest_subarray_nr_palindrom()
test_longest_same_div_count()
test_get_longest_prime_digits()
main()
|
29f1d80b31713e2f6e4be77ba3c2998e0d200414 | Elshafeay/crowd-funding-console-app | /projects/searching.py | 4,607 | 3.5 | 4 | import json
from printjson import PrinterJSON
import main
from colors.utils import printing_warning, printing_error, printing_bold
from projects.CRUD import listing
from projects.utils import handle_date
def search():
while True:
print("\nThere are multiple options for search: ")
printing_bold("1-Using Title", "2-Using Date", "3-Using Target")
searching_way = input("Enter your choice number: ")
if searching_way == "1":
search_using_title()
elif searching_way == "2":
search_using_date()
elif searching_way == "3":
search_using_target()
elif searching_way.lower() == "cancel":
return
else:
printing_warning("Wrong Option!")
continue
break
def search_using_title():
title = input("Enter the keyword you wanna search for: ")
if title and not title.lower() == "cancel":
query_result = list()
p = PrinterJSON()
for project in main.projects:
if title.lower() in project["title"].lower():
query_result.append(project)
p.print_data(query_result)
print() # empty line for a better format
return
elif title.lower() == "cancel":
return
listing('all')
def search_using_target():
p = PrinterJSON()
while True:
printing_error("\n=> Leave the values blank for an open range <=")
min_target = input("Enter the minimum target of your range: ")
if min_target.lower() == "cancel":
return
max_target = input("Enter the maximum target of your range: ")
if max_target.lower() == "cancel":
return
try:
min_target = int(min_target) if min_target else 0
max_target = int(max_target) if max_target else 0
if (min_target < 0) or (max_target < 0):
printing_error("Error: Target must be a greater than Zero\n")
continue
except ValueError:
printing_error("Error: targets must have digits only!\n")
continue
if min_target and max_target:
query_result = list()
for project in main.projects:
if max_target >= project["target"] >= min_target:
query_result.append(project)
p.print_data(query_result)
return
if min_target:
query_result = list()
for project in main.projects:
if project["target"] >= min_target:
query_result.append(project)
p.print_data(query_result)
return
if max_target:
query_result = list()
for project in main.projects:
if max_target >= project["target"]:
query_result.append(project)
p.print_data(query_result)
print() # empty line for a better format
return
listing('all')
break
def search_using_date():
while True:
print("Do you wanna search by start date or end date?")
printing_bold("1-Start date", "2-End date")
chosen_key = input("Enter your choice number: ")
if chosen_key == "1":
chosen_key = "start_date"
elif chosen_key == "2":
chosen_key = "end_date"
elif chosen_key.lower() == "cancel":
return
else:
printing_error("Error: Wrong Option!\n")
continue
print("Do you wanna search by the exact date or range of dates?")
printing_bold("1-Exact date", "2-Range of dates")
chosen_way = input("Enter your choice number: ")
if chosen_way == "1":
search_exact_date(chosen_key)
elif chosen_way == "2":
search_range_date(chosen_key)
elif chosen_key.lower() == "cancel":
return
else:
printing_error("Error: Wrong Option!\n")
continue
return
def search_exact_date(date_option):
query_result = list()
p = PrinterJSON()
while True:
date_input = input("Please enter the date to be used in search [yyyy-mm-dd]: ")
date = handle_date(date_input)
if date:
break
elif date_input.lower() == "cancel":
return
for project in main.projects:
if str(date) == project[date_option]:
query_result.append(project)
p.print_data(query_result)
print() # empty line for a better format
return
def search_range_date(date_option):
query_result = list()
p = PrinterJSON()
while True:
while True:
start_date_input = input("Please enter the start date of the range [yyyy-mm-dd]: ")
start_date = handle_date(start_date_input)
if start_date:
break
elif start_date_input.lower() == "cancel":
return
while True:
end_date_input = input("Please enter the end date of the range [yyyy-mm-dd]: ")
end_date = handle_date(end_date_input)
if end_date:
break
elif end_date_input.lower() == "cancel":
return
if start_date < end_date:
break
printing_error("Error: start date can't be later than end date!\n")
for project in main.projects:
if str(end_date) >= project[date_option] >= str(start_date):
query_result.append(project)
p.print_data(query_result)
print() # empty line for a better format
return
|
ba384d829ef2a07926a8c469afb9f444fc006133 | MagaliLin/hello-python | /Game_Minion.py | 985 | 3.796875 | 4 | # Kevin and Stuart want to play the 'The Minion Game'.
# Game Rules
# Both players are given the same string,
# Both players have to make substrings using the letters of the string
# Stuart has to make words starting with consonants.
# Kevin has to make words starting with vowels.
# The game ends when both players have made all possible substrings.
# Scoring
# A player gets +1 point for each occurrence of the substring in the string
//github
def minion_game(string):
tVowel = ('A', 'E', 'I', 'O', 'U')
kevin_Sco = 0
stuart_Sco = 0
n = len(string)
for i in range(n):
if string[i:i+1] in tVowel:
kevin_Sco += n - i
else:
stuart_Sco += n - i
# print('zu' + word)
if kevin_Sco == stuart_Sco:
print('Draw')
elif kevin_Sco > stuart_Sco:
print('Kevin ' + str(kevin_Sco))
else:
print('Stuart ' + str(stuart_Sco))
if __name__ == '__main__':
s = input()
minion_game(s)
|
146f9233d0d2e9cd8183cbd6ebd1815f2570a312 | nutllwhy/Leetcode_python | /Easy/2String/9Longest_public_prefix.py | 1,078 | 3.5625 | 4 | # 最长公共前缀
# 编写一个函数来查找字符串数组中的最长公共前缀。
# 如果不存在公共前缀,返回空字符串 ""。
# 说明:所有输入只包含小写字母 a-z 。
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# 不排序做法60ms:第一个的每一位和后面的每一位对比
if strs is None or len(strs) == 0:
return ''
res = strs[0]
for i in range(1,len(strs)):
temp = res
res = ''
for j in range(min(len(strs[i]), len(temp))):
if temp[j] == strs[i][j]:
res = res + temp[j]
else:
break
return res
# 排序做法48ms:排完之后比较第一个和最后一个公共前缀
if not strs:
return ''
strs.sort()
res = ''
for i in range(len(strs[0])):
if strs[-1][i] != strs[0][i]:
return res
res += strs[0][i]
return res
|
eda5d72ab7b6c0815fe0fdddbd18b0ae01e9ca01 | unwosu/ThinkDeep | /dataset/ConvMNIST.py | 624 | 3.515625 | 4 | import tensorflow as tf
from dataset.Dataset import Dataset, DataValues
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data")
class ConvMNIST(Dataset):
"""
MNIST DATASET
"""
def __init__(self, batch_size):
Dataset.__init__(self, batch_size)
in_reshape = (-1, 28, 28, 1)
self.set_train(DataValues(x=mnist.train.images.reshape(*in_reshape), y=mnist.train.labels))
self.set_val(DataValues(x=mnist.test.images.reshape(*in_reshape), y=mnist.test.labels))
self.set_test(DataValues(x=mnist.test.images.reshape(*in_reshape), y=mnist.test.labels))
|
fe966523f61cb1c9816662082666235f7fb35882 | InnaOrtman/homework | /ypok 3/task_3.py | 463 | 4.40625 | 4 | # The name check.
# Write a program that has a variable with your name stored (in lowercase) and then asks for your name as input.
# The program should check if your input is equal to the stored name even if the given name has another case,
# e.g., if your input is “Anton” and the stored name is “anton”, it should return True.
name = 'inna'
question = input("What is your name?").lower()
if question == name:
print("True")
else:
print("False")
|
c46a95ed34ed335e8b11678cdc2140169cb456a5 | phk0606/helloPython | /tmp/011.py | 250 | 3.53125 | 4 | scope = [1,2,3,4,5]
for x in scope:
print(x)
str = 'abcdef'
for c in str:
print(c)
list = [1,2,3,4,5]
for c in list:
print(c)
ascii_codes = {'a':97, 'b':98, 'c':99}
for c in ascii_codes:
print(c)
for c in range(10):
print(c)
|
9927ed62801c12b4f625ff1fff910517f5ceb140 | gsudarshan1990/PythonSampleProjects | /Python/inputfunction.py | 137 | 3.890625 | 4 | name=input('Enter the name')
print(name)
number=input('Enter the number')
#print(number+1) input gets only string
print(int(number)+1)
|
4506ee189d903a2850dbd1dba9f4b7b20d8e0bea | sghosh1991/InterviewPrepPython | /LeetCodeProblemsMedium/168_excel_sheet_column_titile.py | 867 | 3.9375 | 4 | """
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
Same as base conversion here base is 26
And 1 = A...26 = Z
Because of this complexity the direct remainder wont work
We need to shift the remainder as per the fact that A = 1
So we cyclic left shift remainders
26 <- 0
"""
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
remainder = []
while n:
n -= 1
remainder.append(n % 26)
n /= 26
result = [ chr(x + ord('A')) for x in reversed(remainder)]
return "".join(result)
if __name__ == "__main__":
x = Solution()
print x.convertToTitle(28)
#print x.convertToTitle(52)
|
a5c5a277af7b8d3ed32c4778d3e283187cc71641 | liseningg/Coding4Interviews | /剑指offer/062-二叉搜索树的第k个结点/code.py | 861 | 3.546875 | 4 |
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
if not pRoot: return None
stack = []
while pRoot or stack:
while pRoot:
stack.append(pRoot)
pRoot = pRoot.left
pRoot = stack.pop()
k -= 1
if k == 0:
return pRoot
pRoot = pRoot.right
递归法
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
res = []
def preorder(pRoot):
if not pRoot:
return None
preorder(pRoot.left)
res.append(pRoot)
preorder(pRoot.right)
preorder(pRoot)
if len(res) < k or k <1:
return None
return res[k-1]
|
92039c4bad63df6123697a07e4ec74662b7e3df5 | HongLeiNW/project | /day01/xiaojiayu/recursion_2.py | 437 | 3.859375 | 4 | #斐波那契数列的迭代实现--n1+n2=n3
#相应速度快
def fab(n):
n1 = 1
n2 = 1
n3 = 1
#不能输入0或负数
if n < 1:
print('输入错误!')
return -1
while (n - 2) > 0:
n3 = n2 + n1
n1 = n2
n2 = n3
n -= 1
return n3
result = int(input('Input one number: '))
fab_number = fab(result)
if result != -1:
print('数量共计 %d 个' % fab_number) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.