blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ebe64f9cc91e45d6038ba34f15201566328bdc50 | Haut-Stone/study_Python | /PythonCookbook/<3>数字日期和时间/11-随机选择.py | 546 | 3.75 | 4 | '''
'''
import random
values = [1, 2, 3, 4, 5, 6]
print(random.choice(values))
print(random.choice(values))
print(random.choice(values))
# 想要取出N个元素,将选出的元素移除以做进一步的考察,可以使用random.sample()
print(random.sample(values, 2))
print(random.sample(values, 2))
# 打乱顺序
random.shuffle(values)
print(values)
# 生成随机整数
print(random.randint(0, 10))
print(random.randint(0, 10))
# 产生0到1之间均匀分布的浮点数值
random.random()
random.random()
random.random()
|
d42bb2c01669d8bb3e4b8354076e6b5d7d0e178b | mveselov/CodeWars | /tests/kyu_8_tests/test_barking_mad.py | 356 | 3.65625 | 4 | import unittest
from katas.kyu_8.barking_mad import Dog
class DogTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(Dog("Beagle").bark(), 'Woof')
def test_equals_2(self):
self.assertEqual(Dog("Great Dane").bark(), 'Woof')
def test_equals_3(self):
self.assertEqual(Dog('Schnauzer').bark(), 'Woof')
|
a9ae85551ea5d35db0118e1907afeb3597223e89 | chrinide/Mahjong-5 | /AI.py | 12,165 | 3.6875 | 4 | AI_name_list=['no_AI','zr_AI','zx_AI(zrzr)','zx_AI(zrno)','zx_AI(nozr)','zx_AI(nono)','human']
def init(player,gametable):
if player.AI_name == None:
player.AI_name = player.name
while player.AI_name not in AI_name_list:
print("可用的AI方法有:", ", ".join(AI_name_list))
player.AI_name = str(input("没有名为%s的AI,请指定正确的AI方法:"))
if player.AI_name == 'no_AI':
return no_AI(player,gametable)
elif player.AI_name == 'zr_AI':
return zr_AI(player,gametable)
elif player.AI_name == 'zx_AI(zrzr)':
return zx_AI(player,gametable,"zr_AI","zr_AI")#first 4 peng , second 4 drop
elif player.AI_name == 'zx_AI(zrno)':
return zx_AI(player,gametable,"zr_AI","no_AI")
elif player.AI_name == 'zx_AI(nozr)':
return zx_AI(player,gametable,"no_AI","zr_AI")
elif player.AI_name == 'zx_AI(nono)':
return zx_AI(player,gametable,"no_AI","no_AI")
elif player.AI_name == 'human':
return human(player,gametable)
else:
print("没有%s这个AI方法"%player.AI_name)
return None
class human():
def __init__(self,player,gametable):
self.name='no_AI'
self.player = player
self.gametable = gametable
def think_peng(self):
self.Print_tiles()
print("\n你可以碰牌: ",self.player.cnt[self.gametable.receive_tiles[-1][1]],"\n你要碰吗?(1要,2不要)")
ans=input()
if ans =="1":
return True
elif ans == "2":
return False
def Print_tiles(self):
print("\n\n你当前有牌:")
T_list = [None]*14
k=0
for i in range(0,34):
e= self.player.cnt[i]
if e:
t_name=self.player.get_tile_name(i)
while(e>0):
T_list[k]=i
print(t_name, end="\t")
k += 1
e -= 1
print()
return k,T_list
def think(self):
print("\n\n你摸到的牌:",self.player.get_tile_name(self.player.last_draw))
print("\n桌面上已出去的牌:")
for t in range(0,34):
if self.gametable.receive_cnt[t]:
print(self.player.get_tile_name(t),"x",self.gametable.receive_cnt[t],end="\t")
k,T_list = self.Print_tiles()
for i in range(1,k+1):
print(i,end="\t")
while 1:
print("\n\n输入要出的牌编号:")
try:
o=int(input())
if o in range(1,k+1):
return T_list[o-1]
except:
print("编号有误请重新输入")
class no_AI():
def __init__(self,player,gametable):
self.name='no_AI'
self.player = player
self.gametable = gametable
def think_peng(self):
return True
def think(self,player = None):
if player == None:
player = self.player
t = player.last_draw
for i in range(0, 3):
for j in range(1, 8):
k = i * 9 + j
if player.cnt[k] == 1:
if player.cnt[k - 1] + player.cnt[k + 1] == 0:
t = k
return t
elif player.cnt[k - 1] + player.cnt[k + 1] == 1:
t = k
# 0
k = i * 9 + 0
if player.cnt[k] == 1:
if player.cnt[k + 1] == 0:
t = k
elif player.cnt[k + 1] == 1:
t = k
# 1
k = i * 9 + 8
if player.cnt[k] == 1:
if player.cnt[k - 1] == 0:
t = k
elif player.cnt[k - 1] == 1:
t = k
for k in range(0, 7):
if player.cnt[k + 27] == 1:
t = k + 27
return t
return t
class zr_AI():
def __init__(self,player,gametable,s0=10,s1=6,s2=6,k0=2,k1=1,k2=1):
self.name='zr_AI'
self.player = player
self.gametable = gametable
self.s0 = s0
self.s1 = s1
self.s2 = s2
self.k0 = k0
self.k1 = k1
self.k2 = k2
def get_num_t(self,t):
return 4-self.player.cnt[t]-self.gametable.receive_cnt[t]#改进空间为计算其他玩家持牌的概率???
def get_first_level_ts(self,t):
ts=set()
p=t%9
if t>=0:
if t<=26:
p = t % 9
if p*(p-8):
return [t+1,t-1]
else:
return [t+1-1*p//4]
elif t<=33:
return []
return None
def get_second_level_ts(self,t):
ts=set()
p=t%9
if t>=0:
if t<=26:
p = t % 9
if p*(p-8)*(p-1)*(p-7):
return [t+2,t-2]
else:
return [t+(p*p*p-12*p*p+11*p)//42+2]
elif t<=33:
return []
return None
def think_peng(self):
l_r_t=self.player.cnt[self.gametable.receive_tiles[-1][1]]
sum_rp,sum_rpp = 0,0
for t in range(0,34):
sum_rp += self.rp_t(t)
self.player.cnt[l_r_t] -= 2
for t in range(0,34):
sum_rpp += self.rp_t(t)
sum_rpp += 3 * self.s0
self.player.cnt[l_r_t] += 2
return (sum_rpp>=sum_rp)
def think(self,player = None,gametable = None):
if player == None:
player = self.player
if gametable == None:
gametable = self.gametable
min_p=16*(self.s0+self.s1*self.s2+self.k0+self.k1*self.k2)
drop_t=None
for t in range(0,34):
p_t=self.rp_t(t)
if p_t!=0 and p_t<=min_p:
min_p=p_t
drop_t=t
if drop_t == None:
print("?")
return drop_t
def rp_t(self,t):
p_t = 0
sn_0 = self.player.cnt[t]
if sn_0:
sn_1, sn_2, kn_0, kn_1, kn_2 = 0, 0, 0, 0, 0
kn_0 = self.get_num_t(t)
for t1 in self.get_first_level_ts(t):
sn_1 += self.player.cnt[t1]
kn_1 += self.get_num_t(t1)
for t2 in self.get_second_level_ts(t):
sn_2 += self.player.cnt[t2]
kn_2 += self.get_num_t(t2)
p_t = sn_0 * self.s0 + (sn_1 * self.s1) + (sn_2 * self.s2) + kn_0 * self.k0 + (kn_1 * self.k1) + (kn_2 * self.k2)
return p_t
class zx_AI(zr_AI,no_AI):
def __init__(self,player,gametable,peng,drop):
zr_AI.__init__(self,player,gametable)
no_AI.__init__(self,player,gametable)
self.name='zx_AI'
self.AI4peng=peng
self.AI4drop=drop
# self.player = player
# self.gametable = gametable
self.n=1
def get_p_Ts(self,Ts):
p=0
for t in Ts:
n = (4-self.player.cnt[t]-self.gametable.receive_cnt[t])
p += n/122
return p
def think_peng(self):
l_r_t = self.player.cnt[self.gametable.receive_tiles[-1][1]]
max_n=self.n
n = 0
while n <= max_n:
p = self.get_p_Ts(self.get_n_ava_t(n))
if p > 0:
self.player.cnt[l_r_t] -= 2
self.player.peng += 1
pp = self.get_p_Ts(self.get_n_ava_t(n))
self.player.cnt[l_r_t] += 2
self.player.peng -= 1
if self.player.is_show in ["normal", "full"]:
print("神级判碰")
return pp>=p
n += 1
if self.AI4peng == "zr_AI":
return zr_AI.think_peng(self)
elif self.AI4peng == "no_AI":
return no_AI.think_peng(self)
else:
print ("AI4peng not found!")
def think(self):
t_best=self.get_best_drop_t(self.n)
if t_best !=None:
return t_best
if self.AI4drop == "zr_AI":
return zr_AI.think(self,self.player,self.gametable)
elif self.AI4drop == "no_AI":
return no_AI.think(self,self.player)
else:
print ("AI4drop not found!")
def get_best_drop_t(self,max_n):
n=0
while n<=max_n:
p_max,t_best=self.get_n_drop_t(n)
if p_max != 0:
if self.player.is_show in ["normal","full"]:
print("雀神在此!%d级听牌!"%n,end=" ")
return t_best
n += 1
return None
def get_n_drop_t(self,n):
n=int(n)
p_max = 0
for t in range(0, 34):
if self.player.cnt[t]>0:
self.player.cnt[t] -= 1
Tx = self.get_n_ava_t(n)
p_x=self.get_p_Ts(Tx)
if p_x>=p_max:
p_max=p_x
t_best=t
self.player.cnt[t] += 1
return p_max,t_best
def get_n_ava_t(self,n):
if n == 0:
T0 = []
T0p = []
for t in range(0, 34):
self.player.cnt[t] += 1
if self.player.hu_judge():
T0.append(t)
self.player.cnt[t] -= 1
return T0
elif n>=1:
T0 = self.get_n_ava_t(n-1)
p0 = self.get_p_Ts(T0)
T1 = []
T1p = []
for t in range(0, 34):
self.player.cnt[t] += 1
T0x = self.get_n_ava_t(n-1)
p0x = self.get_p_Ts(T0x)
if p0x > p0:
T1.append(t)
self.player.cnt[t] -= 1
return T1
else:
print("n应该为正整数")
# def get_zero_avalible_t(self,d_t):
# T0=[]
# T0p=[]
# for t in range(0,34) and t!=d_t:
# self.player.cnt[t] +=1
# if self.player.hu_jugde():
# T0.append(t)
# self.player.cnt[t] -= 1
# return T0
#
# def get_first_avalible_t(self,d_t):
# T0=self.get_zero_avalible_t()
# p0=get_p_Ts(T0)
# T1=[]
# T1p=[]
# for t in range(0,34) and t != d_t:
# self.player.cnt[t] +=1
# T0x = self.get_zero_avalible_t()
# p0x=get_p_Ts(T0x)
# if p0x > p0:
# T1.append(t)
# T1p.append(p0x)
# self.player.cnt[t] -= 1
# return T1,T1p
#
# def get_second_avalible_t(self):
# T1,T1p=self.get_first_avalible_t()
# p1=get_p_Ts(T1)
# T2=[]
# T2p=[]
# for t in range(0,33):
# self.player.cnt[t] +=1
# T1x = self.get_first_avalible_t()
# p1x=get_p_Ts(T1x)
# if p1x > p1:
# T2.append(t)
# T2p.append(p1x)
# self.player.cnt[t] -= 1
# return T2,T2p
def no_ai(self,player = None):
if player == None:
player = self.player
t = player.last_draw
for i in range(0, 3):
for j in range(1, 8):
k = i * 9 + j
if player.cnt[k] == 1:
if player.cnt[k - 1] + player.cnt[k + 1] == 0:
t = k
return t
elif player.cnt[k - 1] + player.cnt[k + 1] == 1:
t = k
# 0
k = i * 9 + 0
if player.cnt[k] == 1:
if player.cnt[k + 1] == 0:
t = k
elif player.cnt[k + 1] == 1:
t = k
# 1
k = i * 9 + 8
if player.cnt[k] == 1:
if player.cnt[k - 1] == 0:
t = k
elif player.cnt[k - 1] == 1:
t = k
for k in range(0, 7):
if player.cnt[k + 27] == 1:
t = k + 27
return t
return t
|
f4ff5535438cd0c972f3062f1a3f9b30e203986b | jaford/thissrocks | /Python_Class/py3intro3day 2/EXAMPLES/fmt_signed.py | 393 | 4 | 4 | #!/usr/bin/env python
values = 123, -321, 14, -2, 0
for value in values:
print("default: |{:d}|".format(value)) # <1>
print()
for value in values:
print(" plus: |{:+d}|".format(value)) # <2>
print()
for value in values:
print(" minus: |{:-d}|".format(value)) # <3>
print()
for value in values:
print(" space: |{: d}|".format(value)) # <4>
print()
|
4bd1e0de72840f708132df376ecaa40cd941fffa | JdoubleW/Opdrachten_programmeren | /Week 2/pe3_3.py | 211 | 3.875 | 4 | age = eval(input('Wat is je leeftijd?'))
passport = input('Heb je een paspoort?')
if age >= 18 and passport == 'Ja':
print("Gefeliciteerd! Jij mag stemmen!")
else:
print("Jij mag niet stemmen.") |
5e88c5e02104d94684a53a24c78e0ab540249fd7 | GuillyK/University-world-ranking-group-4 | /Used python code/student_count.py | 801 | 3.6875 | 4 | ######################################################################################
# moves the universities into 3 different catogories based on the amount of students.
# adds these values in to the csv
######################################################################################
import googlemaps
import csv
import pandas as pd
import numpy
data = pd.read_csv("university_ranking_2016.csv")
counter = 0
for number in data['fte_students']:
if number <= 5000:
size = 'small'
print('small')
elif number > 5000 and number <= 15000:
size = 'medium'
print('medium')
elif number > 15000:
size = 'large'
print('big')
data.set_value(counter, "size", size)
counter += 1
data.to_csv("university_ranking_2016.csv", index=False)
|
8b0e669e821771dc7122c0a0baaf0e41d6f67bca | MTrajK/coding-problems | /Math/sum_of_multiples.py | 1,140 | 4.1875 | 4 | '''
Multiples of a OR b
If we list all the natural numbers below 10 that are multiples of 3 OR 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of A or B below N.
=========================================
Don't need iteration to solve this problem, you need to find only how many divisors are there.
Example - 3 + 6 + 9 ... + N = (1 + 2 + 3 + ... N // 3) * 3
Sum(K)*N = 1*N + 2*N + ... + (K-1)*N + K*N
Use sum formula - (N * (N + 1))/2
Time Complexity: O(1)
Space Complexity: O(1)
'''
############
# Solution #
############
def sum_of_multiples_below(a, b, total):
total -= 1
# sum of dividens of A + sum of dividens of B - sum of common dividens (because they're added twice)
return sum_of_dividends(total, a) + sum_of_dividends(total, b) - sum_of_dividends(total, a * b)
def sum_of_dividends(total, divisor):
n = total // divisor
return (n * (n + 1) // 2) * divisor
###########
# TESTING #
###########
# Test 1
# Correct result => 23
print(sum_of_multiples_below(3, 5, 10))
# Test 2
# Correct result => 233168
print(sum_of_multiples_below(3, 5, 1000))
|
7aa7a3e47bcaa541acfef053bba89a8995a7e63c | daorox/aoc2019 | /day13/e13.py | 1,550 | 3.703125 | 4 | from computer import Computer
class TileTypes:
EMPTY = 0
WALL = 1
BLOCK = 2
PADDLE = 3
BALL = 4
class BreakOutAi:
def __init__(self, computer):
self.computer = computer
self.computer.mem[0] = 2
self.db = {}
self._update_db(computer.run(0))
def destroy_all_blocks(self):
while self.get_positions(TileTypes.BLOCK):
self.make_move()
return self.db[-1, 0] # score
# Obviously inefficient, but simple :)
def get_positions(self, tile_type):
return [k for k, v in self.db.items() if v == tile_type]
def make_move(self):
self._update_db(self._make_move())
return self.db
def _update_db(self, it):
try:
while True:
x = next(it)
y = next(it)
tile = next(it)
self.db[x, y] = tile
except StopIteration:
pass
def _make_move(self):
ball_pos = self.get_positions(TileTypes.BALL)[0]
pad_pos = self.get_positions(TileTypes.PADDLE)[0]
if ball_pos[0] < pad_pos[0]:
return self.computer.run(-1)
elif ball_pos[0] > pad_pos[0]:
return self.computer.run(1)
else:
return self.computer.run(0)
if __name__ == "__main__":
with open("e13.txt") as f:
data = list(map(int, f.read().split(",")))
# 1
print(len(BreakOutAi(Computer(data)).get_positions(TileTypes.BLOCK)))
# 2
print(BreakOutAi(Computer(data)).destroy_all_blocks())
|
bbb07334f86b66ff8f620978b603b221213c5139 | akimi-yano/algorithm-practice | /lc/222.CountCompleteTreeNodes.py | 2,208 | 4.0625 | 4 | # 222. Count Complete Tree Nodes
# Medium
# 2425
# 228
# Add to List
# Share
# Given a complete binary tree, count the number of nodes.
# Note:
# Definition of a complete binary tree from Wikipedia:
# In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
# Example:
# Input:
# 1
# / \
# 2 3
# / \ /
# 4 5 6
# Output: 6
# This solution works but not optimal:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
def helper(cur):
if not cur:
return 0
return 1 + helper(cur.left) + helper(cur.right)
return helper(root)
# This solution works !!!
'''
# Time: O( (logN)^2 )
# Space: O( 1 )
idea:
1) go the left most to get the level
2) then binary search for the right by doing bitwise operation and then calculate at the end
since its complete tree number of nodes is 2^level - 1
left is 0
right is 1
00 01 10 11
levels = how many bits there are
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if root is None:
return 0
levels = 0
cur = root
while cur.left is not None:
levels += 1
cur = cur.left
left = 0
right = (1 << levels) - 1
while left < right:
mid = (left + right + 1) // 2
cur = root
for i in range(levels-1, -1, -1):
if mid & (1 << i):
cur = cur.right
else:
cur = cur.left
if cur is None:
right = mid - 1
else:
left = mid
return (1 << levels) - 1 + left + 1 |
9d1226581eecf399ce55e8c104946e7395eca760 | supergonzo812/cs-module-project-algorithms | /eating_cookies/eating_cookies.py | 1,155 | 4.21875 | 4 | '''
Input: an integer
Returns: an integer
'''
def eating_cookies(n):
# Cookie Monster can eat either 1, 2, or 3 cookies at a time. If he were given a jar of cookies with `n` cookies inside of it, how many ways could he eat all `n` cookies in the cookie jar? Implement a function `eating_cookies` that counts the number of possible ways Cookie Monster can eat all of the cookies in the jar.
# For example, for a jar of cookies with `n = 3` (the jar has 3 cookies inside it), there are 4 possible ways for Cookie Monster to eat all the cookies inside it:
# 1. He can eat 1 cookie at a time 3 times
# 2. He can eat 1 cookie, then 2 cookies
# 3. He can eat 2 cookies, then 1 cookie
# 4. He can eat 3 cookies all at once.
# Thus, `eating_cookies(3)` should return an answer of 4.
# 1, 1, 1, 1, 1
# 1, 1, 1, 2
# 1, 1, 3
# 1, 2, 2
# 1, 3, 1
# 1, 1, 2, 1
# 1, 2, 1, 1
# 2, 1, 1, 1
# 2, 1, 2
# 2, 2, 1
# 3, 1, 1
# 2, 3
# 3, 2
if __name__ == "__main__":
# Use the main function here to test out your implementation
num_cookies = 5
print(f"There are {eating_cookies(num_cookies)} ways for Cookie Monster to each {num_cookies} cookies")
|
5a1c6d4d39839b13b29dddba41817049016de02f | LinkIsACake/PTUT-CoffreFortElectronique | /src/EncryptCore/sources/Utilities.py | 3,885 | 3.5 | 4 | from math import log, ceil
def bundleSizeAndRest(size: int, rest: int):
"""
# get a bundled number of the rest and the bytes needed to store the cipher
# Note: some arbitrary modification is done to this number to protect it against reverse engineering
:param size: the size of the cipher to bundle (max: 255)
:param rest: the rest of the cipher to bundle (max: 16 777 215)
:return: a bundled number containing the size and the rest of the cipher
"""
if size > 255 or rest > 16777215:
raise ValueError("The numbers are too big to be bundled together... (size: %d, rest: %d)" % (size, rest))
# get the 2nd byte of the rest and shift it to the topmost position
swapValue = (rest & 0x0000ff00) << 16
# shift the value of the bytesNeeded to the 3rd position
size <<= 8
# create the bundled value with this memory sheme: rest_1|rest_2|bytesNeeded|rest_0
sizeAndRestBundle = (rest & 0x00ff00ff) | size | swapValue
# change the endianess of the number and return the result
return sizeAndRestBundle.to_bytes(4, 'little')
def unbundleSizeAndRest(sizeAndRestBundle: int):
"""
Get the size and the rest of the cipher base from a bundled integer
:param sizeAndRestBundle: a bundled number containing the size and the rest of the cipher
:return: the size and the rest as a tuple
"""
if sizeAndRestBundle > 0xffffffff:
raise ValueError("The bundled number is too big.")
# get the size from the 2nb byte
size = (sizeAndRestBundle & 0x0000ff00) >> 8
# get the swap byte from the topmost byte
swapValue = (sizeAndRestBundle & 0xff000000) >> 16
# set the swap byte at the 2ns byte and clear the topmost byte
rest = (sizeAndRestBundle & 0x00ff00ff) | swapValue
return size, rest
def generateKey(fileData: dict, userData: dict):
"""
Generate a key from file infos and user infos dictionaries
:param fileData: a dictionary that contain all file infos used to create the key
:param userData: a dictionary that contain all user infos used to create the key
:return: a integer equavalent of all serialized values
"""
# Serialize all file infos and user infos
pwd = ""
for k,v in fileData.items(): pwd += "%s:%s" % (k,v)
for k,v in userData.items(): pwd += "%s:%s" % (k,v)
# get the int equivalent of the bytes serialized infos in order to be used with a given base
return int.from_bytes(pwd.encode(), 'big')
def generateCipherMod(key: int, base: int):
"""
cipher a given base using a temporary key
:param key: a temporary integer key
:param base: a integer base
:return: a cipher base along with a bundled size & rest integer
given the relation: a = k*b + r
then: a-r = k*b
and: b = (a-r)/k
So let's say that k and r will be stored in the file, a is our key, b is the base
So to cipher the base we will do:
cipher = key // base
rest = key % base
And to decipher the base we will do:
base = (key-rest)//cipher
"""
cipher = key // base
rest = key % base
# this need to be lower than 255
bytesNeeded = ceil(log(cipher, 256))
if bytesNeeded > 255:
raise ValueError("The cipher of the base is larger than 255 bytes...")
bundledSizeAndRest = bundleSizeAndRest(bytesNeeded, rest)
cipherBytes = cipher.to_bytes(bytesNeeded, 'big', signed=False)
return bundledSizeAndRest, cipherBytes
def getModFromCipher(key: int, cipher: int, rest: int):
"""
get the base from the sipher, the key and the rest values
:param key: a temporary integer key
:param cipher: the ciphered base retreived from the file
:param rest: the rest of the equation (see Utilities:generateCipher)
:return: a integer base
"""
base = (key-rest) // cipher
return base
|
ad4a7392e6ac0c0f2122a21d3a12dd4cd9a78b6d | gerrymanoim/advent_of_code | /2019/5.py | 4,476 | 4.4375 | 4 | """
An Intcode program is a list of integers separated by commas (like 1,0,0,3,99).
To run one, start by looking at the first integer (called position 0). Here,
you will find an opcode - either 1, 2, or 99.
- 99 means that the program is finished and should immediately halt.
- Opcode 1 adds together numbers read from two positions and stores the result
in a third position. The three integers immediately after the opcode tell you
these three positions - the first two indicate the positions from which you
should read the input values, and the third indicates the position at which
the output should be stored.
- Opcode 2 works exactly like opcode 1, except it multiplies the two inputs
instead of adding them. Again, the three integers after the opcode indicate
where the inputs and outputs are, not their values.
- Opcode 3 takes a single integer as input and saves it to the position given
by its only parameter. For example, the instruction 3,50 would take an input
value and store it at address 50.
- Opcode 4 outputs the value of its only parameter. For example, the
instruction 4,50 would output the value at address 50.
Right now, your ship computer already understands parameter mode 0, position
mode, which causes the parameter to be interpreted as a position - if the
parameter is 50, its value is the value stored at address 50 in memory. Until
now, all parameters have been in position mode.
Now, your ship computer will also need to handle parameters in mode 1,
immediate mode. In immediate mode, a parameter is interpreted as a value - if
the parameter is 50, its value is simply 50.
Parameter modes are stored in the same value as the instruction's opcode. The
opcode is a two-digit number based only on the ones and tens digit of the
value, that is, the opcode is the rightmost two digits of the first value in an
instruction. Parameter modes are single digits, one per parameter, read
right-to-left from the opcode: the first parameter's mode is in the hundreds
digit, the second parameter's mode is in the thousands digit, the third
parameter's mode is in the ten-thousands digit, and so on. Any missing modes
are 0.
"""
from pathlib import Path
from typing import Callable
from collections import namedtuple
def f01(ixs, in_1, in_2, out_loc):
ixs[out_loc] = str(in_1 + in_2)
def f02(ixs, in_1, in_2, out_loc):
ixs[out_loc] = str(in_1 * in_2)
def f03(ixs, out_loc):
ixs[out_loc] = input("Enter a number: ")
def f04(ixs, out):
print(f">>>>> OUTPUT <<<<<< {out}")
def f05(ixs, in_1, in_2):
if in_1 != 0:
return in_2
def f06(ixs, in_1, in_2):
if in_1 == 0:
return in_2
def f07(ixs, in_1, in_2, out_loc):
ixs[out_loc] = "1" if in_1 < in_2 else "0"
def f08(ixs, in_1, in_2, out_loc):
ixs[out_loc] = "1" if in_1 == in_2 else "0"
Opt = namedtuple("Optcode", ["n_args", "func", "output"])
code_to_opt = {
"99": "return",
"01": Opt(2, f01, True),
"02": Opt(2, f02, True),
"03": Opt(0, f03, True),
"04": Opt(1, f04, False),
"05": Opt(2, f05, False),
"06": Opt(2, f06, False),
"07": Opt(2, f07, True),
"08": Opt(2, f08, True),
}
def run_instruction(pntr: int, ixs: list) -> int:
ix = ixs[pntr]
if ix == "99":
return -1
opt_str, modes = ix[-2:].zfill(2), ix[:-2].zfill(3)[::-1]
print(f"opt_str {opt_str}, modes {modes}")
opt = code_to_opt[opt_str]
buffer = []
for i in range(opt.n_args):
mode = modes[i]
pos = int(ixs[pntr + i + 1])
if mode == "1":
buffer.append(pos)
else:
buffer.append(int(ixs[pos]))
if opt.output:
buffer.append(int(ixs[pntr + opt.n_args + 1]))
print(f"buffer {buffer}")
maybe_pntr = opt.func(ixs, *buffer)
print(f"Maybe pnt {maybe_pntr}")
if maybe_pntr:
return maybe_pntr
else:
is_output = 1 if opt.output else 0
return pntr + opt.n_args + is_output + 1
def run_program(input_ixs: list) -> list:
pntr = 0
while True:
print(f"pntr: {pntr}")
print(f"top of loop: {input_ixs}")
pntr = run_instruction(pntr, input_ixs)
if pntr == -1:
return input_ixs
assert run_program(["1002", "4", "3", "4", "33"]) == [
"1002",
"4",
"3",
"4",
"99",
]
with Path("input5.txt") as f:
instructions = f.read_text().split(",")
# instructions = [int(ix) for ix in instructions]
run_program(instructions)
|
0fe427120d8b5e1fbf5eded244a18e4a2a5b01f2 | sprinter-17/PyChess | /test/test_board.py | 1,081 | 3.65625 | 4 | import unittest
from board import Board, Piece
class MyTestCase(unittest.TestCase):
def setUp(self):
self.board = Board()
def test_board_created(self):
self.assertIsNotNone(self.board)
def test_pieces_count(self):
self.assertEqual(len(self.board.pieces), 32)
def test_pieces_colour(self):
self.assertEqual(len([p for p in self.board.pieces if p.colour == Piece.WHITE]), 16)
self.assertEqual(len([p for p in self.board.pieces if p.colour == Piece.BLACK]), 16)
def test_piece_type(self):
for colour in [Piece.BLACK, Piece.WHITE]:
pieces = [p for p in self.board.pieces if p.colour == colour]
self.assertEqual(len([p for p in pieces if p.type == Piece.PAWN]), 8)
self.assertEqual(len([p for p in pieces if p.type == Piece.ROOK]), 2)
self.assertEqual(len([p for p in pieces if p.type == Piece.KING]), 1)
def test_piece_position(self):
self.assertEqual(self.board.get_piece(2, 1).colour, Piece.WHITE)
if __name__ == '__main__':
unittest.main()
|
03f2bc7a6f7d99acfafd8bcb2899e79c02c9421d | maiconferreira/atividade-aula-ALPC | /Atividade-2/main.py | 1,086 | 3.890625 | 4 | '''
Instruções: -O custo ao consumidor de um carro novo é a soma do preço de fábrica com o percentual de lucro do distribuidor e dos impostos aplicados ao preço de fábrica. Faça um programa em Python que receba o preço de fábrica de um veículo, o percentual de lucro do distribuidor e o percentual de imposto, calcule e mostre:
a) o valor correspondente ao lucro do distribuidor;
b) o valor correspondente aos impostos;
c) o preço final do veículo.
'''
#Entradas
preco_fab = float(input('Digite o preço de fábrica do veículo: R$').replace(',',"."))
per_lucro = float(input('Digite o percentual de lucro do distribuidor: ').replace(',','.'))
per_impostos = float(input('Digite o percentual de impostos: ').replace(',','.'))
#Processamento
lucro_dist = (preco_fab * per_lucro) / 100
val_imp = (preco_fab * per_impostos) / 100
preco_final = preco_fab + lucro_dist + val_imp
#Saída
print(f'O lucro do distribuidor será de R${lucro_dist:.2f}')
print(f'O valor pago de impostos será de R${val_imp:.2f}')
print(f'O preço final do veículo será de R${preco_final:.2f}')
|
764185b7c0ed762159f87b983f64c0ce9e41225a | Crayon2f/hello-world | /src/base/for.py | 895 | 3.890625 | 4 | # coding=utf-8
# for循环
print('------------------ for ------------------------')
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
print(fruit)
for index in range(len(fruits)):
print(index)
print('-------------- for else ------------------')
numbers = [1, 2, 3, 4, 5, 6, 7]
for number in numbers:
if number % 2 == 0:
print(number)
break
else:
print('else')
print('------------------ enumerate ------------------------')
for index, item in enumerate(fruits):
print(index, item)
primeList = []
for num in range(2, 100):
for i in range(2, num):
if num % i == 0:
break
else:
primeList.append(num)
print(primeList, len(primeList))
if 4 % 2:
print('----- 4%2=0 在if条件判断中是false(只有为0时候是false) -----------')
elif 4 % 3:
print('------ 4%3=1 在if条件判断中是true---------')
|
7e826d4bb889c4a2f3b826dfd3d30428357ac3df | MKDevil/Python | /学习(千峰)/03语句和语法/02 循环语句练习.py | 1,188 | 3.75 | 4 | '''
Author: MK_Devil
Date: 2021-12-20 17:18:09
LastEditTime: 2022-01-19 17:13:00
LastEditors: MK_Devil
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
# 打印 1-50 内可以被 3 整除的数字
n = 1
while n <= 50:
if n % 3 == 0:
print(n, end='\t')
n += 1
print()
n = 1
counter = 1
while n + 3 < 50:
n = 3 * counter
counter += 1
print(n, end='\t')
print()
# 打印 1-10 的累加和
n = 1
res = 0
while n <= 10:
res += n
n += 1
print(res)
# 猜数字
ran = random.randint(1, 50)
counter = 0
while True:
guess = input('输入你猜的数字,输入 q 退出:')
if guess == 'q':
break
guess = int(guess)
counter += 1
if guess > ran:
print('大了')
elif guess < ran:
print('小了')
else:
print('正确,数字为%d' % ran)
if counter == 1:
print('恭喜一次猜对!')
elif 1 < counter < 5:
print('运气不错,%d次猜对' % counter)
elif 5 < counter < 10:
print('运气一般,%d次猜对' % counter)
else:
print('尼哥就是说的你,%d次才猜对' % counter)
break
|
8f1ba4dffabe554af96aca45218c9c2c44ba490d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2445/60866/266045.py | 335 | 3.8125 | 4 | def chazhao(a,b):
if len(a)!=len(b):
print('false')
else:
A=[ord(x) for x in a]
B=[ord(x) for x in b]
s1=set(A)
s2=set(B)
if len(s1|s2)!=len(s1):
print('false')
else:
print('true')
import re
a=input()
m=re.split(r'\"',a)
a=m[1]
b=m[3]
chazhao(a,b) |
166d7d78bf258a953944dc4ba04276e40a5071ce | noorulameenkm/DataStructuresAlgorithms | /Recursion/factorial_memoization_decorator.py | 328 | 3.71875 | 4 |
def fact_memoization(func):
memory = {}
def fact(num):
if num not in memory:
memory[num] = func(num)
return memory[num]
return fact
@fact_memoization
def factorial(num):
if num == 1:
return 1
return num * factorial(num - 1)
print(factorial(5))
print(factorial(7)) |
6fc68e3bf57bcfa85dfbaf5df66529957e899acf | suterm0/Project13 | /Assignment13.py | 9,506 | 4.28125 | 4 | import sqlite3
from sqlite3 import Error
def choice():
print("""
Put 1 to pull up the customer menu,
2 for the books menu,
3 to pull up the orders,
4 to exit code.
""")
answer = int(input(">"))
while answer <= 1 >= 3: # Unlimited loop for the menu
choice()
if answer == 1:
customer_menu()
if answer == 2:
books_menu()
if answer == 3:
order_menu()
else:
if answer == 4:
exit("goodbye")
def customer_menu():
print("""
1 to add to the customer table
2 to modify a customers name
3 to print the customers table
4 to delete a customer
5 to return to the main menu
""")
answer = int(input(">"))
while answer <= 1 >= 5: # Unlimited loop for the menu
customer_menu()
if answer == 1:
print("Please enter the details for the person:")
first_name = input("What is the first name?")
last_name = input("What is the last name?")
street_address = input("What is the street address?")
city = input("What is the city?")
state = input("What is the state?")
zip_code = input("What is the zip code?")
create_customer = f"""
INSERT INTO
customer (first, last, address, city, state, zip)
VALUES
('{first_name}', '{last_name}', '{street_address}', '{city}', '{state}', '{zip_code}');
"""
execute_query(connection, create_customer) # executes the query
print("Here is the customer table")
select_customers = "SELECT * from customer"
people = execute_read_query(connection, select_customers) # executes the query
for person in people:
print(person)
return choice()
if answer == 2:
update_customer = """ (
UPDATE customer
SET last_name = "magee"
WHERE last_name = "suter"
);
"""
execute_query(connection, update_customer) # executes the query
print("Whos last name was 'Suter' is now 'magee'")
return choice()
if answer == 3:
print("Here is the customer table")
select_customers = "SELECT * from customer"
people = execute_read_query(connection, select_customers) # executes the query
for person in people:
print(person)
return choice()
if answer == 4:
delete_book = """(
DELETE FROM customer
WHERE last_name = "magee"
);"""
execute_query(connection, delete_book) # executes the query
print("You just deleted any person with the last name 'magee'")
return choice()
else:
if answer == 5:
choice()
def books_menu():
print("""
1 to add to the books table
2 to modify a book
3 to print the books table
4 to delete a book
5 to return to the main menu
""")
answer = int(input(">"))
while answer <= 1 >= 5: # Unlimited loop for the menu
customer_menu()
if answer == 1:
print("Please enter the following information to add a book to the table")
title= input("What is the title?")
author = input("Who is the author?")
isbn = input("What is the ISBN?")
edition = input("What is edition?")
price = input("What is the price?")
publisher = input("Who is the publisher?")
create_book = f"""
INSERT INTO
books (title, author, isbn, edition, price, publisher)
VALUES
('{title}', '{author}', '{isbn}', '{edition}', '{price}', '{publisher}');
"""
execute_query(connection, create_book) # executes the query
print("Here is the books table")
select_book = "SELECT * from books"
books = execute_read_query(connection, select_book) # executes the query
for book in books: # this goes through the table printing each row of data
print(book)
return choice()
if answer == 2:
update_book = """ (
UPDATE books
SET title = "magee"
WHERE title = "fire"
);
"""
execute_query(connection, update_book) # executes the query
print("Who's title was 'fire' is now 'magee'")
return choice()
if answer == 3:
print("Here is the books table")
select_book = "SELECT * from books"
books = execute_read_query(connection, select_book) # executes the query
for book in books:
print(book)
return choice()
if answer == 4:
delete_book = """(
DELETE FROM books
WHERE title = "magee"
);"""
execute_query(connection, delete_book) # executes the query
print("You just deleted any book with the title 'magee'")
return choice()
else:
if answer == 5:
choice()
def order_menu():
print("""
Enter 1 to place an order,
Enter 2 to view the orders submitted,
Enter 3 to view more information about the submitted orders,
Enter 4 to return to the main menu
""")
answer = int(input(">"))
while answer <= 1 >= 5: # Unlimited loop for the menu
order_menu()
if answer == 1:
print("Please enter the following information about the order being recorded.")
order_date = input("Enter the date this was ordered in this format '09/12/01'..>")
order_cost = input("Enter the total cost of this order..>")
quantity = input("Enter the number of books ordered..>")
create_order = f"""
INSERT INTO
orders (order_date, order_total)
VALUES
('{order_date}', '{order_cost}');
"""
execute_query(connection, create_order) # executes the query
create_orderlineitem = f"""
INSERT INTO
orderlineitem (quantity)
VALUES
('{quantity}');
"""
execute_query(connection, create_orderlineitem) # executes the query
print("Here is the newly updated orders table")
print("The following table appears like so (Order#, Order date, Cost per book, Customer_id)")
select_order = "SELECT * from orders"
orders = execute_read_query(connection, select_order) # executes the query
for order in orders:
print(order)
return choice()
if answer == 2:
print("Here is the newly updated orders table")
print("The following table appears like so (Order#, Order date, Cost per book, Customer_id")
select_order = "SELECT * from orders"
orders = execute_read_query(connection, select_order) # executes the query
for order in orders:
print(order)
return choice()
if answer == 3:
print("Here is the advanced information table")
print("The following table appears like so (Order_id, book_id, quantity of books ordered)")
select_order = "SELECT * from orderlineitem"
orders = execute_read_query(connection, select_order) # executes the query
for order in orders:
print(order)
return choice()
if answer == 4:
choice()
def create_connection(path):
conn = None
try:
conn = sqlite3.connect(path)
print("Connection to SQLite DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return conn
print("Connect to SQLite database:")
connection = create_connection("Assignment13.db") # executes the query
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred")
def execute_read_query(connection, query):
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except Error as e:
print(f"The error '{e}' occurred")
create_order_table = """
CREATE TABLE IF NOT EXISTS orders (
order_number INTEGER PRIMARY KEY AUTOINCREMENT,
order_date TEXT NOT NULL,
order_total TEXT NOT NULL,
customer_id INTEGER AUTOINCREMENT,
FOREIGN KEY (customer_id) REFERENCES customer(customer_id)
);
"""
create_orderlineitem_table = """
CREATE TABLE IF NOT EXISTS orderlineitem (
order_number INTEGER AUTOINCREMENT,
book_id INTEGER AUTOINCREMENT,
quantity TEXT NOT NULL,
PRIMARY KEY (order_number, book_id),
FOREIGN KEY (order_number) REFERENCES orders(order_number)
FOREIGN KEY (book_id) REFERENCES books(book_id)
);
"""
create_customer_table = """
CREATE TABLE IF NOT EXISTS customer (
customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
first TEXT NOT NULL,
last TEXT NOT NULL,
address TEXT NOT NULL,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL
);
"""
create_books_table = """
CREATE TABLE IF NOT EXISTS books (
book_id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
ISBN TEXT NOT NULL,
edition TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL
);
"""
print("\nRun the query to create the customer table:")
execute_query(connection, create_customer_table)
execute_query(connection, create_books_table)
execute_query(connection, create_order_table)
execute_query(connection, create_orderlineitem_table)
choice()
|
57157eb13c843c4a0ae3f178243d2ed19260a29b | yixinj/cs4417asn2 | /part3/query.py | 1,390 | 3.75 | 4 | import sys
for query in sys.stdin:
# Take query and process it
query = query.strip().upper().split()
# If length of query is 1 (so 1 search term)
if len(query) == 1:
genre_first = query[0] # genre1 is genre to search for
with open('part3/movieInformation', 'r') as f:
for line in f:
line = line.strip()
genre, movies = line.split('\t')
if genre_first == genre:
movies = movies.split('|')
print(movies)
# Otherwise ...
else:
genre_first, operator, genre_second = query
first_set = second_set = None
with open('part3/movieInformation', 'r') as f:
for line in f:
line = line.strip()
genre, movies = line.split('\t')
if genre_first == genre:
movies = movies.split('|')
first_set = set(movies)
if genre_second == genre:
movies = movies.split('|')
second_set = set(movies)
# Output set that fits the operator
if operator == 'AND':
# AND is the intersection of the sets
print(first_set.intersection(second_set))
if operator == 'OR':
# OR is the union of the sets
print(first_set.union(second_set))
|
78f7349cf6a8030df3bd4e5ad7f95660753a9a4f | josealb94/platzi_AplicacionTerminal | /contacts.py | 3,695 | 3.890625 | 4 | # -*- coding: utf8 -*-
import csv
WELCOME = """
---------------------------------------------------
| B I E N V E N I D O A L A A G E N D A |
---------------------------------------------------
"""
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
class ContactBook:
def __init__(self):
self.contacts = []
def add(self, name, phone, email):
contact = Contact(name, phone, email)
self.contacts.append(contact)
self.save()
#print('name: {}, phone: {}, email: {}'.format(name, phone, email))
def delete(self, name):
for i, contact in enumerate(self.contacts):
if contact.name.lower() == name.lower():
del self.contacts[i]
self.save()
break
def search(self, name):
for contact in self.contacts:
if contact.name.lower() == name.lower():
self.print_contact(contact)
break
else:
self.not_found()
def save(self):
with open('contacts.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(('name', 'phone', 'email'))
for contact in self.contacts:
writer.writerow((contact.name, contact.phone, contact.email))
def show_all(self):
print('#########################################################')
print(' L I S T A D E C O N T A C T O S')
print('#########################################################')
for contact in self.contacts:
self.print_contact(contact)
print('#########################################################')
def print_contact(self, contact):
print('---*---*---*---*---*---*---*---')
print('Nombre: {}'.format(contact.name))
print('Telefono: {}'.format(contact.phone))
print('Email: {}'.format(contact.email))
print('---*---*---*---*---*---*---*---')
def not_found(self):
print('#########################################################')
print('El usuario no ha sido encontrado!!')
print('#########################################################')
def run():
contact_book = ContactBook()
print(WELCOME)
with open('contacts.csv', 'r') as f:
reader = csv.reader(f)
for i, row in enumerate(reader):
if i == 0:
continue
contact_book.add(row[0], row[1], row[2])
while True:
command = str(input('''
¿Qué deseas hacer?
[a]ñadir contacto
[ac]tualizar contacto
[b]uscar contacto
[e]liminar contacto
[l]istar contactos
[s]alir
Opcion: '''))
if command == 'a':
name = str(input('Escribe el nombre del contacto: '))
phone = str(input('Escribe el telefono del contacto: '))
email = str(input('Escribe el email del contacto: '))
contact_book.add(name, phone, email)
elif command == 'ac':
print('actualizar contacto')
elif command == 'b':
name = str(input('Escribe el nombre del contacto: '))
contact_book.search(name)
elif command == 'e':
name = str(input('Escribe el nombre del contacto: '))
contact_book.delete(name)
elif command == 'l':
contact_book.show_all()
#print('listar contactos')
elif command == 's':
break
else:
print('Comando no encontrado')
if __name__ == '__main__':
run() |
10127bc09d0220f9e17404e417c405988e54e1c3 | wuxu1019/1point3acres | /Amazon/count_clump.py | 980 | 3.65625 | 4 | """
count clumps of same color in the tree, here are two clumps below
R
R R
G R B B
G
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
count = 0
def CountClumps(root):
def CountClumpsHelp(root, base):
global count
if not root:
return 0
ct = CountClumpsHelp(root.left, root.val) + 1 + CountClumpsHelp(root.right, root.val)
if root.val == base:
return ct
if ct >= 2:
count += 1
return 0
CountClumpsHelp(root, None)
return count
if __name__ == '__main__':
rt = TreeNode('R')
rt.left = TreeNode('R')
rt.right = TreeNode('R')
rt.left.left = TreeNode('G')
rt.left.right = TreeNode('R')
rt.right.left = TreeNode('R')
rt.right.right = TreeNode('R')
rt.left.left.left = TreeNode('R')
ans = CountClumps(rt)
print ans
|
7ec2fa0fbf97e5fc56e0608b3944090d8d6b6e60 | commGom/pythonStudy | /백준/개념/링크드리스트.py | 1,769 | 4.09375 | 4 | # 노드 : 칸에 있는 데이터, 다음 칸에 어떤 노드가 연결되어있는지
# 1.Node 클래스 만들기
class Node:
def __init__(self,data):
self.data=data
self.next=None
# 2.링크드리스트 append print insert delete
# 링크드 리스트는 head에 노드만 가지고 있고 노드.next에 노드를 연결하여 리스트를 만든다
class LinkedList:
def __init__(self,data):
self.head=Node(data)
# 링크드 리스트에 노드 추가
def append(self,data):
cur=self.head
while cur.next is not None:
cur=cur.next
cur.next=Node(data)
# 링크드 리스트 출력
def print_all(self):
cur=self.head
while cur is not None:
print(cur.data)
cur=cur.next
# 링크드 리스트 index값으로 접근
def get_node(self,index):
node=self.head
count=0
while count<index:
node=node.next
count+=1
return node
# 링크드 리스트 index 위치에 값 추가
def add_node(self,index,value):
new_node=Node(value)
if index==0:
new_node.next=self.head
self.head=new_node
return
node=self.get_node(index-1)
next_node=node.next
node.next=new_node
new_node.next=next_node
# index로 접근하여 원소 삭제하기
def delete_node(self,index):
if index==0:
self.head=self.head.next
node=self.get_node(index-1)
node.next=node.next.next
list=LinkedList(5)
list.append(12)
list.append(6)
result=list.get_node(1).data
print(result)
list.add_node(2,7)
list.print_all()
list.delete_node(1)
list.print_all()
|
14df1fb6801a97164fbd15cb7e9b3a61355a306d | Ukabix/python-basic | /core ideas/functions/function call multiple.py | 682 | 3.921875 | 4 | # wywołanie bez domyślnego arg:
def get_integer(help_text):
return int(input(help_text))
age = get_integer("Tell me your age: ") # tutaj zwróci podany tekst
school_year = get_integer("What grade are you in? ") # tutaj zwróci podany tekst
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
# wywołanie z domyślnym arg
def get_integer(help_text="Give me a number: "): # tutaj zwróci podany tekst
return int(input(help_text)) # tutaj zwróci domyślny tekst
age = get_integer("Tell me your age: ")
school_year = get_integer()
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
|
26ed2fe2b2662f8849a1131fb00760080c29db46 | kashyapa/interview-prep | /revise-daily/epi/revise-daily/9_heaps/1_merge_sorted_files.py | 590 | 3.859375 | 4 | import heapq
def merge_sorted_lists():
min_heap = []
for i, one_d_list in enumerate(two_d_list):
heapq.heappush(min_heap, (one_d_list[0], 0, one_d_list))
result = []
while min_heap:
val, list_index, one_d_list = heapq.heappop(min_heap)
result.append(val)
if list_index+1 < len(one_d_list):
heapq.heappush(min_heap, (one_d_list[list_index+1], list_index+1, one_d_list))
return result
if __name__ == '__main__':
two_d_list = [[3, 7, 23, 456, 653, 864], [23, 34, 567, 578, 678, 9832]]
print(merge_sorted_lists())
|
ad19f07b9347aaa327473251e4f57ebec45f651a | ishank-dev/College-Work | /Semester5/Scripting Languages Lab/SEE/Scripting/6/6b/6bprac.py | 821 | 3.90625 | 4 | class Reverse:
def __init__(self,sentence):
self.sentence = sentence
def reverse(self):
reverseSen = ' '.join(reversed(self.sentence.split()))
# print(reverseSen,'\n\n')
return reverseSen
def vowelCount(self):
count = 0
vowels = ['a','e','i','o','u']
for i in self.sentence.lower():
if i in vowels:
count += 1
return count
# REMEMBER TO TAKE STRING WITH DIFFERENT VOWEL COUNT otherwise dictionary will not be able to hold the duplicates
r1 = Reverse(input("Enter a string"))
r2 = Reverse(input("Enter another string"))
r3 = Reverse(input("Enter the third one"))
c1 = r1.vowelCount()
c2 = r2.vowelCount()
c3 = r3.vowelCount()
wordsDesc = {
c1:r1.reverse(),
c2:r2.reverse(),
c3:r3.reverse()
}
for i in sorted(wordsDesc.keys(),reverse=True):
print(i,wordsDesc[i]) |
6e4845730f47d32663a1234d1c5d3c31c60f6c2e | jingyiZhang123/leetcode_practice | /recursion_and_backtracking/93_restore_ip_addresses.py | 939 | 3.703125 | 4 | """
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
"""
class Solution(object):
def _restore(self, soFar, rest):
if not rest:
if len(soFar) == 4:
self.result.append(soFar)
return
if len(soFar) >= 4:
return
for i in range(0, min(3, len(rest))):
next = rest[:i+1]
if int(next) > 255 or (len(next) > 1 and next[0] == '0' ):
continue
remaining = rest[i+1:]
self._restore(soFar+[next], remaining)
def restoreIpAddresses(self, s):
self.result = []
self._restore([], s)
return ['.'.join(x) for x in self.result]
print(Solution().restoreIpAddresses('0000'))
|
e10b06c5ce47f618628e4cb5b72ea831e573d992 | alaa-samy/Tic-Tac-Toe | /tic-tac-toe.py | 3,797 | 4 | 4 |
board = [' ' for i in range(10)]
def insert_letter(letter,position):
board[position] = letter
def space_is_free(position):
return board[position] == ' '
def print_board(board):
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('----------------')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('----------------')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
def is_winner(bo, le):
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def is_board_full(board):
if board.count(' ') > 1:
return False
else:
return True
def player_move():
run = True
while run:
move = input('Please select a position to place an \'X\' (1-9): ')
try:
move = int(move)
if (move > 0 and move < 10):
if space_is_free(move):
run = False
insert_letter('X' , move)
else:
print('This position is already occupied')
else:
print('Please type a number within range 10')
except:
print('Please type a number')
def select_random(li):
import random
ln = len(li)
r = random.randrange(0,ln)
return li[r]
def computer_move():
possible_moves = [x for x , letter in enumerate(board) if letter == ' ' and x != 0]
move = 0
for letter in ['O', 'X']:
for i in possible_moves:
board_copy = board[:]
board_copy[i] = letter
if is_winner(board_copy, letter):
move = i
return move
# Take one of the corner
corners_open = []
for i in possible_moves:
if i in [1,3,7,9]:
corners_open.append(i)
if len(corners_open) > 0:
move = select_random(corners_open)
return move
# Try to take the center
if 5 in possible_moves:
move = 5
return move
# Take one of the edges
edges_open = []
for i in [2,4,6,8]:
edges_open.append(i)
if len(edges_open) > 0:
move = select_random(edges_open)
return move
def main():
print('Welcome to Tic Tac Toe!')
print_board(board)
while not(is_board_full(board)):
if not(is_winner(board, 'O')):
player_move()
print_board(board)
else:
print('Sorry, O\'s won this time!')
break
if not(is_winner(board, 'X')):
move = computer_move()
if move == 0:
print('Tie Game!')
else:
insert_letter('O', move)
print('Computer placed an \'O\' in position', move , ':')
print_board(board)
else:
print('X\'s won this time! Good Job!')
break
if is_board_full(board):
print('Tie Game!')
while True:
answer = input('Do you want to play again? (Y/N)')
if answer.lower() == 'y' or answer.lower == 'yes':
board = [' ' for x in range(10)]
print('-----------------------------------')
main()
else:
break
|
caaa8fb142f2ad4be294bb2364a46bba452b11a7 | bhaumeek/music_recommendation | /Music Recommender/music.py | 993 | 3.765625 | 4 | import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier #sklearn is the package & algoritm udes is decision tree
import joblib #used for saving and loading models
music_data = pd.read_csv('music.csv')
#music_data #in the csv file 1 is given for male and 0 is given for female
#we will now give split the dataset into input set and output set: i/p user is 21 years old and is male output set: what is the genre of music he might like
#we do not want to train ourr module every time therefore commented
X = music_data.drop( columns=['genre'])#returns input data set
# #.drop creates another dataset without the specified column
# X
y = music_data['genre']#returns output data set#algorithm used is: decision tree
model = DecisionTreeClassifier()
model.fit(X,y)
#model = joblib.load('music-recommender.joblib')#stores the name of the file where in we are saving the trained data set
predictions = model.predict(np.array([[21, 1]]))
predictions
|
c855a09628e68e1828d167f081c76688e579f18a | chc1129/introducing-python3 | /chap05/stdlib6.py | 563 | 3.515625 | 4 | from collections import Counter
breakfast = ['spam', 'spam', 'eggs', 'spam']
breakfast_counter = Counter(breakfast)
print(breakfast_counter)
print(breakfast_counter.most_common())
print(breakfast_counter.most_common(1))
breakfast_counter
Counter({'spam': 3, 'eggs': 1})
lunch = ['eggs', 'eggs', 'bacon']
lunch_counter = Counter(lunch)
print(lunch_counter)
print(breakfast_counter + lunch_counter)
print(breakfast_counter - lunch_counter)
print(lunch_counter - breakfast_counter)
print(breakfast_counter & lunch_counter)
print(breakfast_counter | lunch_counter)
|
f12cbccc204786404b5329a0e5e40cf4591315b3 | rlavanya9/hackerrank | /datastructures/practice1.py | 1,522 | 3.75 | 4 | # def binary_search_arr(a, key, low, high):
# if low > high:
# return -1
# mid = low + ((high-low)//2)
# if a[mid] == key:
# return mid
# elif key < a[mid]:
# return binary_search_arr(a, key, low, mid-1)
# else:
# return binary_search_arr(a, key, mid+1, high)
# def binary_search(a, key):
# return binary_search_arr(a, key, 0, len(a)-1)
# arr = [1, 10, 20, 47, 59, 63, 75, 88, 99, 107, 120, 133, 155, 162, 176, 188, 199, 200, 210, 222]
# inputs = [10, 49, 99, 110, 176]
# for i in range(len(inputs)):
# print("binary_search(arr, " + str(inputs[i])+ ") = " + str(binary_search(arr, inputs[i])))
# inventory = [15, 100, 110, 200]
# you want to return output that has atleast 105
# input:
# capacity needed, list of inventory
# output:
# closest match for inventory
def Inventory_Match(capacity, myinvent, low, high):
match = []
mid = low + ((high-low)//2)
if myinvent[mid] == capacity:
return myinvent[mid]
elif myinvent[mid] > capacity:
return Inventory_Match(capacity,myinvent, low, mid-1)
else:
return Inventory_Match(capacity, myinvent, mid+1, high)
def Invent(capacity, myinvent):
return Inventory_Match(capacity, myinvent, 0, len(myinvent)-1)
# for element in myinvent:
# if element >= capacity:
# match.append(element)
# print(match)
# match_srt = sorted(match)
# return match_srt[0]
print(Inventory_Match(105,[15,100,110,200]))
|
9fe1deb49cf847916162a055224ccf4dc418d85c | fredy-prudente/python-brasil-exercicios | /Estrutura De Decisao/ex19.py | 893 | 3.875 | 4 | """
Faça um Programa que leia um número inteiro menor que 1000 imprima a quantidade de centenas, dezenas e unidades do mesmo
Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo:
326 = 3 centenas, 2 dezenas e 6 unidades
"""
n = int(input('Digite um numero menor que 1000: '))
strn = str(n)
ntotal = len(strn)
cs = ''
ds = ''
us = ''
if ntotal == 3:
if strn[0] > '1':
cs = 's'
if strn[1] > '1':
ds = 's'
if strn[2] > '1':
us = 's'
print(f'{strn[0]} centena{cs}, {strn[1]} dezena{ds}, {strn[2]} unidade{us}.')
elif ntotal == 2:
if strn[0] > '1':
ds = 's'
if strn[1] > '1':
us = 's'
print(f'{strn[0]} dezena{ds}, {strn[1]} unidade{us}.')
elif ntotal == 1:
if strn[0] > '1':
us = 's'
print(f'{strn[0]} unidade{us}.')
else:
print('Somente de 0 a 1000!')
|
2f5bddfbf59e2064e16bf187874b49efa0e4f619 | arturolearczuk/zadania | /zad2(czynniki).py | 366 | 3.609375 | 4 | def rozloz(liczba):
dz = 2
while liczba > 1:
while liczba % dz == 0:
print(f"{liczba} {dz}")
liczba = liczba // dz
dz += 1
print("Podaj zakres Liczb jakich chcesz rozłożyc na czynniki")
x = int(input("Od: "))
y = int(input("Do: "))
for i in range(x, y):
print(f"Rozkład {i}")
(rozloz(i)) |
869752d60753074d446a7f313645f25fec32956b | pbarden/python-course | /Chapter 10/extra_credit.py | 327 | 3.734375 | 4 | test_grades = [101, 83, 107, 90]
sum_extra = -999 # Initialize 0 before your loop, useless initialization provided by the assignment instructions
sum_extra = 0 # Correct the default, srsly why would -999 be useful here at all!?
for n in test_grades:
if n > 100:
sum_extra += n % 100
print('Sum extra:', sum_extra) |
ec994851e653c108b2081d71ce6616aaa19b7382 | tabatafeeh/URI | /python/1008.py | 165 | 3.921875 | 4 | # -*- coding: utf-8 -*-
num = int(input(""))
numh = int(input(""))
salh = float(input(""))
salt = numh * salh
print ("NUMBER = %d\nSALARY = U$ %.2f" %(num, salt)) |
eaff9a41194a242db9f2bec92bd6380e9c5ce836 | tianlelyd/pythonPainting | /画电脑.py | 3,206 | 3.6875 | 4 | # 画电脑
from turtle import *
tracer(50)
def computer(): #start from the most northwest corner of the computer.
pensize(4)
pencolor('blue')
seth(10)
circle(-500,16)
rt(90)
fd(10)
rt(90)
circle(500,14)
lt(85)
fd(85)
rt(90)
fd(15)
rt(90)
fd(90)
rt(120)
fd(90)
seth(265)
circle(500,8)
lt(88)
circle(550,9)
seth(90)
fd(60)
lt(85)
circle(500,10)
pu()
seth(40)
fd(79)
seth(-63)
pd()
fd(52)
pu()
seth(-160)
fd(147)
seth(-22)
pd()
fd(63)
pu()
bk(20)
seth(-120)
pd()
circle(17,60)
lt(30)
circle(50,50)
lt(30)
circle(17,60)
pu()
lt(180)
circle(-17,60)
seth(-40)
pd()
circle(-50,40)
seth(-160)
circle(-100,42)
seth(90)
circle(-50,40)
pu()
left(180)
circle(-50,10)
seth(-39)
pd()
circle(50,70)
def square(): #the key on the keyboard,start from the most southeast corner of the computer.
seth(110)
fd(7)
lt(90)
fd(9)
lt(90)
fd(7)
lt(90)
fd(9)
def keyboard(): #start from the most southeast corner of the computer.
pencolor('red')
seth(110)
fd(20)
lt(90)
fd(120)
lt(110)
fd(40)
lt(73)
fd(100)
seth(100)
pu()
fd(5)
pd()
square()
bk(9)
square()
bk(9)
square()
bk(9)
square()
bk(9)
square()
bk(9)
square()
bk(9)
fd(45+9)
lt(90)
fd(7)
square()
bk(9)
square()
bk(9)
square()
pu()
bk(18)
lt(90)
fd(7)
pd()
fd(7)
lt(90)
fd(35)
lt(90)
fd(7)
lt(90)
fd(35)
pu()
bk(44)
pd()
square()
bk(9)
square()
fd(9)
rt(90)
fd(7)
square()
bk(9)
square()
fd(9)
rt(90)
fd(7)
square()
bk(9)
square()
def programmer(): #start from the most southeast corner of the programmer.
pencolor('purple')
seth(90)
fd(50)
seth(45)
circle(70,10)
pu()
circle(70,58)
pd()
circle(70,202)
seth(-100)
circle(500,10)
pu()
seth(70)
fd(170)
pd()
seth(-90)
fd(15)
rt(80)
fd(10)
seth(25)
pu()
fd(45)
pd()
seth(-70)
fd(15)
seth(10)
fd(10)
pu()
seth(-100)
fd(15)
seth(-175)
pd()
pensize(8)
fd(1)
pu()
fd(40)
pd()
fd(1)
pensize(4)
seth(-30)
pu()
fd(20)
pd()
seth(-40)
circle(13,50)
def questionmark(theta): #the beginning angle is theta
pd()
pensize(4)
seth(theta)
fd(6)
circle(-8,180)
lt(60)
pu()
fd(12)
pd()
pensize(5)
fd(1)
pu()
computer()
pu()
seth(-170)
fd(65)
pd()
pensize(3)
keyboard()
pu()
seth(180)
fd(130)
pd()
pensize(3)
pencolor('black')
seth(20)
fd(237)
pu()
fd(114)
pd()
fd(40)
rt(50)
fd(60)
pu()
bk(60)
rt(130)
fd(220)
pd()
programmer()
pu()
seth(105)
fd(120)
questionmark(30)
seth(40)
fd(30)
questionmark(15)
seth(1)
fd(30)
questionmark(1)
seth(145)
fd(135)
pd()
pencolor('black')
write('Python还能画画',move=False,align="left",font=("华文彩云",23,'normal'))
ht()
update()
done() |
3e38a5c4e71084f6bcd47000deb20a7ec047f9b5 | dataders/AJS | /codechef/TRISQ/TRISQ_sub_joel.py | 171 | 3.53125 | 4 | T = int(input())
for i in range(T):
C = int(input())
if C <= 3:
fx = 0
else:
gx = int(0.5*(C-2))
fx = int(0.5*gx*(gx+1))
print(fx)
|
7b8ca5348a79601ee822db195a41203bd2d700ed | sjc2870/LeetCode | /python/string/buddyStrings.py | 624 | 3.5 | 4 | #!/usr/bin/env python3
#coding=utf-8
''' leetcode issue 859 '''
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B): # 长度不相等必定不符合
return False
idx =[i for i in range(len(A)) if A[i] != B[i]]
if len(idx) == 2 and A[idx[0]] == B[idx[1]] and A[idx[1]] == B[idx[0]]: # 两个字符串交换两次完全相同
return True
if len(idx) == 0 and len(A)-len(set(A)) > 0: # 字符串完全相同,且单个字母出现超过两次(超过两次的字母交换不影响)
return True
return False
|
2ebc6da08605492ddf109d63398e7e936353f0bf | nikitabuts/Image-classification | /DataCreator.py | 5,063 | 3.90625 | 4 | import matplotlib.pyplot as plt
import numpy as np
class Functions:
def __init__(self, x, a, b, alpha):
self.x = x
self.y = self.x.copy()
self.a = a
self.b = b
self.alpha = alpha
@staticmethod
def _reverse(f, x, y):
x_2 = x * np.cos(f) - y * np.sin(f)
y_2 = x * np.sin(f) + y * np.cos(f)
return x_2.copy(), y_2.copy()
def parabola(self):
y = self.a * np.power(self.x, 2) + self.b * self.x + np.random.randint(-100, 100, 1)
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def hyperbola(self): # При вызове этого метода лучше определять self.x как np.arange(-30, 31, 0.5)
y = (self.a / self.x) + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def abs(self):
y = self.a * np.abs(self.x) + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def sigmoid(self):
y = self.a / (1 + np.power(np.e, -self.x)) + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def linear(self):
y = self.a * self.x + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def sin(self):
y = self.a * np.sin(self.x) + self.b # Метод не использовался при генерации данных
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def cos(self):
y = self.a * np.cos(self.x) + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
def logarifm(self):
y = self.a * np.log(self.x) + self.b
x, y = self._reverse(self.alpha, self.x, y)
return x, y
class DataGenerator:
def __init__(self, a_len, b_len, alpha_len, random_comand="randn", alpha_initialize="base_circle"):
np.random.seed(17)
if random_comand == "randn":
self.a = np.random.randn(a_len)
self.b = np.random.randn(b_len)
elif random_comand == "randint":
self.a = np.random.randint(-100, 100, a_len)
self.b = np.random.randint(-100, 100, b_len)
else:
print("message: random_comand should be 'randn' or 'randint'")
raise ValueError
if alpha_initialize == "randn":
self.alpha = np.random.randn(alpha_len)
elif alpha_initialize == "base_circle":
self.alpha = np.array([0, 1/8, -1/8, 1/6, -1/6, 1/3, -1/3, 1/4, -1/4, 1/3, -1/3,
5/8, -5/8, 1/2, -1/2, 5/8, -5/8, 2/3, -2/3, 3/4, -3/4,
5/6, -5/6, 7/8, -7/8, 1]) * np.pi
else:
print("message: alpha_initialize should be 'randn' or 'base_circle'")
raise ValueError
self.x = np.arange(-20, 21, 0.5)
self.y = self.x
def fig_plot(self, function, ax=True, save=False, plot=True, verbose=100): #Если save=True - то укажите свой PATH --> код ниже
counter = 0
var_x = self.x.copy()
var_y = self.y.copy()
for theta in self.alpha:
for alpha in self.a:
for beta in self.b:
func = Functions(x=var_x, a=alpha, b=beta, alpha=theta)
if function == 'parabola':
x, y = func.parabola()
elif function == 'sigmoid':
x, y = func.sigmoid()
elif function == 'abs':
x, y = func.abs()
elif function == 'hyperbola':
x, y = func.hyperbola()
elif function == 'linear':
x, y = func.linear()
elif function == 'sin':
x, y = func.sin()
elif function == 'cos':
x, y = func.cos()
elif function == 'log':
x, y = func.logarifm()
if (y != var_y).any():
fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')
plt.plot(x, y)
if ax:
plt.axvline(0, linestyle="--")
plt.axhline(0, linestyle="--")
if plot:
plt.show()
else:
plt.close()
if save:
counter += 1
PATH = "C:\Project_images" + "\\" + str(function) + '_' + str(counter) + ".png"
if counter % verbose == 0:
print(PATH)
fig.savefig(PATH)
|
ba3606232a9bd13c27296d7c0e69c046b83ffbcf | penguin-wwy/leetcode | /source/29-Divide Two Integers/29. Divide Two Integers.py | 1,081 | 3.671875 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if dividend == 0 or divisor == 0:
return 0
flag = 1
res = 0
tmp_dividend = dividend
tmp_divisor = divisor
more = 0
if dividend < 0:
flag *= -1
tmp_dividend = -1 * dividend
if divisor < 0:
flag *= -1
tmp_divisor = -1 * divisor
if tmp_dividend < tmp_divisor:
return 0
elif tmp_dividend == tmp_divisor:
return flag
while tmp_dividend > tmp_divisor:
while tmp_dividend > (tmp_divisor << more):
more += 1
if tmp_dividend == (tmp_divisor << more):
res += 1 << more
break
res += 1 << (more - 1)
tmp_dividend -= (tmp_divisor << (more - 1))
more = 0
if tmp_dividend == tmp_divisor:
res += 1
return flag * res |
2a4d577008b1aee3b290917d7c9b4b61264bcad0 | OscarVegener/TicTacToe | /main.py | 3,494 | 3.796875 | 4 | def paint():
print("---------")
print("| " + nested_lst[0][0] + " " + nested_lst[0][1] + " " + nested_lst[0][2] + " |")
print("| " + nested_lst[1][0] + " " + nested_lst[1][1] + " " + nested_lst[1][2] + " |")
print("| " + nested_lst[2][0] + " " + nested_lst[2][1] + " " + nested_lst[2][2] + " |")
print("---------")
def get_result():
global nested_lst
counter = 0
# horizontal x
for i in range(3):
counter = 0
for j in range(3):
if nested_lst[i][j] == 'X':
counter += 1
if counter == 3:
paint()
print("X wins")
return True
else:
counter = 0
# vertical x
for i in range(3):
counter = 0
for j in range(3):
if nested_lst[j][i] == 'X':
counter += 1
if counter == 3:
paint()
print("X wins")
return True
else:
counter = 0
# horizontal o
for i in range(3):
counter = 0
for j in range(3):
if nested_lst[i][j] == 'O':
counter += 1
if counter == 3:
paint()
print("O wins")
return True
else:
counter = 0
# vertical o
for i in range(3):
counter = 0
for j in range(3):
if nested_lst[j][i] == 'O':
counter += 1
if counter == 3:
paint()
print("O wins")
return True
else:
counter = 0
# diagonal x
if nested_lst[0][0] == 'X' and nested_lst[1][1] == 'X' and nested_lst[2][2] == 'X':
paint()
print("X wins")
return True
if nested_lst[0][2] == 'X' and nested_lst[1][1] == 'X' and nested_lst[2][0] == 'X':
paint()
print("X wins")
return True
# diagonal o
if nested_lst[0][0] == 'O' and nested_lst[1][1] == 'O' and nested_lst[2][2] == 'O':
paint()
print("O wins")
return True
if nested_lst[0][2] == 'O' and nested_lst[1][1] == 'O' and nested_lst[2][0] == 'O':
paint()
print("O wins")
return True
# draw
counter = 0
for i in range(3):
for j in range(3):
if nested_lst[i][j] == " ":
counter += 1
if counter == 0:
paint()
print("Draw")
return True
# not finished
return False
finished = False
nested_lst = []
for i in range(3):
nested_lst.append([])
for j in range(3):
nested_lst[i].append(" ")
move = 0
paint()
while not finished:
x, y = input("Enter the coordinates: ").split()
try:
x = int(x)
y = int(y)
except ValueError:
print("You should enter numbers!")
continue
if x > 3 or x < 1 or y > 3 or x < 1:
print("Coordinates should be from 1 to 3!")
continue
else:
x = abs(x - 1)
y = abs(y - 3)
if nested_lst[y][x] == ' ':
if move % 2 == 0:
nested_lst[y][x] = 'X'
else:
nested_lst[y][x] = 'O'
move += 1
finished = get_result()
if finished:
break
paint()
else:
print("This cell is occupied! Choose another one!") |
c8e09e16c9947de834fc0ecd585285eaced75a94 | naveensakthi04/PythonTraining | /Basics/basics.py | 7,161 | 4.09375 | 4 | import math as M
from math import ceil
print("Hello World!")
print(5 // 2)
print(5 / 2)
print(2 * 7)
print(2 ** 7)
print('Hello World')
print('''Naveen''')
print('''Naveen''')
print("\"Naveen\"")
print(10 * "Naveen ", end=" ")
print(r'\naveen')
x = 10
y = 12
print(x + y)
# split function
print("Hai "+"Hello:World".split(":")[0])
# LIST OPERATIONS => min, max, sum, insert, append, sort, reverse
# LIST OPERATORS => in, not in, :, []
print("------------------------")
print("LIST OPERATIONS")
x = "Hello World"
print(x)
print(x[2:])
print(x[:4])
print(x[2:7])
print(x[-5:])
print("-5 to -9 " + x[-5:-9])
print(x[:-1])
print(x[-1:])
print(x[-1:-1])
print("length of \"" + x + "\" is " + str(len(x)))
print(x[::-1])
print(x[3:7:3])
print("---------------------------------")
nums = [1, 2, 3, "four"]
print(nums)
names = ["hello", "bye", 'all']
nums.extend(names)
print(nums, names)
nums.append(1)
print(nums)
nums.insert(3, "hello")
print(nums)
nums.pop(3)
print(nums)
del nums[3:7]
print(nums)
print(min(nums))
nums.sort()
print(nums)
nums[2] = 120
print(nums)
# nums[24] = 120 //exits with code 1
# print(nums) no error... but it will not be inserted
#
# LISTS - TUPLE - SET
# mutable - immutable - mutable
# slow - fast - fast
# insertion_order - insertion_order - hash_order
# indexing - indexing - no_indexing
# not_type_specific - not_type_specific - not_type_specific
# duplicates - no_duplicates -
nums = (1, 2, 3)
print(nums)
print(nums[2])
tup = (12, 14, 15, "hello", 12)
print(tup)
set0 = {1, 6, 4, 2, 4, "Hello"}
print(set0)
# set[2] //not possible
a = True
print(not a)
# SET OPERATIONS => union, intersection, difference, symmetric_difference
print("------------------------")
print("SET OPERATIONS")
# remove() throws error if specified item is not present
# discard() removes item if it is present, else nothing happens
a = {101, 2, 63, 4, 5, "a"}
b = {4, 5, 6, 7, 8, 'a'}
print("before poping")
print(a)
a.pop()
print("poping")
print(a)
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
print(a)
print(b)
a.difference_update(b)
print(a)
b.symmetric_difference_update(a)
print(b)
# DICTIONARY OPERATIONS =>
# key = immutable : value = mutable
print("------------------------")
print("DICTIONARY OPERATIONS")
captains = {'England': 'Root', 'Australia': 'Smith', 'India': 'Virat', 'Pakistan': 'Sarfraz'}
print(captains.keys())
print(captains.values())
print(captains["England"])
del captains['England']
print(captains)
captains["Australia"] = "Finch"
print(captains)
print(min(captains))
s1 = {"name": "Nitsh", "age": 21, "marks": 60}
s2 = {"name": "Naveen", "age": 21, "marks": 80}
s3 = {"name": "Sarvesh", "age": 21, "marks": 90}
interns = {1: s1, 2: s2, 3: s3}
print(interns)
print(interns[1]["marks"])
print(len(interns))
print(len(interns[2]))
print("------------------------------------")
print("ID")
a = 10
b = 10
print("a = 10 b = 10 ")
print(id(a))
print(id(b))
print(id(10))
print("id(9)", end=" ")
print(id(9))
print("a = 11")
a = 11
print(id(a))
print(id(b))
print(a.__sizeof__())
a = "STRING"
print(a.__sizeof__())
a = "s"
print(a.__sizeof__())
# ::::::::::::::::::::::::::::::::::::::::
# :::::::::::::::\./::::::::::::::::::::::
# :::::::::::::::.\.::::::::::::::::::::::
# :::::::::::::::/.\::::::::::::::::::::::
# :::UNFORTUNATELY NO CONSTS IN PYTHON::::
# ::::::::::::::::::::::::::::::::::::::::
print("DATATYPES")
print(type(a))
print(type(captains))
print(type(nums))
print(type(None))
print(type(1 + 3j))
print(type(False))
a = 5
print(complex(a))
print(type(a))
print(type(float(a)))
print(bool(4))
print(bool(-4))
print(bool(0))
a = range(2, 10, 3)
print(a)
a = list(range(2, 10, 3))
print(a)
a = tuple(range(2, 10, 3))
print(a)
a = set(range(2, 10, 3))
print(a)
print("----------------------------")
print("OPERATORS")
x = 1
x += 2
print(x)
m, n = 1, 6
print(m, n)
m, n = n, m
print(m, n)
# and or not
# > < == <= >= !=
# ~ & | ^ << >>
print(~13)
# MATH FUNCTIONS
print(M.factorial(12))
a = ceil(1.1)
print(a)
# INPUT
# Converting from float rep as string to int
# x = int(float(input("Enter a number")))
# print(x)
#
# x = input("Enter a char")[0]
# print(x)
#
# x = eval(input("Enter a expr"))
# print(x)
# for command line input
# import sys
# x = sys.argv[1]
print("------------------------------------------")
print("Type Conversion")
print("bool(\"\")")
print(bool(""))
print("bool(\"False\")")
print(bool("False"))
# CONDITIONAL STATEMENTS
print("--------------------------------------------")
print("CONDITIONAL STATEMENTS")
if 1000 < 100:
print("10 is less than 100")
else:
if 100 == 12:
print("Hello")
elif (100 > 12): # parenthesis is optional
print("Hello all")
else:
print("Welcome")
# LOOPS
print("--------------------------------------------")
print("LOOPS")
num = 0
while num < 5:
num = num + 1
print("num =", num)
else:
print("END")
for x in range(1, 4):
print("Hello", end="")
for y in range(x, 15, 3):
print(" World" + str(y), end="")
print()
dict = {1: 100, 2: 200, 3: 300}
for k in dict.keys():
print(k, dict.get(k))
for k in dict.items():
print(k)
for k, v in dict.items():
print(k, v)
# break - exits loop
# continue - skips current iteration
# pass - does nothing... not considered as a statement by the interpreter
# FUNCTIONS
print("----------------------------------")
print("FUNCTIONS")
def add_sub(_1, _2):
_a = _1 + _2
_b = _1 - _2
return _a, _b
s, m = add_sub(10, 56)
print("check")
print(m)
print(s)
def greet(name):
print("Hello" + " " + name)
return
greet("Naveen")
# for immutable objects python is call by value like thing... not exactly
# for mutable objects python call by reference
print("CALL BY VALUE OR REFERENCE")
print("IMMUTABLE")
def update_immutable(x):
print(id(x))
x = 20
print(id(x))
print(x)
return
x = 10
print(id(x))
print(x)
update_immutable(x)
print(x)
print("MUTABLE")
def update_mutable(x):
print(id(x))
x[1] = 21
print(id(x))
print(x)
return
x = [10, 20, 30]
print(id(x))
print(x)
update_mutable(x)
print(x)
# TYPES OF ARGUMENTS
# POSITION is the default
# KEYWORD
def person(name, age):
print(name)
print(age)
person(age=21, name="Naveen")
# DEFAULT
def person1(name, age=30):
print(name)
print(age)
person1(name="Naveen")
# VARIABLE LENGTH
def addVarialbeLength(*x):
_s = 0
for i in x:
_s += i
print("sum=", end=" ")
print(_s)
addVarialbeLength(5,6,7,8,9)
# KEYWORDED VARIABLE LENGTH ARGUMENTS
def _person(**x):
for i,j in x.items():
print(i,j)
_person(name="Naveen", age="21", city="Coimbatore")
|
b733170325793d63b2db089bb0a4a31dd5d36c55 | dimaape/GeekBrains_Python_Course | /Lesson_1/GB_Py_HW_1_1.py | 1,252 | 4.34375 | 4 | # Задание 1.1
# Поработайте с переменными, создайте несколько, выведите на экран
print("Поработайте с переменными, создайте несколько, выведите на экран.\n")
var_a = 0
var_b = "some text"
var_c = 10
var_d = "some text again"
print(var_a, var_b, var_c, var_d, sep='\n')
# Запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
print("\nЗапросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.\n" +
"Нет обработчика ошибок. Но это и не в данном уроке.\n")
user_input_int_a = int(input("Please provide any integer:\n--> "))
user_input_float_a = float(input("Please provide any float number:\n--> "))
user_input_str_a = str(input("Please provide any string:\n--> "))
user_input_str_b = str(input("Please provide another string:\n--> "))
print(user_input_int_a, user_input_float_a, user_input_str_a, user_input_str_b, sep='\n')
|
65b070c3ff4e9cf6551eb5fa776b623d01aab524 | madiyar99/webdev2019 | /week10/hackerrank/9.py | 334 | 3.75 | 4 | n = int(input())
arr = []
for i in range(n):
lis = list(input().split())
arr.append(lis)
name = input()
for i in range(n):
if(arr[i][0] == name):
math = float(arr[i][1])
physics = float(arr[i][2])
chemistry = float(arr[i][3])
average = float((math + physics + chemistry) / 3)
break
print('{0:.2f}'.format(average))
|
431be85fffa91b7b0bc2c879bc867de4379a3bbf | tslator/arlobot_rpi | /src/arlobot/environment/onoffmonitor.py | 2,108 | 3.71875 | 4 | #! /usr/bin/env python
from __future__ import print_function
# The purpose of this script is to allow the Raspberry Pi to shutdown gracefully when the Arlobot power switch is turned
# off.
# Idea stolen from here: https://www.element14.com/community/docs/DOC-78055/l/adding-a-shutdown-button-to-the-raspberry-pi-b
#
# The Arlobot PC uses the M4-ATX power supply which is connected directly to the battery and contains logic to maintain
# power long enough to allow the PC to shutdown gracefully. This logic is being leveraged for the Raspberry Pi by
# connecting the PowerPi to the 12v rail of the M4-ATX which means the Raspberry Pi will power up/down at the same time as
# the PC. Additionally, the ATX protocol supports a 3.3v signal which notifies the motherboard when power is being
# removed.
#
# To ensure graceful shutdown on the RaspberryPi a script (below) monitors the On/Off signal from the M4 via a GPIO pin.
# When there is a change on the pin the callback executes the shutdown command. The script will run from /etc/rc.local.
#
# Script Basics:
# - Run the script automatically via /etc/rc.local
# - Register a callback on a pin change event
# - When there is a pin change event, execute the OS shutdown command
# Notes:
# How much debounce is needed?
# Is there a need to stabilize the input,
# Should we count the number of pulses then only issue shutdown after a certain number.
# Need to characterize the On/Off signal
# Is this a 5v or 3.3v signal?
#
import RPi.GPIO as GPIO
import os
import time
M4_ON_OFF_PIN = 40 # Pin 40, GPIO21
def OnOffChanged(channel):
'''
Monitor pin x which is connected to the on/off signal from the M4 power supply. When there is a change to the input
this is a notification to shutdown the Raspberry Pi OS
:return:
'''
print("OnOff pin changed: ", GPIO.input(channel))
#os.system("sudo shutdown -h now")
GPIO.setmode(GPIO.BOARD)
GPIO.setup(M4_ON_OFF_PIN, GPIO.IN)
GPIO.add_event_detect(M4_ON_OFF_PIN, GPIO.BOTH, callback=OnOffChanged, bouncetime=200)
while 1:
time.sleep(1)
|
ed253782297205366fa4fabcc628823aac342e93 | kamath7/Automate-The-Boring-Stuff-Al | /Basics/app12.py | 1,048 | 4 | 4 | #Dictionaries
my_dict = {'name':'Kams','age':25,'nationality':'Indian'}
print('My name is {0}'.format(my_dict['name'],))
some_other_dict = {0:'India',1:'Brazil',2: 'Argentina'}
print(some_other_dict)
#Comparing two same dictionaries
a_dict = {'name':'Kams','age':29,'nationality': 'Indian'}
b_dict = {'age':29,'nationality': 'Indian','name':'Kams'}
print(a_dict == b_dict) #Works?
print('name' in my_dict) #Checking if key exists in a dictionary
#Dictionaries are mutable
print(list(my_dict.keys()))
print(list(my_dict.items()))
print(list(my_dict.values()))
for k,v in my_dict.items():
print(k,v)
if 'name' in my_dict.keys():
print('Good')
print(my_dict.get('Name','John Doe')) #get - use it to check if a value exists else use the alternate in the second arguement
my_dict.setdefault('city','Mangalore')
print(my_dict)
#Lalle Program
message = 'a quick brown fox jumped over the lazy dog'
count = {}
for letter in message.lower().replace(" ",""):
count.setdefault(letter, 0)
count[letter] = count[letter] + 1
print(count) |
5a3eaff983d3c29af6f5cd01105ed957748126d4 | lxgzhw520/ZhangBaofu | /day029/hw_001_双下str方法.py | 629 | 3.859375 | 4 | # _*_ coding:UTF-8 _*_
# 开发人员: 理想国真恵玩-张大鹏
# 开发团队: 理想国真恵玩
# 开发时间: 2019-04-16 08:32
# 文件名称: hw_001_双下str方法.py
# 开发工具: PyCharm
# 内置的类方法和内置的函数之间关系非常紧密
print(repr(1))
print(repr('1'))
print(1, '1')
print('--' * 22)
class A:
def __str__(self):
return 'A的说明信息:原生调用的是地址{}'.format(id(self))
a = A()
# 实际上是调用了类的 __str__方法
print(str(a))
print(a)
class B:
def __str__(self):
return "{}:{}".format('B', id(self))
pass
b = B()
print(b)
|
9e689a2c59b920a5dc21212d0f557c13e1a54773 | mjgutierrezo/MCOC-Nivelaci-n- | /23082019/000300.py | 1,089 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Aplicar ciclo while para recorrer una lista y someter a los elementos dentro de ella a condiciones
"""
from numpy import *
#000300
given_list = [5, 4, 4, 3, 1, -2, -3, -5]
#se quiere obtener la suma de sólo los números positivos de la lista
total = 0
i = 0
# en vez de usar un ciclo for que evalúe cada uno de los elementos de la lista, se crea una condición para ellos con loop while
while i < len(given_list) and given_list[i] > 0:
total += given_list[i] #suma acumulada
i += 1 #modificar variable estudiada en el ciclo para continuar
print (total) #retorna la suma total de elementos que cumplían condición
#000740
#ejecutar ejercicio anterior con ciclo for
total2 = 0
for element in given_list: #recorrer todos los elementos de la lista
if element <= 0: #condición para evaluar números negativos dentro de lista
break #se rompe ciclo if, continúa con for
total2 += element #suma acumulada
print (total2) #retorna total de suma
#"break" también puede ser usado en ciclios while |
70a201e94ffe034bc090275d9939c8a6cd9cf92b | Biscuit28/WKEXP1 | /HTML/main_crawler/tools/dateformat.py | 1,659 | 4 | 4 | def compare_date(sdate, edate):
'''
recursively checks if sdate is bigger than edate
Expects date format to be YY-mm-dd
'''
print sdate
sdate = sdate.split('-')
edate = edate.split('-')
def check(index=0):
if int(sdate[index]) > int(edate[index]):
return False
elif int(sdate[index]) == int(edate[index]):
if index == 2:
return False
return check(index=index+1)
else:
return True
return check()
def format_date(date):
FORMAT = ['Y','M', 'D', 'H', 'Min', 'S']
num_arr, digit = [], ''
Listen_state = False
for ele in date:
if ele.isdigit():
Listen_state = True
elif not ele.isdigit() and Listen_state:
num_arr.append(digit)
digit = ''
Listen_state = False
if Listen_state:
digit += ele
if digit != '':
num_arr.append(digit)
new_date_string = ''
if len(num_arr) == 2:
return '2017-{}-{} 00:00:00'.format(num_arr[0], num_arr[1])
for j in range(len(FORMAT)):
F = FORMAT[j]
try:
N = num_arr[j]
except:
N = '00'
if len(N) == 1:
N = '0' + N
if F == 'Y':
if len(N) < 3:
N = str(2000 + int(N))
new_date_string += N +'-'
if F == 'M':
new_date_string += N +'-'
if F == 'D':
new_date_string += N +' '
if F == 'H' or F == 'Min':
new_date_string += N+':'
if F == 'S':
new_date_string += N
return new_date_string
|
8b2e32a69338825a226d76faafb673f2e3a600af | ssam1994/bootcamp | /lesson_39.py | 1,672 | 3.546875 | 4 | """
Lesson 39: Intro to Image processing
"""
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import pandas as pd
import scipy
import seaborn as sns
sns.set_style('dark')
import skimage.io
import skimage.exposure
import skimage.morphology
import skimage.filters
import skimage.measure
phase_im = skimage.io.imread('data/HG105_images/noLac_phase_0004.tif')
plt.imshow(phase_im, cmap=plt.cm.viridis)
plt.show()
plt.close()
# Apply a gaussian blur to the image.
im_blur = skimage.filters.gaussian(phase_im, 50.0)
# Show the blurred image.
plt.imshow(im_blur, cmap=plt.cm.viridis)
plt.show()
plt.close()
phase_float = skimage.img_as_float(phase_im)
phase_sub = phase_float - im_blur
plt.figure()
plt.imshow(phase_float, cmap=plt.cm.viridis)
plt.title('original')
plt.figure()
plt.imshow(phase_sub, cmap=plt.cm.viridis)
plt.title('subtracted')
plt.show()
plt.close()
thresh = skimage.filters.threshold_otsu(phase_sub)
seg = phase_sub < thresh
plt.close('all')
plt.imshow(seg, cmap=plt.cm.Greys_r)
plt.show()
# Label cells
seg_lab, num_cells = skimage.measure.label(seg, return_num=True, background=0)
plt.imshow(seg_lab, cmap=plt.cm.Spectral_r)
plt.show()
plt.close()
# Compute the regionproperties and extract area of each object.
ip_dist = 0.063 # µm per pixel
props = skimage.measure.regionprops(seg_lab)
areas = np.array([prop.area for prop in props])
cutoff = 300
im_cells = np.copy(seg_lab) > 0
for i, _ in enumerate(areas):
if areas[i] < cutoff:
im_cells[seg_lab==props[i].label] = 0
area_filt_lab = skimage.measure.label(im_cells)
plt.figure()
plt.imshow(area_filt_lab, cmap=plt.cm.Spectral_r)
plt.show()
plt.close()
|
d7ed83a87e1eb77d01eda1b216368dc7b1d22602 | rochaktamang/pythonProject | /lab 1/apples.py | 324 | 3.890625 | 4 | N=int(input('enter the number of students: '))
K=int(input('enter the number of apples: '))
number_of_apples_each_students_get=K//N
numbers_of_apples_in_basket=K%N
print(f'the number of apples each students get is {number_of_apples_each_students_get}')
print('the number of apples in basket is', numbers_of_apples_in_basket) |
659a6de586382f12ca40d39b5fc43a3d2da48f8b | Nicole-Bidigaray/Bootcamp-pirple.com | /Python_is_Easy/Homework#3/main.py | 1,108 | 4.3125 | 4 | """
pirple.com/python
Homework Assignment #3: "If" Statements
If conditionals.
Create a function that accepts 3 parameters and checks for equality between any two of them.
Your function should return True if 2 or more of the parameters are equal,
and false is none of them are equal to any of the others.
Bonus:
Modify your function so that strings can be compared to integers if they are equivalent.
For example, if the following values are passed to your function:
6,5,"5"
You should modify it so that it returns true instead of false.
Hint: there's a built in Python function called "int" that will help you convert strings to Integers.
"""
def compare(a, b, c):
if int(a) == int(b) or int(a) == int(c) or int(b) == int(c):
return True
else:
return False
# Check the compare function
print(compare(1,1,2)) # True
print(compare(1,2,2)) # True
print(compare(1,2,1)) # True
print(compare(1,2,3)) # False
# Bonus
print(compare(6,5,"5")) # True
li=[1,2,3,4,3,2,1]
print(li[-3])
li=[1,2,3,4,3,2,1]
print(li[3:4])
li=[["a","b"]]
print(li[0][0])
li=[["john","doe"]]
print(li[-1][-1]) |
e1415877ddcc3eca4fb9e9033675cbcd02d05e11 | vins-stha/hy-data-analysis-with-python | /part05-e05_best_record_company/src/best_record_company.py | 584 | 3.828125 | 4 | #!/usr/bin/env python3
import pandas as pd
def myfilter(df): # The filter function must return a boolean value
return df["WoC"].sum() >= 10
def best_record_company():
df = pd.read_csv("src/UK-top40-1964-1-2.tsv", sep="\t")
#print(df.head())
publishers = df.groupby("Publisher")
v = publishers["WoC"].apply(lambda x:(x.sum())).sort_values(ascending=False)
result = df.loc[df["Publisher"]==v.index[0]]
return result
def main():
(best_record_company())
return
if __name__ == "__main__":
main()
|
d3c7a472c2dc343b4e5d19e454032ba26c80e9f8 | JianmingS/Practice-Code | /leetcode/双指针/面试题 02.02. 返回倒数第 k 个节点.py | 471 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
start_point = head
end_point = head
cnt = 0
while start_point:
start_point = start_point.next
cnt += 1
if cnt > k:
end_point = end_point.next
return end_point.val |
1f457ec4bd96b1375d21c09e45021c56dbb4fcc7 | irina-rus/Geekbrains | /L6/hw6_t2.py | 1,229 | 3.71875 | 4 | #Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
# Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
# Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
# Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом,
# толщиной в 1 см*число см толщины полотна. Проверить работу метода.
#Например: 20м*5000м*25кг*5см = 12500 т
class Road:
weight_1sm = 25
depth = 5
def asphalt_weight(self, _length, _width):
self.length = _length
self.width = _width
wa = int(self.length * self.width * self.weight_1sm * (self.depth/1000))
print(f'To cover the road asphalt weight should be {wa}')
w = Road()
w.asphalt_weight(20, 5000) |
487317f842b366efa579064ef21cd1908b4e1386 | petersimachev/Struct-Prog | /lab1-3.py | 491 | 4.15625 | 4 | import math
print('Сейчас будет решено выражение:')
print('N = (z+(z*x)^(1/5))^(1/5))/e^x+a^5*arctg(x)')
z = float(input('Введите переменную z: '))
e = float(input('Введите переменную e: '))
x = float(input('Введите переменную x: '))
a = float(input('Введите переменную a: '))
sqrz=z+math.sqrt(z*x)
n=math.pow(sqrz,1/5)/(math.exp(x)+math.pow(a,5)*math.atan(math.radians(x)))
print('Ответ:',n) |
457ea69a221c2de3d22dbc5b094425d2e67040ba | sushantMoon/Personal-Development | /Geeks4Geeks/activity_selection.py | 689 | 3.609375 | 4 | """
Sushant Moon
Date 14/7/2018
Activity Selection Problem
Reference :
https://www.geeksforgeeks.org/greedy-algorithms-set-1-activity-selection-problem/
"""
def activity_selection(activity):
activity = sorted(activity, key=lambda item:item[1])
results = []
results.append(activity[0])
for index, item in enumerate(activity):
if index == 0:
pass
else:
if results[-1][1] <= activity[index][0]:
results.append(activity[index])
for item in results:
print("Starts at {start} ----- Ends at => {end}".format(start=item[0], end=item[1]))
s = [[1,2] , [3,4] , [0,6] , [5,7] , [8,9] , [5,9]]
activity_selection(s)
|
541b97af90e998ba930d5943a492689a7ddca71e | aletisunil/Covid19_liveTracker | /Covid19_liveTracker.py | 1,253 | 3.5 | 4 | import requests
import bs4
country_name=input("Enter the Country name: ")
def covid19(country):
res = requests.get("https://www.worldometers.info/coronavirus/#countries")
soup = bs4.BeautifulSoup(res.text, 'lxml')
index = -1
data=soup.select('tr td')
for i in range(len(data)):
if data[i].text.lower()==country.lower():
index=i
break
for i in range(7):
if i == 0:
print("\nCountry name: "+str(data[i+index].text))
elif i == 1:
print("Total cases: "+str(data[i+index].text))
elif i == 2:
if data[i+index].text == '':
print("New cases: 0")
else:
print("New cases: "+str(data[i+index].text))
elif i == 3:
print("Total deaths: "+str(data[i+index].text))
elif i == 4:
if data[i+index].text == '':
print("New deaths: 0")
else:
print("New deaths: "+str(data[i+index].text))
elif i == 5:
print("Total Recovered: "+str(data[i+index].text))
elif i == 6:
print("Active cases: "+str(data[i+index].text),end='\n\n')
covid19(country_name)
|
b8fcd7fcc7d3885ec836d98dd811ba12e11c80e6 | seanchen513/dcp | /dcp160 - given tree with weighted edges, compute length of longest path.py | 3,970 | 4.28125 | 4 | """
dcp#160
This problem was asked by Uber.
Given a tree where each edge has a weight, compute the length of the longest path in the tree.
For example, given the following tree:
a
/|\
b c d
/ \
e f
/ \
g h
and the weights: a-b: 3, a-c: 5, a-d: 8, d-e: 2, d-f: 4, e-g: 1, e-h: 1, the longest path would be c -> a -> d -> f, with a length of 17.
The path does not have to pass through the root, and each node can have any amount of children.
"""
# Clarify: How to represent? Are weights all positive?
# If weights can be <= 0, we would have to worry about whether paths have to
# go all the way to leaves.
# "weight" is for edge connecting current node to its parent
class Node():
# use default [] to make iterable since None is not iterable
def __init__(self, val, weight=0, children=[]):
self.val = val
self.weight = weight
self.children = children
# not bothering to implement
def print_tree():
pass
"""
Idea:
For each node, keep track of max weights of one-way paths going down starting from that node.
[If a node has no children (ie, is a leaf), we can ignore it.]
[If a node has only 1 child (and a parent), we can ignore it since the path including its parent
will have bigger weight.]
The max weight turning at the node is the sum of the two biggest of these one-way paths.
Keep track of the max of these max weights throughout the tree.
[For these nodes, suffices to consider only nodes with at least 2 children.]
[If no nodes have at least two children, then tree is linear and the max path is the entire linear path.]
[Notes in square bracket can be done by hand and maybe implemented, but that's
not what the code here does.]
Example:
a
3/ |5 \8
b c d
2/ \4
e f
1/ \1
g h
Numbers are max weights of one-way paths going down starting from node:
a:3,5,12
/|\
b c d:3,4
/ \
e:1,1 f
/ \
g h
2-way max weights:
a: 5 + 12 = 17
d: 3 + 4 = 7
e: 2 + 2 = 4
weight of longest path = max(17, 7, 4) = 17
"""
# max_weight is max weight of all 2-way paths found so far
def max_weight_path(root, max_weight=0):
if root is None:
return 0
max1 = 0 # largest weight among 1-way paths down from node
max2 = 0 # 2nd largest weight among 1-way paths down from node
print("\n*** Starting processing for node {}".format(root.val))
for ch in root.children:
max_1way, max_2way = max_weight_path(ch, max_weight)
ch_weight = max_1way + ch.weight
if ch_weight >= max1:
max2 = max1
max1 = ch_weight
print("\nFor node {}, evaluated up to child {}:".format(root.val, ch.val))
print(" max1, max2 (1-way paths) = {}, {}".format(max1, max2))
print("\n--- finished processing node {}".format(root.val))
print(" max1 (1-way), max_weight (2-way) = {}, {}".format(max1, max(max1 + max2, max_weight)))
# 1st arg: max weight of 1-way paths down from this node
# 2nd arg: max weight of all 2-way paths found so far
return max1, max(max1 + max2, max_weight)
"""
a
3/ |5 \8
b c d
2/ \4
e f
1/ \1
g h
a-b: 3, a-c: 5, a-d: 8, d-e: 2, d-f: 4, e-g: 1, e-h: 1
The longest (2-way) path: c -> a -> d -> f, with length 5 + 8 + 4 = 17.
The longest (1-way) path: a -> d -> f, with length 8 + 4 = 12.
"""
### Tree given by problem statement.
root = Node('a')
b = Node('b', 3)
c = Node('c', 5)
d = Node('d', 8)
e = Node('e', 2)
f = Node('f', 4)
g = Node('g', 1)
h = Node('h', 1)
root.children = [b, c, d]
d.children = [e, f]
e.children = [g, h]
### Same tree pruned down to be linear.
# root = Node('a')
# d = Node('d', 8)
# e = Node('e', 2)
# g = Node('g', 1)
# root.children = [d]
# d.children = [e]
# e.children = [g]
#print_tree(root)
max_1way, max_2way = max_weight_path(root)
print("\nmax weight of all 1-way paths = {}".format(max_1way))
print("\nmax weight of all 2-way paths = {}".format(max_2way))
|
c798db8fbf7348d4793b24ecff4f39be3e1deb00 | eltechno/python_course | /CODES/17. Logical Operators/logicaloperators.py | 620 | 4.125 | 4 | '''number = int(input("Type a number and I will tell if it's between 1 and 10: "))
if (number > 1 and number < 10):
print("number between 1 and 10")
'''
a = 5
b = 2
if (not(a > b and b == 5)):
print("test")
'''
LOGICAL operators
True False
and
True True - True
True False - False
False True - False
False False - False
Conjuction is TRUE only when BOTH expressions are TRUE
or
True True - True
True False - True
False True - True
False False - False
Alternative is FALSE only when BOTH expressions are FALSE
not - no
True to False
False to True
'''
|
c0fb388cafc01226f6c1968eeeb1f843b670593d | pratik-iiitkalyani/Python | /function/return_print.py | 181 | 3.65625 | 4 | # return vs print
# return
def add_three(a,b,c):
return a+b+c #function returning the value
print(add_three(5,4,3))
# print
def add_two(a,b):
print(a+b)
add_two(5,4) |
f4461e360ce4e1cd22361ec8452ef74e020e3fe7 | gulberkdemir/isanagram | /Anagram.py | 334 | 3.765625 | 4 | import sys
import os
import string
import time
import argparse
class Anagram:
def __init__(self):
pass
@staticmethod
def isAnagram(s1, s2):
s1 = sorted(s1)
s2 = sorted(s2)
if s1 == s2:
print("This is an anagram")
else:
print("This is not an anagram")
|
5b0f6ed9a64ded26d94b96dd86d62789a9208acc | xuqil/DataStructures | /第三章线性表/链接表/单链表/单链表反转.py | 1,318 | 3.84375 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def rev(link):
pre = link
cur = link.next
pre.next = None # 第一个元素变为最后一个元素,它的next指向None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
if __name__ == '__main__':
link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9)))))))))
root = rev(link)
while root:
print(root.data)
root = root.next
"""
line 9-11是将原链表的第一个节点变成了新链表的最后一个节点,同时将原链表的第二个节点保存在cur中
line13-16就是从原链表的第二个节点开始遍历到最后一个节点,将所有节点翻转一遍
以翻转第二个节点为例
temp = cur.next是将cur的下一个节点保存在temp中,也就是第节点3,因为翻转后,节点2的下一个节点变成了节点1,原先节点2和节点3之间的连接断开,通过节点2就找不到节点3了,因此需要保存
cur.next = pre就是将节点2的下一个节点指向了节点1
然后pre向后移动到原先cur的位置,cur也向后移动一个节点,也就是pre = cur ,cur =temp
这就为翻转节点3做好了准备
""" |
4ca6087351dd33a465efa05fcf7ece8b6982c835 | fyber/jenkins_test | /sample.py | 90 | 3.703125 | 4 | import math
NUMBER = 16
print('Square root of {} is {}'.format(NUMBER, math.sqrt(16)))
|
ba3748d39d4fa6016cd8ef96851c73a9aa50d469 | danieldiniz1/blue | /aula 14.05/exercicio 3.py | 1,297 | 3.828125 | 4 |
opc = True
gabriel = 0
pedro = 0
matheus = 0
ana = 0
nulo = 0
branco = 0
total = 0
while opc ==True :
print("eleição! numero dos candidatos: 1- gabriel, 2- pedro, 3- matheus, 4- ana, 5- NULO, 6- BRANCO.")
voto = int(input("Digite seu voto: "))
if voto == 1 :
gabriel += 1
total += 1
elif voto == 2 :
pedro += 1
total += 1
elif voto == 3 :
matheus += 1
total += 1
elif voto == 4 :
ana +=1
total +=1
elif voto == 5 :
nulo +=1
total +=1
elif voto == 6 :
branco +=1
total +=1
elif voto ==0:
opc = False
print("Total de votos:", total)
print(f"Total de votos do candidato gabriel: {gabriel} votos / {((gabriel/total)*100):.2f} %")
print(f"Total de votos do candidato pedro: {pedro} votos / {((pedro/total)*100):.2f} %")
print(f"Total de votos do candidato matheus: {matheus} votos / {((matheus/total)*100):.2f} %")
print(f"Total de votos do candidata ana: {ana} votos / {((ana/total)*100):.2f} %")
print("Total de votos nulos: ", nulo)
print("Total de votos brancos: ", branco)
print(f"Percentual de votos nulos pelo total: {((nulo/total)*100):.2f} %")
print(f"Percentual de votos brancos pelo total: {((branco/total)*100):.2f} %") |
7b21c840e4b72e5f500137d20e2b392f7a6549b1 | donfreiday/cs50-web-programming | /lecture02/name.py | 108 | 4.21875 | 4 | print("Enter your name: ");
name = input()
# f is new in python 3.6, format string
print(f"Hello, {name}!") |
aeb8515ed95abcc3ab69595ae6533af5652aaba9 | stOracle/Migrate | /Programming/CS303E/bmi.py | 316 | 4.34375 | 4 | #prompt user to enter their weight and height
w = float(input("Enter your weight in pounds:"))
h = float(input("Enter your height in inches:"))
#convert weight to kilograms
k = w * .45359237
#convert height to meters
m = h * .0254
#calculate bmi
bmi = k / m ** 2
#print BMI result
print("BMI is" , bmi , end=".") |
18c7fb246077d25c323ae61efff2c07fe09042e0 | jhondare/WeJapa | /wave-1/Lab2of1.py | 131 | 3.828125 | 4 |
street = "No 5 Francis Road"
city = "Sambisa City"
print("The stubborn shild lives at {}, which is in {}".format(street, city))
|
318407d0b315c828efdd0c8b171b2a3a1106abb8 | Psingh12354/PythonNotes-Internshalla | /code/IF_ELSE.py | 343 | 4.125 | 4 | price=int(input("Enter the price : "))
quantity=int(input("Enter quantity : "))
amount=price*quantity
if amount>1000:
print("You got a discount of 10%")
discount=amount*10/100
amount-=discount
else:
print("You got a discount of 5%")
discount=amount*5/100
amount-=discount
print("Total amount is : ",amount)
|
2c58020eaf8c1753c69a27ee3dfdeaa3fd876fc0 | raghavddps2/Technical-Interview-Prep-1 | /UD_DSA/Course1/Recursion/subsets.py | 290 | 3.71875 | 4 | import copy
def subsets(arr):
if len(arr) == 0:
return [[]]
else:
res = []
temp = arr[0]
res = subsets(arr[1:])
for i in copy.deepcopy(res):
i.insert(0,temp)
res.append(i)
return res
print(subsets([1,2])) |
20eb9d6e2ebf1f28749e47aebeafb984c9e537e1 | ardicsobutay/phys48y | /Assignment 2/Homework 1/hw1_huseyinanilgunduz.py | 744 | 4.0625 | 4 |
balance = float(raw_input('Please enter balance:'))
annualInterestRate = float(raw_input('Please enter annual Interest Rate:'))
monthlyPaymentRate = float(raw_input('Please enter monthly Payment Rate:'))
monthintrate = annualInterestRate / 12.0
totalpaid=0.0
for i in range(12):
minmonthpay = monthlyPaymentRate * balance
monthlyunpaidbalance = balance - minmonthpay
updatedbalance = monthlyunpaidbalance + monthintrate * monthlyunpaidbalance
balance = updatedbalance
totalpaid += minmonthpay
print "Month:",i+1,"\nMinimum monthly payment:",(round(minmonthpay,2)),"\nRemaining balance:",(round(updatedbalance,2))
print "Total paid:",(round(totalpaid,2)),"\nRemaining balance:",(round(updatedbalance,2)) |
4a763fa79818d9b03f185576a0460e7ccea03a32 | javacode123/oj | /leetcode/middle/treeGraph/kSmall.py | 972 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-08-23 12:48
# @Author : Zhangjialuo
# @mail : [email protected]
# @File : kSmall.py
# @Software: PyCharm
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return None
queue, node, i = [], root, 1
while queue or node:
while node:
queue.append(node)
node = node.left
node = queue.pop()
if i == k:
return node.val
node = node.right
i += 1
return None
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(2)
print(Solution().kthSmallest(root, 2)) |
d2e25f7a65ba1cdbff2dc63f72f9added65b95ff | sashkarivkind/imagewalker | /fbm_mbm_lic/mbm.py | 4,843 | 3.5625 | 4 | """Generate realizations of multifractional Brownian motion."""
import inspect
from math import gamma
import numpy as np
class MBM(object):
"""The MBM class.
A class for generating multifractional Brownian motion or
multifractional Gaussian noise using approximate methods.
"""
def __init__(self, n, hurst, length=1, method="riemannliouville"):
"""Instantiate an MBM."""
self._methods = {"riemannliouville": self._riemannliouville}
self.n = n
self.length = length
self.hurst = hurst
self.method = method
self._mbm = self._methods[self.method]
self._dt = 1.0 * self.length / self.n
self._ts = self.times()
# Flag if some params get changed
self._changed = False
def __str__(self):
"""Str method."""
return (
"mBm ("
+ str(self.method)
+ ") on [0, "
+ str(self.length)
+ "] with Hurst function "
+ self.hurst.__name__
+ " and "
+ str(self.n)
+ " increments"
)
def __repr__(self):
"""Repr method."""
return (
"MBM(n="
+ str(self.n)
+ ", hurst="
+ self.hurst.__name__
+ ", length="
+ str(self.length)
+ ', method="'
+ str(self.method)
+ '")'
)
@property
def n(self):
"""Get the number of increments."""
return self._n
@n.setter
def n(self, value):
if not isinstance(value, int) or value <= 0:
raise TypeError("Number of increments must be a positive int.")
self._n = value
self._changed = True
@property
def hurst(self):
"""Hurst parameter."""
return self._hurst
@hurst.setter
def hurst(self, value):
try:
num_args = len(inspect.signature(value).parameters)
except Exception:
raise ValueError("Hurst parameter must be a function of one argument.")
if not callable(value) or num_args != 1:
raise ValueError("Hurst parameter must be a function of one argument.")
self._check_hurst(value)
self._hurst = value
self._changed = True
def _check_hurst(self, value):
self._hs = [value(t) for t in self.times()]
for h in self._hs:
if h <= 0 or h >= 1:
raise ValueError("Hurst range must be on interval (0, 1).")
@property
def length(self):
"""Get the length of process."""
return self._length
@length.setter
def length(self, value):
if not isinstance(value, (int, float)) or value <= 0:
raise ValueError("Length of fbm must be greater than 0.")
self._length = value
self._changed = True
@property
def method(self):
"""Get the algorithm used to generate."""
return self._method
@method.setter
def method(self, value):
if value not in self._methods:
raise ValueError("Method must be ...")
self._method = value
self._mgn = self._methods[self.method]
self._changed = True
def mbm(self):
"""Generate a realization of multifractional Brownian motion."""
return self._mbm()
def mgn(self):
"""Generate a realization of multifractional Gaussian noise."""
return np.diff(self.mbm())
def _riemannliouville(self):
"""Generate Riemann-Liouville mBm."""
gn = np.random.normal(0.0, 1.0, self.n)
if self._changed:
self._dt = 1.0 * self.length / self.n
self._ts = self.times()
self._check_hurst(self.hurst)
self._changed = False
mbm = [0]
coefs = [(g / np.sqrt(self._dt)) * self._dt for g in gn]
for k in range(1, self.n + 1):
weights = [self._w(t, self._hs[k]) for t in self._ts[1 : k + 1]]
seq = [coefs[i - 1] * weights[k - i] for i in range(1, k + 1)]
mbm.append(sum(seq))
return np.array(mbm)
def times(self):
"""Get times associated with the fbm/fgn samples."""
return np.linspace(0, self.length, self.n + 1)
def _w(self, t, hurst):
"""Get the Riemann-Liouville method weight for time t."""
w = (
1.0
/ gamma(hurst + 0.5)
* np.sqrt((t ** (2 * hurst) - (t - self._dt) ** (2 * hurst)) / (2 * hurst * self._dt))
)
return w
def mbm(n, hurst, length=1, method="riemannliouville"):
"""One off sample of mBm."""
m = MBM(n, hurst, length, method)
return m.mbm()
def mgn(n, hurst, length=1, method="riemannliouville"):
"""One off sample of mGn."""
m = MBM(n, hurst, length, method)
return m.mgn()
|
28b488c744f253b61e20f65636e5755bcd2d426e | EmilioAlzarif/intro-to-python | /week 5/Practical/P10.py | 143 | 3.828125 | 4 | list1= [1, 2, 43, 5, 213, 4]
def list_func(list1):
for x in list1:
yield x
value = list_func(list1)
print(value)
print(next(value)) |
ecf663ad4537e8f4f2a3a3068b12407cb0cc3e69 | archana986/Python-Coding-Projects-Udacity | /bikeshare Project 2.py | 27,516 | 3.875 | 4 | import csv
import calendar
import datetime
from collections import Counter
from operator import itemgetter
import pprint
import time
def get_city():
'''Asks the user for a city and returns the filename for that city's bike share data.
Args:
none.
Returns:
(str) Filename for a city's bikeshare data.
'''
city = input('\nHello! Let\'s explore some US bikeshare data!\n'
'Would you like to see data for Chicago, New York, or Washington?\n')
city=str(city)
if city.lower() == 'chicago':
city = 'chicago'
elif city.lower() == 'new york':
city = 'new_york_city'
elif city.lower() == 'washington':
city = 'washington'
else:
print('We do not have this information\n')
city = 'none'
return city
def load_cityfile(city):
'''Loads the city file and the transformed columns to a list of dictionaries to be used in other functions.
Args:
city name.
Returns:
list of dictionaries containing bikeshare data
'''
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
csvfile = city+'.csv'
with open(csvfile) as f:
open_city_file = [{k: v for k, v in row.items()}
for row in csv.DictReader(f, skipinitialspace=True)]
city_file = []
cnt = 0
for row in open_city_file:
CityDict = {}
CityDict['Start_Time'] = datetime.datetime.strptime(row['Start Time'], DATETIME_FORMAT)
CityDict['Start_Time_Month'] = datetime.datetime.strptime(row['Start Time'], DATETIME_FORMAT).strftime('%m')
CityDict['Start_Time_Month_Nm'] = datetime.datetime.strptime(row['Start Time'], DATETIME_FORMAT).strftime('%B')
CityDict['Start_Time_Day'] = datetime.datetime.strptime(row['Start Time'], DATETIME_FORMAT).strftime('%A')
CityDict['Start_Time_Hr'] = datetime.datetime.strptime(row['Start Time'], DATETIME_FORMAT).strftime('%H')
CityDict['End_time'] = datetime.datetime.strptime(row['End Time'], DATETIME_FORMAT)
CityDict['duration'] = int(float(row['Trip Duration']))
CityDict['Start_St'] = row['Start Station']
CityDict['End_St'] = row['End Station']
CityDict['Trip'] = '|'+row['Start Station']+' to '+row['End Station']+'|'
if row['User Type'] == 'Customer':
CityDict['User_Type'] = 'Customer'
elif row['User Type'] == 'Subscriber':
CityDict['User_Type'] = 'Subscriber'
else:
CityDict['User_Type'] = 'Unknown'
if 'Gender' not in row:
CityDict['Gender'] = 'U'
else:
if row['Gender'] == 'Male':
CityDict['Gender'] = 'Male'
elif row['Gender'] == 'Female':
CityDict['Gender'] = 'Female'
else:
CityDict['Gender'] = 'Unknown'
if 'Birth Year' in row:
try:
CityDict['Y_O_B'] = int(float(row['Birth Year']))
except ValueError:
CityDict['Y_O_B'] = 0
else:
CityDict['Y_O_B'] = 0
city_file.append(CityDict)
cnt += 1
return city_file
def get_month():
'''Asks the user for a month and returns the specified month.
Args:
none.
Returns:
(str) Name of the "Month" for a city's bikeshare data.
'''
month = input('\nWhich month? January, February, March, April, May, or June?\n')
month=str(month).lower().title()
return month
def get_day():
'''Asks the user for a day and returns the specified day.
Args:
none.
Returns:
(int) "Day number" for which you need city's bikeshare data and return the day of the week
'''
day = input('\nWhich day? Please type your response as an integer, 1 = Monday, 2 = Tuesday, 3= Wednesday, 4= Thursday, 5=Friday, 6=Saturday and 7=Sunday.\n')
day=int(day)-1
day=calendar.day_name[day]
return day
def get_time_period():
'''Asks the user for a time period and returns the specified filter.
Args:
none.
Returns:
(str) Choice of "Month" & Name of the month (OR) Day and Day Name (OR) None, for a city's bikeshare data.
'''
timefilter = input('\nWould you like to filter the data by month, day, or not at'
' all? Type "none" for no time filter.\n')
timefilter=str(timefilter).lower()
if timefilter=="month":
month = get_month()
time_period=(timefilter,month)
return (time_period)
elif timefilter=="day":
day = get_day()
time_period=(timefilter,day)
return (time_period)
else:
timefilter=="none"
time_period = (timefilter,'none')
return (time_period)
def popular_month(city,city_file):
''' Question: What is the most popular month for start time?
Args:
city,cityfile
Returns: none.
'''
popularmonth = Counter(k['Start_Time_Month_Nm'] for k in city_file if k.get('Start_Time_Month_Nm'))
for Start_Time_Month_Nm, count in popularmonth.most_common(1):
print ("The most popular month for the city: {}'s bikeshare data is {} with {} occurrences.".format(city,Start_Time_Month_Nm,str(count)))
def popular_day(city,city_file, time_period):
'''Question: What is the most popular day of week (Monday, Tuesday, etc.) for start time? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: Most popular Day with a print statement of the month and occurrences.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
popularday = Counter(k['Start_Time_Day'] for k in cityfilemonth if k.get('Start_Time_Day'))
for Start_Time_Day, count in popularday.most_common(1):
print ("The most popular day for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Start_Time_Day,str(count)))
else:
popularday = Counter(k['Start_Time_Day'] for k in city_file if k.get('Start_Time_Day'))
for Start_Time_Day, count in popularday.most_common(1):
print ("The most popular day for the city :{}'s bikeshare data is {} with {} occurrences.".format(city,Start_Time_Day,str(count)))
def popular_hour(city,city_file, time_period):
'''Question: What is the most popular Hour for start time? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
popularhour = Counter(k['Start_Time_Hr'] for k in cityfilemonth if k.get('Start_Time_Hr'))
for Start_Time_Hr, count in popularhour.most_common(1):
print ("The most popular hour for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Start_Time_Hr,str(count)))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
popularhour = Counter(k['Start_Time_Hr'] for k in cityfilemonth if k.get('Start_Time_Hr'))
for Start_Time_Hr, count in popularhour.most_common(1):
print ("The most popular hour for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Start_Time_Hr,str(count)))
else:
popularhour = Counter(k['Start_Time_Hr'] for k in city_file if k.get('Start_Time_Hr'))
for Start_Time_Hr, count in popularhour.most_common(1):
print ("The most popular hour for the city :{}'s bikeshare data is {} with {} occurrences.".format(city,Start_Time_Hr,str(count)))
def trip_duration(city,city_file, time_period):
'''
Question: What is the total trip duration and average trip duration? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
total_duration = sum(item['duration'] for item in cityfilemonth)
try:
avg_duration =sum(item['duration'] for item in cityfilemonth)/len(cityfilemonth)
print ("The \"trip\" related statistic for the the city :{}\'s bikeshare data with filters: ({},{}) is a total duration of {} with an average trip duration of {}.".format(city,timefilter,timefilter_nm,str(total_duration),str(avg_duration)))
except ZeroDivisionError:
print('The \"trip\" related statistic for the the city :{}\'s bikeshare data with filters: ({},{}) resulted in an Error: Division by Zero.'.format(city,timefilter,timefilter_nm))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
total_duration = sum(item['duration'] for item in cityfilemonth)
try:
avg_duration=total_duration/len(cityfilemonth)
print ("The \"trip\" related statistic for the the city :{}\'s bikeshare data with filters: ({},{}) is a total duration of {} with an average trip duration of {}.".format(city,timefilter,timefilter_nm,str(total_duration),str(avg_duration)))
except ZeroDivisionError:
print('The \"trip\" related statistic for the the city :{}\'s bikeshare data with filters: ({},{}) resulted in Error: Division by Zero.'.format(city,timefilter,timefilter_nm))
else:
total_duration = sum(item['duration'] for item in city_file)
try:
avg_duration=total_duration/len(city_file)
print ("The \"trip\" related statistic for the the city :{}\'s bikeshare data is a total duration of :{} with an average trip duration of :{}.".format(city,str(total_duration),str(avg_duration)))
except ZeroDivisionError:
print('The \"trip\" related statistic for the the city :{}\'s bikeshare data resulted in Error: Division by Zero.'.format(city))
def popular_stations(city,city_file, time_period):
'''Question: What is the most popular Hour for start time? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
popularStart_St = Counter(k['Start_St'] for k in cityfilemonth if k.get('Start_St'))
for Start_St, count in popularStart_St.most_common(1):
print ("The most popular Start Station for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Start_St,str(count)))
popularEnd_St = Counter(k['End_St'] for k in cityfilemonth if k.get('End_St'))
for End_St, count in popularEnd_St.most_common(1):
print ("The most popular End Station for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,End_St,str(count)))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
popularStart_St = Counter(k['Start_St'] for k in cityfilemonth if k.get('Start_St'))
for Start_St, count in popularStart_St.most_common(1):
print ("The most popular Start Station for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Start_St,str(count)))
popularEnd_St = Counter(k['End_St'] for k in cityfilemonth if k.get('End_St'))
for End_St, count in popularEnd_St.most_common(1):
print ("The most popular End Station for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,End_St,str(count)))
else:
popularStart_St = Counter(k['Start_St'] for k in city_file if k.get('Start_St'))
for Start_St, count in popularStart_St.most_common(1):
print ("The most popular Start Station for the city :{} is {} with {} occurrences.".format(city,Start_St,str(count)))
popularEnd_St = Counter(k['End_St'] for k in city_file if k.get('End_St'))
for End_St, count in popularEnd_St.most_common(1):
print ("The most popular End Station for the city :{} is {} with {} occurrences.".format(city,End_St,str(count)))
def popular_trip(city,city_file, time_period):
'''Question: What is the most popular trip? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
populartrip = Counter(k['Trip'] for k in cityfilemonth if k.get('Trip'))
for Trip, count in populartrip.most_common(1):
print ("The most popular Trip for the city :{} 's bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Trip,str(count)))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
populartrip = Counter(k['Trip'] for k in cityfilemonth if k.get('Trip'))
for Trip, count in populartrip.most_common(1):
print ("The most popular Trip for the city :{}'s bikeshare data with filters: ({},{}) is {} with {} occurrences.".format(city,timefilter,timefilter_nm,Trip,str(count)))
else:
populartrip = Counter(k['Trip'] for k in city_file if k.get('Trip'))
for Trip, count in populartrip.most_common(1):
print ("The most popular Trip for the city :{} is {} with {} occurrences.".format(city,Trip,str(count)))
def users(city,city_file, time_period):
'''Question: What are the counts of each user type? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
users = Counter(map(itemgetter('User_Type'), cityfilemonth))
print ("The user type counts for the city :{}'s bikeshare data with filters: ({},{}) are {}.".format(city,timefilter,timefilter_nm,users.most_common()))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
users = Counter(map(itemgetter('User_Type'), cityfilemonth))
print ("The user type counts for the city :{}'s bikeshare data with filters: ({},{}) are {}.".format(city,timefilter,timefilter_nm,users.most_common()))
else:
users = Counter(map(itemgetter('User_Type'), city_file))
print ("The user type counts for the city :{} are {}.".format(city,users.most_common()))
def gender(city,city_file, time_period):
'''Question: What are the counts of each user type? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
Gender = Counter(map(itemgetter('Gender'), cityfilemonth))
print ("The Gender counts for the city :{}'s bikeshare data with filters: ({},{}) are {}.".format(city,timefilter,timefilter_nm,Gender.most_common()))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
Gender = Counter(map(itemgetter('Gender'), cityfilemonth))
print ("The Gender counts for the city :{}'s bikeshare data with filters: ({},{}) are {}.".format(city,timefilter,timefilter_nm,Gender.most_common()))
else:
Gender = Counter(map(itemgetter('Gender'), city_file))
print ("The Gender counts for the city :{}'s bikeshare data are {}.".format(city,Gender.most_common()))
def birth_years(city,city_file, time_period):
'''Question: Question: What are the earliest, most recent, and most popular birth years? If the filter chosen has a timeperiod, filter based on that
Args:
city,city_file, time_period
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
exclude_yr =[0]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm and x ['Y_O_B'] not in exclude_yr , city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
YOBseq = [x['Y_O_B'] for x in cityfilemonth]
popularYOB = Counter(k['Y_O_B'] for k in cityfilemonth if k.get('Y_O_B'))
for Y_O_B, count in popularYOB.most_common(1):
print ("The most popular birth years for the city {}'s bikeshare data with filters: ({},{}) is {} with {} occurrences. \nThe earliest Birth Year is {} and the most recent Birth Year is {}.".format(city,timefilter,timefilter_nm,Y_O_B,str(count),min(YOBseq),max(YOBseq)))
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm and x ['Y_O_B'] not in exclude_yr , city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
YOBseq = [x['Y_O_B'] for x in cityfilemonth]
popularYOB = Counter(k['Y_O_B'] for k in cityfilemonth if k.get('Y_O_B'))
for Y_O_B, count in popularYOB.most_common(1):
print ("The most popular birth year for the city {}'s bikeshare data with filters: ({},{}) is {} with {} occurrences. \nThe earliest Birth Year is {} and the most recent Birth Year is {}.".format(city,timefilter,timefilter_nm,Y_O_B,str(count),min(YOBseq),max(YOBseq)))
else:
YOBseq = [x['Y_O_B'] for x in city_file]
popularYOB = Counter(k['Y_O_B'] for k in city_file if k.get('Y_O_B'))
for Y_O_B, count in popularYOB.most_common(1):
print ("The most popular birth years for the city {}'s bikeshare data is {} with {} occurrences.\nThe earliest Birth Year is {} and the most recent Birth Year is {}.".format(city,Y_O_B,str(count),min(YOBseq),max(YOBseq)))
def display_data(city,city_file,time_period):
'''Displays five lines of data if the user specifies that they would like to.
After displaying five lines, ask the user if they would like to see five more,
continuing asking until they say stop.
Args:
city,city_file, time_period.
Returns: none.
'''
timefilter=time_period[0]
timefilter_nm=time_period[1]
if timefilter == 'month':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Month_Nm'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
display = input('Would you like to view individual trip data?'
'Type \'yes\' or \'no\'. \n')
display = display.lower()
i = 0
while display.lower() == 'yes':
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(cityfilemonth[i:i+5])
i += 5
display = input("\nWould you like to view five more lines?"
"Type 'yes' or 'no'.\n")
else:
print('No data selected to be displayed.')
elif timefilter == 'day':
cityfilemonth = list(filter(lambda x : x ['Start_Time_Day'] in timefilter_nm, city_file))
if cityfilemonth==[]:
print('There is no data with this filter criteria')
else:
display = input('Would you like to view individual trip data?'
'Type \'yes\' or \'no\'. \n')
display = display.lower()
i = 0
while display.lower() == 'yes':
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(cityfilemonth[i:i+5])
i += 5
display = input("\nWould you like to view five more lines?"
"Type 'yes' or 'no'.\n")
else:
print('No data selected to be displayed.')
else:
display = input('Would you like to view individual trip data?'
'Type \'yes\' or \'no\'. \n')
display = display.lower()
i = 0
while display.lower() == 'yes':
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(city_file[i:i+5])
i += 5
display = input("\nWould you like to view five more lines?"
"Type 'yes' or 'no'.\n")
else:
print('No data selected to be displayed.')
def statistics():
'''Calculates and prints out the descriptive statistics about a city and time period
specified by the user via raw input.
Args:
city.
Returns:
none.
'''
# Filter by city (Chicago, New York, Washington)
city = get_city()
if city!='none':
city_file = load_cityfile(city)
# Filter by time period (month, day, none)
time_period = get_time_period()
# What is the most popular month for start time?
if time_period[0] == 'none':
print('Calculating the first statistic...')
start_time = time.time()
popular_month(city,city_file)
print("That took %s seconds." % (time.time() - start_time))
# What is the most popular day of week (Monday, Tuesday, etc.) for start time?
if time_period[0] == 'none' or time_period[0] == 'month':
print("Calculating the next statistic...")
start_time = time.time()
popular_day(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What is the most popular hour of day for start time?
print("Calculating the next statistic...")
start_time = time.time()
popular_hour(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What is the total trip duration and average trip duration?
print("Calculating the next statistic...")
start_time = time.time()
trip_duration(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What is the most popular start station and most popular end station?
print("Calculating the next statistic...")
start_time = time.time()
popular_stations(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What is the most popular trip?
print("Calculating the next statistic...")
start_time = time.time()
popular_trip(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What are the counts of each user type?
print("Calculating the next statistic...")
start_time = time.time()
users(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What are the counts of gender?
print("Calculating the next statistic...")
start_time = time.time()
gender(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# What are the earliest, most recent, and most popular birth years?
print("Calculating the next statistic...")
start_time = time.time()
birth_years(city,city_file, time_period)
print("That took %s seconds." % (time.time() - start_time))
# Display five lines of data at a time if user specifies that they would like to
display_data(city,city_file, time_period)
else:
exit()
# Restart?
restart = input('Would you like to restart? Type \'yes\' or \'no\'.\n')
if restart.lower() == 'yes':
statistics()
if __name__ == "__main__":
statistics()
|
d779a6553d646d7ce6347aa8c55e975afad77198 | swapnilvishwakarma/100_Days_of_Coding_Challenge | /12.Find_First_and_Last_Position_of_Element_in_Sorted_Array.py | 497 | 3.796875 | 4 | # Given an array of integers nums sorted in ascending order, find the starting and ending position of a
# given target value.
# If target is not found in the array, return [-1, -1].
from bisect import bisect_left, bisect_right
class Solution:
def searchRange(self, nums: list, target: int) -> list:
l = bisect_left(nums, target)
r = bisect_right(nums, target)
return (l, r-1) if l<r else (-1, -1)
sol = Solution()
print(sol.searchRange([5,7,7,8,8,10], 8)) |
75a169c5da376cabac50cef74656576ed17cab24 | JonahEgashira/competitive-programming | /abc158b.py | 114 | 3.671875 | 4 | x = int(input())
ans = 0
money = 100
while money < x:
money *= 1.01
money = int(money)
ans += 1
print(ans)
|
ec327ec7923093333c3585a395808a277bc7e9bf | Minkov/python-oop-2020-02 | /encapsulation/1_person.py | 542 | 3.8125 | 4 | class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __validate_age(self, age):
if age < 0 or age > 125:
raise ValueError('Invalid age value')
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_age(self, age):
self.__validate_age(age)
self.__age = age
person = Person("George", 32)
person.__name = 'Pesho'
person2 = Person('Peter', 33)
print(person.__dict__)
print(person2.__dict__)
|
2da27a7c0109f54641fc887100444e22217da6ca | naimucar/8.hafta_odevler-Fonksiyonlar | /BUYUK kucukharf fonk.py | 579 | 3.78125 | 4 | #Kullanıcıdan bir input alan ve bu inputun içindeki büyük ve küçük harf
# sayılarının veren bir fonksiyon yazınız.
def buyuk_kucuk_harf(metin=input('metin giriniz:')):
sayac1=0
sayac2=0
sayac3=0
for sayac in metin:
if sayac.islower():#kucuk harf kontrolu
sayac1+=1
if sayac.isupper():#buyuk harf kontrolu
sayac2+=1
if sayac.isdigit():#rakam kontrolu
sayac3+=1
print("metinde {} adet buyuk harf,{} adet kucuk harf {} adet rakam bulunur".format(sayac2,sayac1,sayac3))
buyuk_kucuk_harf()
|
675bdf361b67001df0e7d96124b1ba1cf2b75136 | psnluiz/exercises-and-stuff | /Soma de dez números inteiros.py | 395 | 4.125 | 4 | n = 1
soma = 0
while (n <= 10):
if n == 1:
num = int(input("Type the 1st number: "))
elif n == 2:
num = int(input("Type the 2nd number: "))
elif n == 3:
num = int(input("Type the 3rd number: "))
else:
num = int(input("The the {}th number: ".format(n))
n += 1
soma = soma + num
print ("The average is: "), soma/n)
|
b834d729614414dd5ff6f35b17aab19917c8bfed | eragon11/codekata | /Beginner/set1/hellon.py | 97 | 3.796875 | 4 | n = int(input());
if (n == 0):
print();
else:
for i in range(n):
print("Hello"); |
f9d0b6738ec933f6bfb0d64b8f998c9954dd9e33 | easystart-co/python | /MultiThreading/main9.py | 1,511 | 4.15625 | 4 | # 用队列进行多线程数据传递
import threading
import time
def threading1():
global numA,numB
add_times = 100
time.sleep(1)
for i in range(add_times):
lockR.acquire() #获取锁
numA = numA+1
thread_name = threading.current_thread().getName()
print(thread_name+'-numA:'+str(numA))
lockR.acquire() #获取锁
numB = numB+1
thread_name = threading.current_thread().getName()
print(thread_name+'-numB:'+str(numB))
lockR.release() #释放锁
lockR.release() #释放锁
def threading2():
global numA,numB
add_times = 100
time.sleep(1)
for i in range(add_times):
lockR.acquire() #获取锁
numA = numA+1
thread_name = threading.current_thread().getName()
print(thread_name+'-numA:'+str(numA))
lockR.acquire() #获取锁
numB = numB+1
thread_name = threading.current_thread().getName()
print(thread_name+'-numB:'+str(numB))
lockR.release() #释放锁
lockR.release() #释放锁
if __name__ == "__main__": # 主线程
lockR = threading.RLock() #递归锁
numA = 0
numB = 0
th1 = threading.Thread(target=threading1,args=()) #子线程1
th2 = threading.Thread(target=threading2,args=()) #子线程2
th1.setName('TH1')
th2.setName('TH2')
th1.start()
th2.start()
th1.join()
th2.join()
# print(num)
print('main threading end')
|
6ca546991e83505cc32efe4f4632404a73d04203 | daniel-reich/ubiquitous-fiesta | /r8jXYt5dQ3puspQfJ_21.py | 400 | 4.0625 | 4 |
def split(txt):
new_sentence = ""
for char in txt:
if is_vowel(char):
new_sentence += char
for char in txt:
if not is_vowel(char):
new_sentence += char
return new_sentence
def is_vowel(character):
vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]
if character in vowels:
return True
return False
|
1b9fbecacd4c3af89cd4c0f2ff1aa5231e31d463 | salisu14/learn-python-programming | /Q4.py | 287 | 4.1875 | 4 | #!usr/bin/env python3
num1 = input("Enter First Number: ")
num2 = input("Enter Second Number: ")
if num1 > num2:
print(num1,"is greater than", num2)
elif num2 > num1:
print(num2,"is greater than", num1)
elif num2 == num1:
print(num1, "and", num2, "are equal")
|
fa793b5457e3d2ad1f5a85844e5965896f829151 | okq550/PythonExamples | /PIRPLE/HomeWorks/main8.py | 2,637 | 4.25 | 4 | import os
def readFile(fileName):
#Print the content of the passed file
print('** Operation Read For File', fileName , '**')
myFileHandler = open(fileName, 'r')
print(myFileHandler.read())
myFileHandler.close()
return True
def appendToFile(fileName):
#Append content to the passed file
print('** Operation Append To File', fileName , '**')
content = input('Please enter the content to be appended to file ' + fileName + ': ')
myFileHandler = open(fileName, 'a')
myFileHandler.write(content + '\n')
myFileHandler.close()
return True
def replaceFile(fileName):
#Empty the file to start over again
print('** Operation Replace File', fileName, 'file content has been dumped, You can start over again! **')
myFileHandler = open(fileName, 'w')
myFileHandler.write('')
myFileHandler.close()
return True
def replaceSingleLineInFile(fileName):
print('** Operation Replace Single Line In File', fileName , '**')
lineNumber = 1
filesLinesAsList = []
with open(fileName, 'r') as currentFile:
for line in currentFile:
print(lineNumber, end=' ')
print(line)
filesLinesAsList.append(line.strip())
lineNumber += 1
#Ask the user for line number and the content then replace it in the passed file
editlineNumber = int(input('Please enter the line number you want to edit: '))
if editlineNumber > len(filesLinesAsList) or editlineNumber <= 0:
print('Error, Invalid line number.')
newContent = input('Please enter the content for line number ' + str(editlineNumber) + ':')
filesLinesAsList[editlineNumber-1] = newContent
myFileHandler = open(fileName, 'w')
myFileHandler.write('\n'.join(filesLinesAsList))
myFileHandler.close()
return True
userFileName = input('Please enter file name: ')
if not os.path.isfile(userFileName):
fileContent = input('Please enter file content: ')
myFileHandler = open(userFileName, 'w')
myFileHandler.write(fileContent)
myFileHandler.close()
else:
print('File ', userFileName, ' already exists.')
operationMode = input('Please enter the operation you want to make on the file (read = 1, append = 2, replace = 3, edit single line = 4): ')
if operationMode == '1':
readFile(userFileName)
elif operationMode == '2':
appendToFile(userFileName)
elif operationMode == '3':
replaceFile(userFileName)
elif operationMode == '4':
replaceSingleLineInFile(userFileName)
else:
print("Error, operation mode is not supported.") |
5c4b17f07d9ea9958d3a332b4c2815757f2ba38b | Devin6Tam/python_practice | /lesson101/practice_day03.py | 1,292 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/15 17:51
# @Author : tanxw
"""
6、编写代码设计简易计算器,用户通过3次输入,可以进行两个整数的加减乘除运算并输出结果。
7、闰年判断程序: if判断、格式化输出、运算符
要求:
输入一个有效的年份,判断是不是闰年;
如果是闰年,则打印“***年是闰年”;否则打印“***年不是闰年”;
如输入"2017",将打印“2017年不是闰年”
"""
num_a = int(input("请输入一个整数:"))
operator = input("请输入一个运算符:")
num_b = int(input("请输入一个整数:"))
if operator == "+":
print("%d%s%d=%d" % (num_a, operator, num_b, num_a + num_b))
elif operator == "-":
print("%d%s%d=%d" % (num_a, operator, num_b, num_a - num_b))
elif operator == "*":
print("%d%s%d=%d" % (num_a, operator, num_b, num_a * num_b))
elif operator == "/":
if num_b == 0:
print("被除数不能为0")
else:
print("%d%s%d=%d" % (num_a, operator, num_b, num_a / num_b))
else:
print("输入运算符错误!")
year = int(input("请输入一个有效的年份:"))
if (year % 4 == 0 & year % 100 != 0) or year % 400 == 0:
print("%d是润年" % year)
else:
print("%d不是润年" % year)
|
fae7fece7248517b6f6f5c5f335ffd68352b596a | rmiguelito/python-rest | /get-movies.py | 919 | 3.609375 | 4 | import requests
import json
#isto eh uma funcao
def requisicao(titulo):
#tratando erros com try except, ainda tenho que entender os mecanismos internos no VSCODE
try:
req = requests.get('http://www.omdbapi.com/?apikey=a9b0d085&t=' + titulo)
dicionario = json.loads(req.text)
return dicionario
except:
print ("erro ao acessar o site")
return None
def print_detalhes(filme):
print ("Nome Filme:", filme['Title'])
print ("Atores:", filme['Actors'])
print ("Ano:", filme['Year'])
print ("NotaImdb:", filme['imdbRating'])
print ("")
sair = False
while not sair:
op = input("Escreva o nome de um filme ou SAIR para fechar: ")
if op == 'SAIR':
sair = True
else:
filme = requisicao(op)
if filme['Response'] == "False":
print ("Filme Nao encontrado")
else:
print_detalhes (filme) |
77c86462ea9cca4fbd8e3a6307ad501bb8924c69 | XMK233/Leetcode-Journey | /py-Jindian/16.02.py | 870 | 3.546875 | 4 | '''
[面试题 16.02. 单词频率 - 力扣(LeetCode)](https://leetcode-cn.com/problems/words-frequency-lcci)
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
WordsFrequency(book)构造函数,参数为字符串数组构成的一本书
get(word)查询指定单词在书中出现的频率
示例:
WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"});
wordsFrequency.get("you"); //返回0,"you"没有出现过
wordsFrequency.get("have"); //返回2,"have"出现2次
wordsFrequency.get("an"); //返回1
wordsFrequency.get("apple"); //返回1
wordsFrequency.get("pen"); //返回1
提示:
book[i]中只包含小写字母
1 <= book.length <= 100000
1 <= book[i].length <= 10
get函数的调用次数不会超过100000
'''
|
25836c343dbc69c704744c70bc7569bfb4530eb1 | nathy-mesquita/script_python | /Desafio_17.py | 382 | 4.125 | 4 | #Cálculo do Seno, Cosseno e Tangente
from math import radians, sin, cos, tan
num = float (input (' Insira o valor do ângulo: '))
sen = sin(radians(num))
print ('O Seno do ângulo {} é {:.2f}'.format(num, sen))
cos = cos(radians(num))
print ('O Cosseno do ângulo {} é {:.2f}'.format(num,cos))
tan = tan(radians(num))
print ('A Tangente do ângulo {} é {:.2f}'.format(num, tan)) |
bf54a9a9e4d308eeeeed4cc4fb81720c0098fdc5 | alvkao58/pylot | /pylot/control/messages.py | 1,240 | 3.609375 | 4 | import erdos
class ControlMessage(erdos.Message):
""" This class represents a message to be used to send control commands.
Attributes:
steer: Steer angle between [-1.0, 1.0].
throttle: Throttle command between [0.0, 1.0].
brake: Brake command between [0.0, 1.0].
hand_brake: Boolean controlling hand-brake engagement.
reverse: Boolean controlling reverse gear engagement.
"""
def __init__(self, steer, throttle, brake, hand_brake, reverse, timestamp):
super(ControlMessage, self).__init__(timestamp, None)
assert steer >= -1 and steer <= 1, 'Steer angle must be in [-1, 1]'
self.steer = steer
assert throttle >= 0 and throttle <= 1, 'Throttle must be in [0, 1]'
self.throttle = throttle
assert brake >= 0 and brake <= 1, 'Brake must be in [0, 1]'
self.brake = brake
self.hand_brake = hand_brake
self.reverse = reverse
def __str__(self):
return ('ControlMessage(timestamp: {}, steer: {}, throttle: {}, '
'brake: {}, hand_brake: {}, reverse: {})'.format(
self.timestamp, self.steer, self.throttle, self.brake,
self.hand_brake, self.reverse))
|
308c9a9b0baa25166eb2c68fec949a14ff22d29a | sryhan/Coding-Exercises | /codingbat_exercises/warmup1_missing_char.py | 414 | 4.15625 | 4 |
"""
Given a non-empty string and an int n, return a new string where the char at
index n has been removed. The value of n will be a valid index of a char in the
original string (i.e. n will be in the range 0..len(str)-1 inclusive)
"""
def missing_char(str, n):
if str == "":
return False
if n > len(str):
return "Out of range"
str.pop(n)
return str
print(missing_char("cat", 1))
|
25e2210aabfca90f7bff1a1ac02a3c5eb05b95f9 | ZhehanZhang/Leetcode-NowCoder-Practice | /lc849.py | 410 | 3.53125 | 4 | ##https://leetcode.com/problems/maximize-distance-to-closest-person/
##通过计算连续0的个数来决定坐在哪一组0的中间(或者坐在最两边)
n = int(input())
res = []
for i in range(n):
stair = int(input())
if stair == 1:
print(0)
else:
f1, f2 = 0,1
for s in range(stair):
f1, f2 = f2, f1+f2
res.append(str(f1))
print('\n'.join(res)) |
ef50eee05af6658c33ba0d9127fd1452aab9b78a | nub8p/2020-Summer-Jookgorithm | /강재민/7월/[20.07.06]1002.py | 568 | 3.546875 | 4 | import math
T = int( input() )
for i in range(T):
input_list = input().split()
j = ( int(input_list[0]), int(input_list[1]) )
b = ( int(input_list[3]), int(input_list[4]) )
r1 = int(input_list[2])
r2 = int(input_list[5])
distance = math.sqrt( ( j[0] - b[0] )**2 + (j[1] - b[1] )**2 )
if( j == b ) and r1 == r2:
print( -1 )
elif r1+distance > r2 and r2+distance > r1 and r1+r2 > distance:
print( 2 )
elif r1+distance == r2 or r2+distance == r1 or r1+r2 == distance:
print( 1 )
else:
print( 0 ) |
2e5a107e9dc14ff0ee3dab7b9b6f795ba4542872 | nnelluri928/DailyByte | /intersetion_numbers.py | 997 | 4.25 | 4 | '''
This question is asked by Google. Given two integer arrays, return their intersection.
Note: the intersection is the set of elements that are common to both arrays.
Ex: Given the following arrays...
nums1 = [2, 4, 4, 2], nums2 = [2, 4], return [2, 4]
nums1 = [1, 2, 3, 3], nums2 = [3, 3], return [3]
nums1 = [2, 4, 6, 8], nums2 = [1, 3, 5, 7], return []
'''
def intersection(nums1,nums2):
res = []
for i in range(len(nums2)):
if nums2[i] in nums1:
res.append(nums2[i])
return set(res)
nums1 = [2, 4, 4, 2]; nums2 = [2, 4]
assert intersection(nums1,nums2) != [2,4]
nums1 = [1, 2, 3, 3]; nums2 = [3, 3]
assert intersection(nums1,nums2) != [3]
nums1 = [2, 4, 6, 8]; nums2 = [1, 3, 5, 7]
assert intersection(nums1,nums2) != []
def intersection_1(nums1,nums2):
return set(nums1) & set(nums2)
nums1 = [1,2,2,1]; nums2 = [2,2]
assert intersection_1(nums1,nums2) != [2,2]
nums1 = [4,9,5]; nums2 = [9,4,9,8,4]
assert intersection_1(nums1,nums2) != [ 9,4] |
6eb711ec4e534d0c8a6d4e4c8943a4b4cc583467 | tosunufuk/pEuler | /Python/pProblem_2.py | 369 | 3.5 | 4 | from datetime import datetime
startTime = datetime.now()
maxVal = 4000000;
val = 1;
pastVal1 = 0;
temp = 0;
total = 0;
while val < maxVal :
temp = val;
val += pastVal1;
pastVal1 = temp;
if ((val & 1) == 0) :
total += val;
print(total)
print("Runtime is ", datetime.now() - startTime) |
20147c9ceab8e0ca59667b57b43c58f1f1fc8609 | gogenich/homework_vasiliy_redkin | /lesson_2/the_task_5.py | 382 | 3.6875 | 4 | l = [7, 6, 4, 3, 3, 2]
namber = int(input('введите целое положительное число: '))
print(f'старый список: {l}')
i = 0
for x in l:
if namber > x:
l.insert(i, namber)
break
i = i + 1
print(f'новый список с введенным числом: {l}')
print(f'позиция введенного числа: {i}')
|
b7b30612c56a2e52edb5f59e9f356c1f71732b2d | WILDCHAP/python_study_std | /python_Project_03/hash哈希.py | 338 | 4.1875 | 4 | '''
Python中内置有一个名字叫做hash(o)的函数
。接收一个不可变类型的数据作为参数
。返回结果是一个整数
'''
# 无论什么时候输出都一样
print(hash(1))
print(hash("hellow"))
print(hash((1,)))
# 不能列表(因为可变)
# print(hash([1, 2]))
# 不能字典(因为可变)
# print(hash({1: 2}))
|
20c0a9a41928d8fda89dba26ae86451726bbb770 | bpate05/PyBank-PyPoll | /mainPP.py | 2,425 | 3.765625 | 4 | #PyPoll
import os
import csv
# set a csv file path for the data
poll_csv = os.path.join('election_data.csv')
# define function
def get_results(data):
# define variables
totalVotesCount = 0
votes = []
candidateCount = []
uniqueCandidates = []
percent = []
# start looping through rows
for row in data:
# count the total number of votes
totalVotesCount += 1
# append unique names to the candidates list
if row[2] not in uniqueCandidates:
uniqueCandidates.append(row[2])
# make a list of all the votes
votes.append(row[2])
# start a second loop that will populate the candidateCount with each vote
for candidate in uniqueCandidates:
candidateCount.append(votes.count(candidate))
percent.append(round(votes.count(candidate)/totalVotesCount*100,3))
# find the winner using index position of the max count in candidateCount
winner = uniqueCandidates[candidateCount.index(max(candidateCount))]
# print results, use a loop for the number of uniqueCandidates
print('Election Results')
print('--------------------------------')
print(f'Total Votes: {totalVotesCount}')
print('--------------------------------')
for i in range(len(uniqueCandidates)):
print(f'{uniqueCandidates[i]}: {percent[i]}% {candidateCount[i]}')
print('--------------------------------')
print(f'Winner: {winner}')
print('--------------------------------')
# set exit path
poll_output = os.path.join("PyPollResults.txt")
# write out results to text file
with open(poll_output, "w") as txtfile:
txtfile.write('Election Results')
txtfile.write('\n------------------------------------')
txtfile.write(f'\nTotal Votes: {totalVotesCount}')
txtfile.write('\n------------------------------------')
for i in range (len(uniqueCandidates)):
txtfile.write(f'\n{uniqueCandidates[i]}: {percent[i]}% {candidateCount[i]}')
txtfile.write('\n------------------------------------')
txtfile.write(f'\nWinner: {winner}')
txtfile.write('\n------------------------------------')
# read in the CSV file
with open(poll_csv, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# adjust for header
csv_header = next(csvfile)
# use function
get_results(csvreader) |
2d79716197efaee245bf7ea7f99e29b244c9bdc8 | KaisChebata/Computing-in-Python-III-Data-Structures-GTx-CS1301xIII-Exercises | /Extra Practice Problems/IMDb2.py | 1,921 | 4.125 | 4 | #Write a function called imdb_dictionary. imdb_dictionary
#should have one parameter, a string representing a
#filename.
#
#On each row of the file will be a comma-and-space-separated
#list of movies, then a colon, then a performer's name. For
#example, one file's contents could be:
#
#Avengers: Infinity War, Sherlock Holmes 3, Spider-Man: Homecoming; Robert Downey Jr.
#Avengers: Infinity War, Isle of Dogs, Ghost in the Shell; Scarlett Johansson
#Avengers: Infinity War, Kodachrome, Wind River, Ingrid Goes West; Elizabeth Olsen
#
#You may assume that the only semi-colon will be before the
#performer's name, and that there will be no commas in the
#movie titles.
#
#Return a dictionary where the keys are each actor's name,
#and the values are alphabetically-sorted lists of the movies
#they have been in. For example, if imdb_dictionary was called
#on the file above, the output would be:
#{"Robert Downey Jr.": ["Avengers: Infinity War", "Sherlock Holmes 3", "Spider-Man: Homecoming"],
#"Scarlett Johansson": ["Avengers: Infinity War", "Ghost in the Shell", "Isle of Dogs"],
#Elizabeth Olsen": ["Avengers: Infinity War", "Ingrid Goes West", "Kodachrome", "Wind River"]}
#
#Make sure the list of movies is sorted alphabetically. Don't
#worry about the order the keys (names) appear in the dictionary.
#
#Hint: Remember to deal with the spaces after the commas and
#semicolons!
#Add your code here!
#Below are some lines of code that will test your function.
#You can change the contents of some_performers.txt from
#the dropdown in the top left to test other inputs.
#
#If your function works correctly, this will originally
#print (although the order of the keys may vary):
#{"Robert Downey Jr.": ["Avengers: Infinity War", "Sherlock Holmes 3", "Spider-Man: Homecoming"], "Scarlett Johansson": ["Avengers: Infinity War", "Ghost in the Shell", "Isle of Dogs"], Elizabeth Olsen": ["Avengers: Infinity War", "Ingrid Goes West", "Kodachrome", "Wind River"]}
print(imdb_dictionary("some_performers2.txt"))
|
a5b5a7495632910ba32e0db22f2041cd798de9d4 | Vencislav-Dzhukelov/101-3 | /week7/2-SQL-Starter/create_company.py | 1,053 | 3.96875 | 4 | import sqlite3
def create():
db = sqlite3.connect('company.db')
cursor = db.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS company(id INTEGER PRIMARY KEY, name TEXT,
monthly_salary REAL, yearly_bonus REAL, position TEXT)
"""
cursor.execute(create_table_query)
cursor.execute("INSERT INTO company(name, monthly_salary, yearly_bonus, position) VALUES('Ivan Ivanov', 5000, 10000, 'Software Developer')")
cursor.execute("INSERT INTO company(name, monthly_salary, yearly_bonus, position) VALUES('Rado Rado', 500, 0, 'Technical Support Intern')")
cursor.execute("INSERT INTO company(name, monthly_salary, yearly_bonus, position) VALUES('Ivo Ivo', 10000, 100000, 'CEO')")
cursor.execute("INSERT INTO company(name, monthly_salary, yearly_bonus, position) VALUES('Petar Petrov', 3000, 1000, 'Marketing Manager')")
cursor.execute("INSERT INTO company(name, monthly_salary, yearly_bonus, position) VALUES('Maria Georgieva', 8000, 10000, 'COO')")
db.commit()
if __name__ == "__main__":
create()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.