blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
709d16e136200a63293034a93874d66c775d7b15 | Sem31/Data_Science | /2_Numpy-practice/16_mathematical_functions.py | 661 | 3.9375 | 4 | # Mathematical Functions
import numpy as np #np is a alias name
#rounding function
#np.around(array,decimal)
print("Round function in numpy : ")
a = np.array([1.0,5.55,123,0.567,25.234])
print(a)
print('\nArray after rounding : ')
print(np.around(a))
print(np.around(a, decimals = 1))
print(np.around(a, decimals = -1))
#floor() --> return the floor value
print('\nGiven values are : ')
x = np.array([-1.7,1.5,-0.2,0.6,10])
print(x)
print('\nAfter floor function :')
print(np.floor(x))
#np.ceil() --> return the ceiling value
print('\nGiven values are :')
x = np.array([-1.7,1.5,-0.2,0.6,10])
print(x)
print('\nAfter ceil function :')
print(np.ceil(x))
|
6d8131b97e888562562cd327fd41e049769c85b9 | JulesDesmet/lsh | /src/jaccard.py | 517 | 3.640625 | 4 | #!/usr/bin/env python3.9
from typing import TypeVar
Shingle = TypeVar("Shingle")
def jaccard(set_1: set[Shingle], set_2: set[Shingle]) -> float:
"""
Computes the Jaccard similarity between two sets.
:param set_1:
:param set_2: The sets for which the similarity should be computed.
:return: The Jaccard similarity, which is computed as
`|set_1 ∩ set_2| / |set_1 ∪ set_2|`.
"""
if not set_1 and not set_2:
return 0.0
return len(set_1 & set_2) / len(set_1 | set_2)
|
6410dd88b2218248e9fe437d25f6199b4c5add62 | Rathetsu/GoogleHashCode2021_DroneDelivery | /helpers.py | 816 | 3.625 | 4 | def is_order_complete(order,payload):
for item in order:
if item not in payload or payload[item] != order[item]:
return False
return True
def find_hq(warehouses,orders):
"""
Finds the closes warehouse to all orders such that drones cand drop products there
"""
min_warehouse = None
min_dist = 1e12
for warehouse in warehouses:
total_dist = 0
for order in orders:
dist = warehouse['pos'].distance(order.pos)
total_dist += dist
if total_dist < min_dist:
min_dist = total_dist
min_warehouse = warehouse
return min_warehouse
def get_easiest_order(orders,drones,warehouses):
""""
returns the order which takes the least time for a specific drone
"""
pass
|
db133eea811e2e8bb7834986d7d8160371c5c4af | lucas234/leetcode-checkio | /LeetCode/69.Sqrt(x).py | 732 | 3.71875 | 4 | # @Time : 2021/7/27 9:39
# @Author : lucas
# @File : 69.Sqrt(x).py
# @Project : locust demo
# @Software: PyCharm
def my_sqrt(x: int) -> int:
if x == 1: return 1
for i in range(int(x / 2) + 1):
if i * i == x:
return i
if i * i > x:
return i - 1
return i
print(my_sqrt(2))
# class Solution:
# def mySqrt(self, x: int) -> int:
# low = 0
# high = x
# while low <= high:
# mid = low + (high - low) // 2
# if mid * mid == x:
# return mid
# elif mid * mid < x:
# ans = mid
# low = mid + 1
# else:
# high = mid - 1
# return ans |
23e569b2e2832ed8b3f5832a741554303c6e68d7 | jalondono/holbertonschool-machine_learning | /supervised_learning/0x0D-RNNs/2-gru_cell.py | 1,952 | 3.5 | 4 | #!/usr/bin/env python3
"""GRU Cell """
import numpy as np
class GRUCell:
"""GRUCell class"""
def __init__(self, i, h, o):
"""
Constructor method
:param i: is the dimensionality of the data
:param h: is the dimensionality of the hidden state
:param o: is the dimensionality of the outputs
"""
self.Wz = np.random.randn(i + h, h)
self.Wr = np.random.randn(i + h, h)
self.Wh = np.random.randn(i + h, h)
self.Wy = np.random.randn(h, o)
self.bz = np.zeros((1, h))
self.br = np.zeros((1, h))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
def sigmoid(self, Z):
"""
Sigmoid activation function
:param Z: is the array of W.X + b values
:return: Y predicted
"""
sigma = (1 / (1 + np.exp(-Z)))
return sigma
def softmax(self, x):
"""softmax function"""
return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True)
def forward(self, h_prev, x_t):
"""
performs forward propagation for one time step
:param h_prev: is a numpy.ndarray of shape (m, i)
that contains the data input for the cell
:param x_t: is a numpy.ndarray of shape (m, h)
containing the previous hidden state
:return: h_next, y
"""
conc_input = np.concatenate((h_prev, x_t), axis=1)
# update gqate
zt = self.sigmoid(np.matmul(conc_input, self.Wz) + self.bz)
# reset gate
rt = self.sigmoid(np.matmul(conc_input, self.Wr) + self.br)
h_x = np.concatenate((rt * h_prev, x_t), axis=1)
# new candidates
ht_hat = np.tanh(np.matmul(h_x, self.Wh) + self.bh)
# Final memory
ht = (1 - zt) * h_prev + zt * ht_hat
Z_y = np.matmul(ht, self.Wy) + self.by
# softmax activation
y = self.softmax(Z_y)
return ht, y
|
5e3df1b73850a12efbd5b7ef01dd21b78598e71e | bionictruck/Game | /character.py | 1,463 | 3.921875 | 4 | def c_name():
while True:
try:
c_name = raw_input("Enter a name: ")
if len(c_name) > 2:
print "Hello " + c_name + ", prepare for your adventure." + "\n"
return c_name
else:
print "Sorry the name must contain at least 2 characters"
except:
break
def c_story():
while True:
try:
story = raw_input("Add a backstory 500 characters or less. Press Enter to skip: " "\n")
if len(story) < 500:
return 'Character Story: ' + story + "\n"
else:
print "Backstory is restricted to 500 characters"
except:
break
def c_skills():
restart = False
skill_points = 60
c_skill = {'One-Hand' : 0, 'Two-Hand' : 0, 'Fisticuffs' : 0, 'Marksmanship' : 0, 'Stamina' : 0, 'Agility' : 0}
for skill in c_skill:
skill_entry = int(raw_input('How many points would you like to add to ' + skill + '? '))
if skill_entry > skill_points:
print "You don't have enough points!"
print "Let's try this again."
restart = True
if restart == True:
c_skills()
else:
c_skill[skill] = skill_entry
skill_points = skill_points - skill_entry
print 'You have', skill_points, 'points left.'
return c_skill |
7b16ff69cdb9ab97c90adf3eef25139a4859a108 | davidabcdef123/pythonDemo | /test1/src/main/ShuRuShuChu.py | 1,208 | 3.765625 | 4 | import math
hello = 'hello, runoob\n'
hellos = repr(hello)
print(hellos)
for x in range(1, 11):
print(repr(x).rjust(2), repr(x * x).rjust(3), end= '')
print(repr(x*x*x).rjust(4))
for x in range(1,11):
print('{0:0d}{1:3d}{2:4d}'.format(x,x*x,x*x*x))
print('l2'.zfill(5))
print('-3.14'.zfill(7))
print('3.14159265359'.zfill(5))
print('{}网址:"{}!"'.format('菜鸟教程','www.runoob.com'))
print('{0}和{1}'.format('google','runnoob'))
print('{1}和{0}'.format('google','runnoob'))
print('{name}网址,{site}'.format(name='菜鸟教程',site='www.runnob,com'))
print('常量pi的近似值为:{}'.format(math.pi))
print('常量pi的近似值为:{!r}'.format(math.pi))
print('3f常量PI 的值近似为{0:.3f}'.format(math.pi))
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
for name,number in table.items():
print('{0:10}==>{1:10d}'.format(name,number))
print('--------------------------------')
print('Runoob: {Runoob:d};Google:{Google:d};TaoBao:{Taobao:d}'.format(**table))
print('Runoob: {Runoob:d};Google:{Google:d};Taobao:{Taobao:d}'.format(**table))
print('常量PI 的值近似为:%5.3f'%math.pi)
str=input("输入")
print('输入的内容是:',str)
|
a477083bccb434d507b3187b3b49a37a94c625ad | thileepanp/Python-practice | /string cleaning.py | 422 | 3.71875 | 4 | """
Functions to clean strings!!
"""
import re
def remove_punctuation(value):
return re.sub('[!@#$%^&*()"''<>?/,.~`{}[]\|]', '', value)
clean_ops = [str.strip, remove_punctuation,str.title]
result =[]
def clean_strings(strings, ops):
for value in strings:
for function in ops:
value = function(value)
result.append(value)
return(result)
#To run the operation run
clean_strings(string_list, clean_ops) |
dcf6bbbf0f75cfe99d7c75e1592df2a1b9c7a80e | AndrewCochran22/python-101 | /c_to_f.py | 272 | 4.21875 | 4 | # def celsius_to_fahrenheit(c):
# f = (c * 9/5) + 32
# return f
# celsius = float(input("Pick a celsius temp: "))
# print("Your temperature in fahrenheit is: ", celsius_to_fahrenheit(celsius))
number = int(input("Give me a Celsius degree: "))
F = (C * 9/5 + 32)
|
0c3b97e12b1b15ce1bb508790b7b8ebfb60d32df | qscf1234/pythontext | /day04/条件控制语句.py | 476 | 3.84375 | 4 | # -*-coding: utf-8 -*-
'''
if 语句
if-else语句
if-elif-else语句
格式:
if 表达式1:
语句1
elif 表达式2:
语句2
elif 表达式3:
语句3
。。。。。。。。。。。
else:
语句.......
'''
age = int(input())
if age < 0:
print('娘胎里')
elif age < 3 and age >= 0:
print('婴儿')
elif age < 6 and age >= 3:
print('童年')
elif age < 18 and age >= 6:
print('少年')
else:
print('中年')
|
74f8d0ffba6981b7aeb8d437a1fd6cdefe5f1f20 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2421/60605/241462.py | 215 | 3.703125 | 4 | def changeNum(string):
newstr = ""
for i in list(string):
if i == "9":
newstr = newstr + i
continue
newstr = newstr + "9"
break
print(input().strip()) |
a662a58f5e7d909f73d26fc5b3c375f7258e0f81 | saumya470/python_assignments | /.vscode/Abstraction/abstractionAssignment.py | 1,247 | 3.96875 | 4 | # Create an abstract parent class or interface - TouchScreenLaptop with two abstract methods - scroll() and click(). This complete
# abstract class should be inherited or extended by HP and DELL which are also abstract classes which implement the scroll() method.
# Then create two more classes- HPNotebook and DELLNotebook which are the actual implementations of HP and DELL respectively and should
# implement the click methods(They can also override the scroll methods). Create objects of HPNotebook and DELLNotebook to access the two methods
from abc import abstractmethod, ABC
class TouchScreenLaptop(ABC):
@abstractmethod
def scroll(self):
pass
@abstractmethod
def click(self):
pass
class HP(TouchScreenLaptop):
def scroll(self):
print('Scrolling the HP model')
class DELL(TouchScreenLaptop):
def scroll(self):
print('Scrolling the DELL laptop')
class HPNotebook(HP):
def click(self):
print('Clicking the HPNotebook model')
class DELLNotebook(DELL):
def click(self):
print('Clicking the DELL Notebook')
hpNotebook = HPNotebook()
hpNotebook.click()
hpNotebook.scroll()
dellNotebook = DELLNotebook()
dellNotebook.click()
dellNotebook.scroll()
|
be33ca14bf93746ed64854ad99788b41138db107 | barreto-jpedro/Python-course-exercises | /Mundo 02/Ex041.py | 487 | 4.15625 | 4 | print('Descubra em qual categoria você se encaixa!')
idade = int(input('Digite a sua idade: '))
if idade < 9:
print('Você será alocado na categoria MIRIM')
elif 9 <= idade and idade < 14:
print('Você será alocado na categoria INFANTIL')
elif 14 <= idade and idade < 19:
print('Você será alocado na categoria JUNIOR')
elif 19 <= idade and idade < 20:
print('Você será alocado na categoria SENIOR')
else:
print('Você será alocado na categoria MASTER')
|
4f2d7e7d2766e30475afea7b7292850f084bad7b | lingxiao00/python_tutorials | /python小技巧/python interview/19 多线程创建常用方法.py | 1,451 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-01-23 22:27:22
# @Author : cdl ([email protected])
# @Link : https://github.com/cdlwhm1217096231/python3_spider
# @Version : $Id$
import time
from threading import Thread
# 自定义线程函数
def my_threadfunc(name='python3'):
for i in range(2):
print("hello", name)
time.sleep(1)
# 创建线程01,不指定参数
thread_01 = Thread(target=my_threadfunc)
# 启动线程01
thread_01.start()
# 创建线程02,指定参数,注意逗号不要少,否则不是一个tuple
thread_02 = Thread(target=my_threadfunc, args=('Curry',))
# 启动线程02
thread_02.start()
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, name='Python3'):
super().__init__()
self.name = name
def run(self):
for i in range(2):
print("Hello", self.name)
time.sleep(1)
# 创建线程03,不指定参数
thread_03 = MyThread()
# 创建线程04,指定参数
thread_04 = MyThread("Curry")
thread_03.start()
thread_04.start()
t = Thread(target=func)
# 启动子线程
t.start()
# 阻塞子线程,待子线程结束后,再往下执行
t.join()
# 判断线程是否在执行状态,在执行返回True,否则返回False
t.is_alive()
t.isAlive()
# 设置线程是否随主线程退出而退出,默认为False
t.daemon = True
t.daemon = False
# 设置线程名
t.name = "My-Thread"
|
a787ac1ba4671e29e9a031269a6235e05d20516e | Macielyoung/LeetCode | /152. Maximum Product Subarray/maxProduct.py | 604 | 3.5625 | 4 | #-*- coding: UTF-8 -*-
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cursor = nums[0]
num = len(nums)
imax = imin = cursor
for i in range(1, num):
if nums[i] < 0:
imax, imin = imin, imax
imax = max(nums[i], imax*nums[i])
imin = min(nums[i], imin*nums[i])
cursor = max(cursor, imax)
return cursor
if __name__ == '__main__':
solu = Solution()
nums = [2,3,-2,4]
res = solu.maxProduct(nums)
print(res)
|
bf13dfcbe61f9db8bbc0fff0008d89527c58e9de | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Dynamic Programming/max_len3_sub_array.py | 3,034 | 4.15625 | 4 | # Fixed size window
def max_sub_array(array, k):
running_sum = 0
maxValue = -2**31
# We iterate the entire length of the array
for i in range(len(array)):
# Build our running sum value with each iteration
running_sum += array[i]
# If i >= k-1 this means we have our window
# We do k-1 to account for the fact that we are using len(list)
if i >= k-1:
# Find the max value between the current window and the running sum window which changes as we go
maxValue = max(maxValue, running_sum)
# We remove the first element in the window from our running sum, hence we deduct it. We do this because we want to
# continue to "slide" our window along the array, hence removing one element from the front leaving us with 2
# then adding one element to the end hence giving us one again, the continuously checking the sum of each new consecutive window
running_sum -= array[i-(k-1)]
return maxValue
print(max_sub_array([4,2,1,7,8,1,2,8,1,0], 3))
# Dynamic window
# Kadane's Algorithm
# Ok, we want to find the largest possible contiguous subarray from a given array. What Kadane's algortihm does is like a dynamic sliding window approach
# What's happening is, we have two variables, current and global maximums, pretty much current is the current size of the dynamic window and global is the max
# recorded size of the dynamic window. So, whats going to happen is as we iterate through the array, find the current_max sub array or better think of it as the current
# max dynamic window. We check, is my current sub array or current element greater than the current element plus the previous sub array. If our current element is greater
# we stick with that elements, else our current element plus the previous sub array elements with dynamic window of size x is greater. So what this implies is simply, each iteration
# we are building up our largest sub array, we have our initial global max right, then we uodate once most likely, then as we keep building up our local_max we keep updating the global max
def maxSubArray(nums):
# Initalize two variables, current and global max to point at the first element in the array
current_max = global_max = nums[0]
#Iterate from the 1st index in the array till the end, we skip the 0th index because we are already looking at it with curret_max and global_max
for i in range(1, len(nums)):
# Every iteration, we ask, is the current array value greater than the current array value plus the previous array value, we ask this ofcourse as there may be negative elements
# Which decrease our total maximum sum, which we do not want, we want the maximum.
current_max = max(nums[i], nums[i] + current_max)
# Next we keep updating our global maximum aslong as current_max is growing!
if current_max > global_max:
global_max = current_max
return global_max
|
04c6dae4f347b4cea2059faf697be62e773cc518 | erjoalgo/pitchperception | /pitchperception/pitchperception.py | 4,692 | 3.578125 | 4 | #!/usr/bin/python
"""An interactive game to test the user's pitch perception abilities.
Inspired by "Measure your pitch perception abilities"
from http://jakemandell.com/adaptivepitch.
"""
import contextlib
import random
import subprocess
import time
import curses
try:
from ._version import __version__
except:
traceback.print_exc()
__version__ = "unknown"
class PitchPerceptionGameConfig(object):
"""Config for a PitchPerceptionGame."""
def __init__(self,
initial_delta=220,
ref_tone=440,
max_incorrect_attempts=2,
min_correct_attempts=3):
self.initial_delta = initial_delta
self.ref_tone = ref_tone
self.max_incorrect_attempts = max_incorrect_attempts
self.min_correct_attempts = min_correct_attempts
class UserQuitError(Exception):
"""Propagates a user quit up the stack."""
pass
class PitchPerceptionChallenge(object):
"""An interactive game to test the user's pitch perception abilities."""
def __init__(self, game_config):
self.game_config = game_config
self.win = None
@staticmethod
def beep(freq):
"""Beep at the given frequency in Hz."""
cmd = ["beep", "-f", str(freq)]
subprocess.check_output(cmd)
def curses_print(self, message):
self.win.clear()
self.win.addstr(0, 0, message)
self.win.refresh()
def curses_getch(self):
ch = self.win.getch()
if ch == 27:
ch = self.win.getch()
assert ch == 91
ch = self.win.getch()
return ch
def _play_tone_challenge(self, first, second):
assert first != second
self.beep(first)
self.beep(second)
prompt = ("Is the second pitch higher or lower "
"(Up: higher, Down: lower, r: repeat, q: quit)? ")
UP, DOWN, REPEAT, QUIT = 65, 66, 114, 113
while True:
self.curses_print(prompt)
ch = self.curses_getch()
if ch == REPEAT:
self.beep(first)
self.beep(second)
elif ch in (UP, DOWN):
return (second > first) == (ch == UP)
elif ch == QUIT:
raise UserQuitError()
else:
self.curses_print("unknown key: {}".format(ch))
time.sleep(2)
@staticmethod
def flip_coin():
return random.randint(0, 1)
def _challenge_at_delta(self, delta):
"""Returns true iff the user can distinguish pitch up to delta Hz."""
assert delta > 0
correct, incorrect = 0, 0
while True:
first = self.game_config.ref_tone
second = first + delta * (1 if self.flip_coin() else -1)
if self.flip_coin():
first, second = second, first
is_correct = self._play_tone_challenge(first, second)
if is_correct:
correct += 1
if correct >= self.game_config.min_correct_attempts:
return True
else:
incorrect += 1
self.curses_print("incorrect: {} => {}".format(first, second))
time.sleep(1)
if incorrect >= self.game_config.max_incorrect_attempts:
return False
@staticmethod
@contextlib.contextmanager
def ncurses_win():
curses_win = curses.initscr()
try:
yield curses_win
finally:
curses.endwin()
def start(self):
end_message = None
with self.ncurses_win() as self.win:
curses.noecho()
delta = self.game_config.initial_delta
last_delta = None
while True:
try:
passed = self._challenge_at_delta(delta)
except UserQuitError:
passed = False
if passed:
last_delta, delta = delta, delta/2.0
elif last_delta is None:
end_message = "unable to determine pitch perception"
break
else:
end_message = (
("your ear is sensitive to pitch differences "
"up to {}Hz").format(delta*2))
break
print (end_message)
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--version", action="version", version=__version__)
args = parser.parse_args()
game_config = PitchPerceptionGameConfig()
game = PitchPerceptionChallenge(game_config)
game.start()
|
6484b57595aaf3032c01377c40b3591903511f68 | asatiratnesh/Python_Assignment | /FileHandlingAssig/assig9.py | 360 | 3.84375 | 4 | # find out count of all the python files in any specific directory and subdirectory
import os
# Open a file
path = raw_input("Enter Dir Path: ")
count = 0
for root, dirList, fileList in os.walk(path):
for x in fileList:
if x.endswith(".py"):
count += 1
print "Count of python files in any specific directory and subdirectory: ", count
|
d28a036c02e504d9376f68cd65569ab32efa3b25 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Homework/Homework_Boni/SecretNumberGameTryouts.py | 1,654 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Libraries
import random
#variablen
secret = int(10 * random.random()) + 1
oldsecret = secret
guess = 0
#Nachfolgend die Bedingung für die whileschleife(Haben wir falsch geraten?)
"""
while guess != secret:
guess = int(raw_input("Errate die Geheimzahl bis 10:"))
if guess == secret:
print "Du hast es!"
oldsecret = secret
secret = int(10 * random.random()) + 1
while secret == oldsecret:
secret = int(10 * random.random()) + 1
print("Secret = "+str(secret))
else:
print "Leider nicht, sehr ärgerlich! versuche es erneut! " + str(guess)+(" ist falsch")
"""
#zweite Möglichkeit:
"""
def getSecret():
return int(10 * random.random()) + 1
while guess != secret:
guess = int(raw_input("Errate die Geheimzahl bis 10:"))
if guess == secret:
print "Du hast es!"
secret = getSecret()
print("Secret = "+str(secret))
guess = 0
else:
print "Leider nicht, sehr ärgerlich! versuche es erneut! " + str(guess)+(" ist falsch")
"""
#dritte mit mehr funktionen
def getSecret():
return int(10 * random.random()) + 1
def istFalsch():
global guess
global secret
return guess != secret
def pruefung():
global guess
global secret
guess = int(raw_input("Errate die Geheimzahl bis 10:"))
if guess == secret:
print "Du hast es!"
secret = getSecret()
print("Secret = " + str(secret))
guess = 0
else:
print "Leider nicht, sehr ärgerlich! versuche es erneut! " + str(guess) + (" ist falsch")
while istFalsch(): pruefung() |
e69d4b0d739617711584d1985b89989e383763cc | Hash-Studios/algoking | /python/greatest_common_divisor.py | 687 | 4 | 4 | def greatest_common_divisor(a, b):
return a if b == 0 else greatest_common_divisor(b, a % b)
def gcd_by_iterative(x, y):
while y:
x, y = y, x % y
return x
def main():
try:
nums = input("Enter two integers separated by space ( ): ").split(" ")
num_1 = int(nums[0])
num_2 = int(nums[1])
print(
f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}"
)
print(
f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}")
except (IndexError, UnboundLocalError, ValueError):
print("Wrong input")
if __name__ == "__main__":
main()
|
69edd16c5d3eed00be694e931efb6bc93ceb38ad | szeitlin/data-incubator | /blah_algebra.py | 1,533 | 3.546875 | 4 | __author__ = 'szeitlin'
def make_blah(num):
"""blah = sum of square of digits mod 59
and
4 digit positive int -> int
>>>blah(6789)
(6**2 + 7 **2 + 8 **2 + 9 **2) mod 59
53
"""
#would be nice to do this with a list comprehension or map reduce fcns
a = 0
for i in str(num):
a += (int(i)**2)
#print a
blah = (a % 59)
return blah
#make_blah(6789)
def des_4dig(num):
"""
helper function to determine if a number is descending, i.e. if digits decrease left to right
4 digit positive int -> bool
>>>des_4dig(6789)
False
>>>des_4dig(5432)
True
"""
numo = list(str(num))
b = 0
for i in range(len(numo)-1):
flag = False
if numo[b+1] >= numo[b] :
break
return flag
elif numo[b+1] < numo[b]:
b +=1
flag = True
return flag
# print des_4dig(6789)
# print des_4dig(5432)
# print des_4dig(9999)
# print des_4dig(9998)
# print des_4dig(1018)
def algrabbra():
"""
returns all possible descending 4-digit integers whose blah is 7.
as a comma-separated sorted list
"""
### start with 9999 (max 4-digit number)
###first descending from there would be 9876
### could write a separate thing just to come up with these, but I think this is easier?
unsorted = []
for num in range(1000, 9999):
if (des_4dig(num) == True) and (make_blah(num) ==7):
unsorted.append(num)
print unsorted
algrabbra()
|
76672e9f028628efa0e411ca98e2ae1358413d42 | GreenMarch/datasciencecoursera | /algo/heap/kth-smallest-element-in-a-sorted-matrix.py | 797 | 3.8125 | 4 | import heapq
class Solution:
def kthSmallest(self, matrix, k):
nums = []
for row in matrix:
for val in row:
nums.append(val)
heapq.heapify(nums)
return heapq.nsmallest(k, nums)[-1]
data = [[1,5,9],[10,11,13],[12,13,15]]
k = 8
print(Solution().kthSmallest(data, k))
"""
378. Kth Smallest Element in a Sorted Matrix
Medium
1780
106
Add to List
Share
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
""" |
3ea7c63c5ff79bb362d24f0d9ff4d143a05bb3de | raririn/LeetCodePractice | /Solution/289_Game_of_Life.py | 2,112 | 3.53125 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.board = board
self.l = len(board)
self.w = len(board[0])
status = [[0] * self.w for _ in range(self.l)]
for i in range(self.l):
for j in range(self.w):
status[i][j] = self.statusUpdate(board[i][j], self.countLivingNeighbor([i, j]))
#print("prev: ", i, j ,board[i][j], " count: ", self.countLivingNeighbor([i, j]), " after:", status[i][j])
for i in range(self.l):
for j in range(self.w):
board[i][j] = status[i][j]
@staticmethod
def statusUpdate(prev: int, neighbors: int) -> int:
if prev and (neighbors < 2 or neighbors > 3):
return 0
if (not prev) and (neighbors == 3):
return 1
return prev
def countLivingNeighbor(self, cell: List[int]) -> int:
countList = [0] * 8
if cell[0] >= 1: #Left
countList[0] = self.board[cell[0]-1][cell[1]]
if cell[1] >= 1:
countList[4] = self.board[cell[0]-1][cell[1]-1] # Leftup
if cell[1] <= self.w - 2:
countList[5] = self.board[cell[0]-1][cell[1]+1] # LeftDown
if cell[0] <= self.l - 2: # Right
countList[1] = self.board[cell[0]+1][cell[1]]
if cell[1] >= 1:
countList[6] = self.board[cell[0]+1][cell[1]-1] # Rightup
if cell[1] <= self.w - 2:
countList[7] = self.board[cell[0]+1][cell[1]+1] # Rightdown
if cell[1] >= 1: # Up
countList[2] = self.board[cell[0]][cell[1]-1]
if cell[1] <= self.w - 2: # Down
countList[3] = self.board[cell[0]][cell[1]+1]
return sum(countList)
'''
Runtime: 44 ms, faster than 27.25% of Python3 online submissions for Game of Life.
Memory Usage: 13.5 MB, less than 10.00% of Python3 online submissions for Game of Life.
''' |
41da291db485d72657a6dfc685d05935c9ad51dd | dupandit/Datastructure-and-Algorithms | /bubblesort.py | 648 | 3.640625 | 4 | n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
count = 0
sorted= False
while sorted == False :
## Track number of elements swapped during a single array traversal
numberofSwaps = 0
for j in range(n-1) :
##Swap adjacent elements if they are in decreasing order
print n
if (a[j] > a[j + 1]) :
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
count = count + 1
numberofSwaps=numberofSwaps+1
##If no elements were swapped during a traversal, array is sorted
if (numberofSwaps == 0) :
sorted = True
print a |
e39031a89464aa80b058443b2625fabbdc2997cb | clcocks/Year7_Python_S2 | /variables/how old/task.py | 140 | 3.90625 | 4 | name = input('what is your name? ')
print('hi '+ name)
age = input('how old are you?')
print(age+' is really old!')
print('bye '+ name)
|
965a4a16b374968f33734c92dfa2daf20a0992fe | shanksms/python_cookbook | /decorators/preserve_meta_data.py | 959 | 3.5 | 4 | import time
from functools import wraps
'''
Copying decorator metadata is an important part of writing decorators.
If you forget to use @wraps, you’ll find that the decorated function loses all sorts of useful information.
For instance, if omitted, the metadata in the last example would look like this:
>>> countdown.__name__
'wrapper'
>>> countdown.__doc__
>>> countdown.__annotations__
{}
>>>
'''
def timethis(func):
'''
Decorator that reports the execution time.
'''
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n : int):
'''
count down
:param n:
:return:
'''
while n > 0:
n -= 1
if __name__ == '__main__':
countdown(10)
countdown.__name__
countdown.__annotations__
countdown.__doc__
|
f55cd6e90820d728904e5ebba5a0b734624a9c37 | wensjuma/Msomi-App | /app/api/v1/models/profile_model.py | 1,571 | 3.609375 | 4 |
profile = []
class Profile(object):
""" profile data model to store data """
def __init__(self):
self.profile = profile
def create_profile(self,data):
profile = {
'user_id' : len(self.profile) + 1,
'username' : data['username'],
'telephone' : data['telephone'],
'passportUrl' : data['passportUrl'],
'school_level' : data['school_level'],
'status' : data['status']
}
self.profile.append(profile)
return profile
def get_specific_profile(self,id):
""" Fetch a single profile by its ID """
profile = [task for task in self.profile if task['user_id'] == id]
return profile
def get_profiles(self):
""" Get all the registered profiles """
return self.profile
def update_profile(self,user_id, data):
""" Update a profile by id """
profile = [task for task in self.profile if task['user_id'] == user_id]
profile[0]['user_id'] = user_id
profile[0]['username'] = data['username']
profile[0]['telephone'] = data['telephone']
profile[0]['passportUrl'] = data['passportUrl']
profile[0]['school_level'] = data['school_level']
profile[0]['status'] = data['status']
return profile
def delete_profile(self, id):
""" Delete a profile by ID """
profile = [task for task in self.profile if task['user_id'] == id]
self.profile.remove(profile[0])
return profile |
4f5be43c67e71d3e664508f8803005cf4e32b880 | patrickmalg/aulas-python | /PYTHON-MUNDO 1/aula02-condicional.py | 295 | 3.953125 | 4 | idade = int(input("Digite a idade: "))
if idade < 16:
print("Não pode votar.")
elif idade >= 16 and idade < 18:
print("Pode votar, mas não é obrigatório.")
elif idade >= 18 and idade < 70:
print("É obrigatório votar.")
else:
print(" Pode votar, mas não é obrigatório.") |
99d28987a096dcbf843e5cced3a9f4cc1b5f78d5 | Alexsandra-kom/HW_Python | /HW8_Alexsandra_7.py | 1,150 | 4.15625 | 4 | # 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число», реализуйте перегрузку
# методов сложения и умножения комплексных чисел. Проверьте работу проекта, создав экземпляры класса (комплексные
# числа) и выполнив сложение и умножение созданных экземпляров. Проверьте корректность полученного результата.
class ComplexNumber:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return f'Сумма равна: {self.a + other.a} + {self.b + other.b} * i'
def __mul__(self, other):
return f'Произведение равно: {self.a * other.a - (self.b * other.b)} + {self.b * other.a} * i'
ComplexNum_1 = ComplexNumber(5, -7)
ComplexNum_2 = ComplexNumber(12, 15)
print(ComplexNum_1 + ComplexNum_2)
print(ComplexNum_1 * ComplexNum_2) |
ca5839ecff60befd2eff0ed150e896d640be831c | ferociousmadman/python | /student-login/student.py | 5,126 | 4.03125 | 4 | def list_courses(id, c_list, r_list):
# ------------------------------------------------------------
# This function displays and counts courses a student has
# registered for. It has three parameters: id is the ID of the
# student; c_list is the course list; r_list is the list of
# class rosters. This function has no return value.
# -------------------------------------------------------------
print("Courses registered: ")
count = 0
if id in r_list[0]:
print(c_list[0])
count += 1
elif id not in r_list:
pass
if id in r_list[1]:
print(c_list[1])
count += 1
elif id not in r_list:
pass
if id in r_list[2]:
print(c_list[2])
count += 1
elif id not in r_list:
pass
print("Total number: ", count, '\n')
def add_course(id, c_list, r_list, m_list):
# ------------------------------------------------------------
# This function adds a student to a course. It has four
# parameters: id is the ID of the student to be added; c_list
# is the course list; r_list is the list of class rosters;
# m_list is the list of maximum class sizes. This function
# asks user to enter the course he/she wants to add. If the
# course is not offered, display error message and stop.
# If the course is full, display error message and stop.
# If student has already registered for this course, display
# error message and stop. Add student ID to the course’s
# roster and display a message if there is no problem. This
# function has no return value.
# -------------------------------------------------------------
count_zero = 0
for i in r_list[0]:
count_zero += 1
count_one = 0
for i in r_list[1]:
count_one += 1
count_two = 0
for i in r_list[2]:
count_two += 1
course_added = input("Enter course you want to add: ")
if course_added not in c_list:
print("Course not found \n")
elif course_added in c_list:
if course_added == "CSC101" and id not in r_list[0]:
if count_zero < m_list[0]:
count_zero += 1
r_list[0].append(id)
print("Course added \n")
elif count_zero >= m_list[0]:
print("Course already full. \n")
elif course_added == "CSC101" and id in r_list[0]:
print("You are already enrolled in that course. \n")
if course_added == "CSC102" and id not in r_list[1]:
if count_one < m_list[1]:
count_one += 1
r_list[1].append(id)
print("Course added \n")
elif count_one >= m_list[1]:
print("Course already full. \n")
elif course_added == "CSC102" and id in r_list[1]:
print("You are already enrolled in that course. \n")
if course_added == "CSC103" and id not in r_list[2]:
if count_two < m_list[2]:
count_two += 1
r_list[2].append(id)
print("Course added \n")
elif count_two >= m_list[2]:
print("Course already full. \n")
elif course_added == "CSC103" and id in r_list[2]:
print("You are already enrolled in that course. \n")
def drop_course(id, c_list, r_list):
# ------------------------------------------------------------
# This function drops a student from a course. It has three
# parameters: id is the ID of the student to be dropped;
# c_list is the course list; r_list is the list of class
# rosters. This function asks user to enter the course he/she
# wants to drop. If the course is not offered, display error
# message and stop. If the student is not enrolled in that
# course, display error message and stop. Remove student ID
# from the course’s roster and display a message if there is
# no problem. This function has no return value.
# -------------------------------------------------------------
course_dropped = input("Enter course you want to drop: ")
if course_dropped not in c_list:
print("Course not found \n")
elif course_dropped in c_list:
if course_dropped == "CSC101" and id in r_list[0]:
r_list[0].remove(id)
print("Course dropped \n")
elif course_dropped == "CSC101" and id not in r_list[0]:
print("You are not enrolled in that course. \n")
if course_dropped == "CSC102" and id in r_list[1]:
r_list[1].remove(id)
print("Course dropped \n")
elif course_dropped == "CSC102" and id not in r_list[1]:
print("You are not enrolled in that course. \n")
if course_dropped == "CSC103" and id in r_list[2]:
r_list[2].remove(id)
print("Course dropped \n")
elif course_dropped == "CSC103" and id not in r_list[2]:
print("You are not enrolled in that course. \n")
|
b0714bcc4eda67b41925f1ff17c795e51a149715 | mayu0007/LeetCode | /155_MinStack.py | 3,718 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
155. Min Stack
Design a stack that supports
push, pop, top, and retrieving the minimum element in constant time.
"""
# Method 1: Use helper stack to store the current min element;
# Additional Space: O(N)
class MinStack_v1:
def __init__(self):
"""
initialize your data structure here.
"""
self.mainStack = []
self.minStack = []
def push(self, x: int) -> None:
self.mainStack.append(x)
# push the current min to minStack
if len(self.minStack) == 0 or self.minStack[-1] > x:
self.minStack.append(x)
else:
self.minStack.append(self.minStack[-1])
def pop(self) -> None:
if len(self.mainStack):
self.mainStack.pop()
self.minStack.pop()
def top(self) -> int:
if len(self.mainStack):
return self.mainStack[-1]
def getMin(self) -> int:
if len(self.minStack):
return self.minStack[-1]
# Method 2: The min stack only store current min value
# Additional Space: O(N)
class MinStack_v2:
def __init__(self):
"""
initialize your data structure here.
"""
self.mainStack = []
self.minStack = []
def push(self, x: int) -> None:
self.mainStack.append(x)
# push the element to minStack if it is the current min
if len(self.minStack) == 0 or self.minStack[-1] >= x:
self.minStack.append(x)
def pop(self) -> None:
if len(self.mainStack):
deleted = self.mainStack.pop()
if deleted == self.minStack[-1]:
self.minStack.pop()
def top(self) -> int:
if len(self.mainStack):
return self.mainStack[-1]
def getMin(self) -> int:
if len(self.minStack):
return self.minStack[-1]
# Method 2: Stack each element is a tuple (value, current_min)
# Additional Space: O(N)
class MinStack_v3:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
# Store current element, current min tuple
if self.stack:
self.stack.append((x,min(self.getMin(),x)))
else:
self.stack.append((x,x))
def pop(self) -> None:
if self.stack:
self.stack.pop()
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
def getMin(self) -> int:
if self.stack:
return self.stack[-1][1]
# Method 4: Use an variable to store the current min, prev min
# Additional Space: O(1)
class MinStack_v4:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minimum = None
def push(self, x: int) -> None:
if not self.stack:
self.minimum = x
self.stack.append(x)
elif x >= self.minimum:
self.stack.append(x)
elif x < self.minimum:
temp = 2 * x - self.minimum # temp < minimum
self.stack.append(temp)
self.minimum = x
def pop(self) -> None:
if self.stack:
popped = self.stack.pop()
if popped < self.minimum:
self.minimum = 2*self.minimum - popped
return (popped + self.minimum) // 2
def top(self) -> int:
if self.stack:
if self.stack[-1] < self.minimum:
return self.minimum
else:
return self.stack[-1]
def getMin(self) -> int:
return self.minimum
|
fefcf7d3596478e69db68de85887bbd77be021ff | NajibAdan/project-euler | /problem_010.py | 615 | 3.71875 | 4 | import math
def isPrime(n):
if n==1:
return False
elif n<4:
return True
elif n % 2 ==0:
return False
elif n<9:
return True
elif n % 3 == 0:
return False
else:
r = math.floor(math.sqrt(n))
f = 5
while f<=r:
if n % f == 0:
return False
if n % (f+2) == 0:
return False
f = f+6
return True
limit = 2_000_000
candidate = 1
sum = 2
while candidate <= limit:
candidate = candidate +2
if isPrime(candidate):
sum = candidate + sum
print(sum) |
af51e62329dc13dc473bc1165bfaaed2680d204d | Legion-web/Refresh | /Calculator.py | 119 | 3.875 | 4 | no1=float(input("Enter your first number:"))
no2=float(input("Enter your second number:"))
result=no1+no2
print(result) |
afc0a31b99cac2ebdf9fb6ac85e3abd0e5471971 | Sandy4321/tensorflow_examples | /simple CNN.py | 3,213 | 3.765625 | 4 | """使用tensorflow实现一个简单的卷积神经网络"""
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
sess = tf.InteractiveSession()
"""进行权重的初始化"""
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
"""进行偏置项的初始化"""
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)
"""卷积层操作
x :x是输入,形状类似为[-1(图片数量),28(横向像素数),28(纵向像素数),1(通道数,如果是灰度图片,通道为1,如果是rgb图片,通道为3)]
w : 形状类似为[5,5,1,32],前两个数字代表卷积核的尺寸,1代表通道数,32代表feture map的数量
[1,1,1,1]:代表卷积模版移动的布长,都是1代表不会遗漏其中任何一个点
padding="SAME":这样的处理方式代表给边界加上Padding让卷积的输入和输出保持同样的尺寸
"""
def conv2d(x,W):
return tf.nn.conv2d(x,W,[1,1,1,1],padding='SAME')
"""池化操作
ksize代表了池化的大小
strides代表了步长
"""
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
x = tf.placeholder(tf.float32,[None,784])
y_ = tf.placeholder(tf.float32,[None,10])
x_image = tf.reshape(x,[-1,28,28,1])
#初始化第一层的参数
w_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
#经过第一层的卷积和池化,尺寸变为14*14
h_conv1 = tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#初始化第二层的参数
w_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
#经过第二层的卷积和池化,尺寸变为7*7,但是有64个feture map
h_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# 将64个feture map上的特征连接一个有1024个隐藏层节点的全链接神经网络中
w_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
# 需要对此时的输出进行变形
h_poll2_flat = tf.reshape(h_pool2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_poll2_flat,w_fc1)+b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
w_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))
train_step = tf.train.AdagradOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accruacy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32))
tf.global_variables_initializer().run()
for i in range(20000):
batch_xs,batch_ys = mnist.train.next_batch(50)
if i%100==0:
train_accruacy = accruacy.eval(feed_dict={x:batch_xs,y_:batch_ys,keep_prob:1.0})
print ("step %d,training accruacy %g" % (i,train_accruacy))
train_step.run(feed_dict={x:batch_xs,y_:batch_ys,keep_prob:0.5})
print ('accuracy:'.format(accruacy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})))
|
ca78f2fa8fd365fa73ea40b98cc03ef84d9f0c8e | nandita-mehta/Python-Assignment | /Program_6.py | 194 | 4.0625 | 4 | def divisibility(x):
for i in range(0, x+1):
if i % 5 == 0 or i % 7 == 0:
yield i
n = int(input("Enter the number:"))
for i in divisibility(n):
print(i, end=", ")
|
350d2aaf2bfab570c87d37851d696e3bcddee6b9 | joseagb97/Tarea1GonzalezSoto | /tarea1.py | 2,532 | 4.03125 | 4 | def check_char(x):
if type(x) is not str: # Compara si la variable de entrada es string
print("No puede ingresar varoles de tipo int, array, float, clase...")
elif len(x) > 1: # Compara si solo se ingresó 1 solo caracter
print("Error: Solo puede ingresar una letra")
elif 64 < ord(x) < 91 or 96 < ord(x) < 123:
return 0 # Verifica que se es una letra del abecedario y retorna 0
else: # Es un solo caracter que no es parte del abecedario
print("Error: Solamente puede introducir letras(No cuenta la ñ)")
def caps_switch(x):
if check_char(x) == 0: # Verifica las condiciones de check_char
if ord(x) < 91: # Verifica que es mayúscula
return chr(ord(x) + 32) # Le suma 32 para la letra minúscula
else: # Cae en el caso de ser minúscula
return chr(ord(x) - 32) # Le resta 32 para la letra mayúscula
else:
print("Vuelva a intentarlo introduciendo solo 1 letra en formato str")
# PARA EJECUTAR LAS PRUEBAS ESCRIBA LA PALABRA pytest, LUEGO PRESIONE ENTER
# PRUEBAS
def test1(): # Verifica que sea solo 1 letra
assert check_char("vT") == 0
def test2(): # Verifica que sea una letra(no cuenta ñ)
assert check_char("ñ") == 0
def test3(): # Verifica que sea un string
assert check_char(8) == 0
def test4(): # Verifica todas las entradas para check_char
i = 65 # Primera letra(en número) en codigo ASCII
while i < 123:
assert check_char(chr(i)) == 0 # Cambia a caracter y verifica
if i == 90: # Última letra en mayúscula en ASCII
i = i + 7 # Salta a las letras minúsculas
else:
i = i + 1 # Salta a siguiente letra
def test5(): # Verifica todas las entradas para caps_switch
i = 65 # Primera letra(en número) en codigo ASCII
while i < 123: # Cambia a caracter y verifica
if i < 91: # Verifica que sea mayúscula
assert caps_switch(chr(i)) == chr(i + 32) # Verifica la minúscula
if i == 90: # Última letra en mayúscula en ASCII
i = i + 7 # Salta a las letras minúsculas
else:
i = i + 1 # Salta a siguiente letra
else:
assert caps_switch(chr(i)) == chr(i - 32) # Verifica la mayúscula
i = i + 1 # Salta a siguiente letra
|
c5bfcfe7c6b41d4b01171cc935e4722346886c66 | moman102/Python-Basis | /Math.py | 132 | 3.9375 | 4 | a = int(input(" a : "))
b = int(input(" b : "))
print(a + b)
print(a * b)
print(a // b)
print(a / b)
print(a ** b)
print(a % b)
|
d6c870e298f1953a572e56c505db466ea684d2f7 | kostur86/kasia_tut | /test_001/test_003.py | 2,022 | 3.796875 | 4 | #!env python3
"""
Draw a sprite in a PyGame window.
"""
import pygame
from pygame import K_ESCAPE, QUIT
# As long as this variable is True game will be running
active = True
# Some global variables
SCREEN_SIZE = 128
BKG_COLOUR = (255, 255, 255) # White
def read_input():
"""
Read user input and return state of running the game.
If user press Esc or exit game window stop game main loop.
Returns:
bool: Should game still be running?
"""
# Should we still run game after parsing all inputs?
running = True
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == pygame.KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
running = False
# Did the user click the window close button? If so, stop the loop.
elif event.type == QUIT:
running = False
return running
def main():
"""
This is main function - it will be executed only explicitly, like this:
import main
main.main()
or when executing script from command line:
python3 main.py
"""
global active
# Initialize PyGame library
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([SCREEN_SIZE, SCREEN_SIZE])
while active:
# Read any inputs from keyboard - this function will return False if
# we supposed to stop game (closed window or pressed Esc)
active = read_input()
# If user stopped game do not draw this frame
if not active:
continue
# Fill the background with white
screen.fill(BKG_COLOUR)
# Draw an image
my_img = pygame.image.load('Sprite-0001.png')
screen.blit(my_img, (32, 32))
# Flip the display
pygame.display.flip()
if __name__ == '__main__':
# When executing script from command line start main function
main()
|
bdcf775633ba1fca1265f67a2a46c06a5c316c4a | webclinic017/Financial_Machine_Learning | /build_model/model_insights.py | 1,992 | 3.75 | 4 | """
Name : model_insights.py in Project: Financial_ML
Author : Simon Leiner
Date : 02.09.2021
Description: Get build_model insights by permutation importance
"""
import eli5
from eli5.sklearn import PermutationImportance
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Checked: Function works
def perm_importance(trained_model, X_test,Y_test):
"""
This function shows, what features have the most impact.
:param trained_model: your final trained build_model
:param X_test: pd.DataFrame: Full X testing set
:param Y_test: pd.Series: Fully y testing set
:return: None
Permutation feature importance is a build_model inspection technique that can be used for any fitted estimator
when the data is tabular. This is especially useful for non-linear or opaque estimators. The permutation
feature importance is defined to be the decrease in a build_model score when a single feature value is randomly
shuffled 1. This procedure breaks the relationship between the feature and the target, thus the drop in the
build_model score is indicative of how much the build_model depends on the feature. This technique benefits from being build_model
agnostic and can be calculated many times with different permutations of the feature.
"""
#make use of Permutation
perm = PermutationImportance(trained_model,random_state = 1)
# n_repeats int, default = 10
# fit the build_model
perm.fit(X_test, Y_test)
#get the resulst as a DF: values to the top are the most important features
df_weights = eli5.explain_weights_df(perm)
#adjust feature names
df_weights["feature"] = X_test.columns.tolist()
print("Permutation Importance of the Variables [Test]:")
print(df_weights.head(5))
print("-" * 10)
return None
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
87569c82f01514cf76417def49b6db8a00a9e023 | TechMaster/LearnAI | /LinearRegression/Keras/keras_linear1.py | 679 | 3.75 | 4 | # Theo ví dụ mẫu của https://machinelearningcoban.com/2018/07/06/deeplearning/
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 1. create pseudo data y = 2*x0 + 3*x1 + 4
X = np.random.rand(100, 2)
y = 2 * X[:, 0] + 3 * X[:, 1] + 4 + .2 * np.random.randn(100) # noise added
# 2. Build model
model = keras.Sequential([
layers.Dense(5, activation='linear', input_shape=(2,)),
layers.Dense(1)
])
# 3. gradient descent optimizer and loss function
sgd = tf.keras.optimizers.SGD(lr=0.1)
model.compile(loss='mse', optimizer=sgd)
# 4. Train the model
model.fit(X, y, epochs=100, batch_size=2)
|
499ae05233dee30a4b2dfadd1cdb5ea2842271ea | rlaboulaye/bofinger | /tools/simple-tokenizer.py | 723 | 3.6875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import fileinput
ignorelist = ('!', '-', '_', '(', ')', ',', '.', ':', ';', '"', '\'', '?')
def displayword(w):
if w != "":
print w
# print w.lower()
def handletail(w):
# print w
if(w == ""):
return
if(ignorelist.count(w[len(w)-1]) > 0):
handletail(w[0:len(w)-1])
displayword(w[len(w)-1])
else:
displayword(w[0:len(w)])
def handleword(w):
if(w[0] in ignorelist):
displayword(w[0])
w = w[1:len(w)]
pos = w.find('\'')
if(pos >= 0):
displayword(w[0:pos+1])
w = w[pos+1:len(w)]
handletail(w)
def main():
for line in fileinput.input():
words = line.split()
for w in words:
handleword(w)
if __name__ == "__main__":
main()
# handletail('abc...')
|
13197a4400b41eb7f8cb3a31d0b273b545388c0e | YuanchengWu/coding-practice | /problems/1.1.py | 379 | 3.8125 | 4 | # Is Unique: Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
def isUnique(s):
if len(s) > 128:
return False
seen = [None] * 128
for c in s:
val = ord(c)
if seen[val]:
return False
seen[val] = True
return True
print(isUnique('(#@LIOV'))
|
9846ed7e4675e1d810c0a141f3bf991e4232ba3e | JackKelly1/Rubiks-Cube | /Cubie.py | 2,551 | 3.65625 | 4 | class Cubie():
def __init__(self, x, y, z, lenc, colours):
self.x = x
self.y = y
self.z = z
# length of a cubie side
self.lenc = lenc
self.colours = colours
def show(self):
# sets the color used to draw lines and borders around shapes
stroke(0)
# sets the width of the stroke used for lines, points, and the border around shapes
strokeWeight(8)
# pushes the current transformation matrix onto the matrix stack
pushMatrix()
# specifies an amount to displace objects within the display window
translate(self.x, self.y, self.z)
r = self.lenc/2
# create the 6 sides of a cubie
beginShape(QUADS)
fill(self.colours[0])
vertex(self.lenc/2, self.lenc/2, self.lenc/2)
vertex(self.lenc/2, self.lenc/2, -self.lenc/2)
vertex(self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(self.lenc/2, -self.lenc/2, self.lenc/2)
fill(self.colours[1])
vertex(-self.lenc/2, self.lenc/2, self.lenc/2)
vertex(-self.lenc/2, self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, self.lenc/2)
fill(self.colours[2])
vertex(self.lenc/2, self.lenc/2, self.lenc/2)
vertex(self.lenc/2, self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, self.lenc/2, self.lenc/2)
fill(self.colours[3])
vertex(self.lenc/2, -self.lenc/2, self.lenc/2)
vertex(self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, self.lenc/2)
fill(self.colours[4])
vertex(self.lenc/2, self.lenc/2, self.lenc/2)
vertex(self.lenc/2, -self.lenc/2, self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, self.lenc/2)
vertex(-self.lenc/2 , self.lenc/2, self.lenc/2)
fill(self.colours[5])
vertex(self.lenc/2, self.lenc/2, -self.lenc/2)
vertex(self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, -self.lenc/2, -self.lenc/2)
vertex(-self.lenc/2, self.lenc/2, -self.lenc/2)
# end the creation of the cubie
endShape()
# pops the current transformation matrix off the matrix stack
popMatrix()
|
ba3356c5dca260222cdc7c6d2c6f16c124a3bb1d | xiaohaiguicc/CS5001 | /Course_case/2018_10_30/word_reverse.py | 286 | 3.859375 | 4 | import sys
from stack_linkedlist import Stack
def main():
stack = Stack()
in_string = input("Input a string:\n")
out_string = ""
for c in in_string:
stack.push(c)
while not stack.is_empty():
out_string += stack.pop()
print(out_string)
main() |
0cda415271ae3a8cef1bf338e8b47c52f2fb3157 | jibarra/advent-of-code | /2017/day3/day3.py | 9,851 | 4.25 | 4 | import math
# day3_input = 23
day3_input = 347991
"""
Each new 'square' is an odd number squared. So the first
is 1^2, the next is 3^2, then 5^2, etc.
In these scenarios, the max distance is at the diagonals. The
diagonals are a distance of 1 less than the number squared
for that particular square. The min distance is ceil(odd_square / 2).
The start for each rotation is the max distance - 1.
"""
def part1(target_space):
odd_square = int(math.ceil(math.sqrt(target_space)))
if odd_square % 2 is 0:
odd_square += 1
max_distance = odd_square - 1
min_distance = math.ceil(odd_square / 2) - 1
current_distance = max_distance
current_pos = ((odd_square - 2) * (odd_square - 2)) + 1
is_positive_direction = False
while current_pos <= target_space:
if is_positive_direction:
current_distance += 1
if current_distance == max_distance:
is_positive_direction = False
else:
current_distance -= 1
if current_distance == min_distance:
is_positive_direction = True
current_pos += 1
print(current_distance)
"""
Differences between diagonals (5, 3):
right side:
beginning square: 16
in between: 17
diagonal: 18
diagonals:
18
20
22
24
With 16?
"""
def determine_diagonal(current_square, current_space, spaces, difference_square):
previous_square = current_square - 2
difference = difference_square
beginning_space = previous_square * previous_square + 1
top_right_space = beginning_space + previous_square
top_left_space = top_right_space + previous_square + 1
bottom_left_space = top_left_space + previous_square + 1
bottom_right_space = bottom_left_space + previous_square + 1
# First space of square
if beginning_space == current_space:
index = current_space - difference
return spaces[index] + spaces[current_space - 2]
# Second space of square
elif beginning_space + 1 == current_space:
index = current_space - difference - 1
return spaces[index] + spaces[index + 1] + spaces[current_space - 2] + spaces[current_space - 3]
# Space before top right corner of square
elif top_right_space - 1 == current_space:
index = current_space - difference - 1
return spaces[index] + spaces[index - 1] + spaces[current_space - 2]
# Top right corner of square
elif top_right_space == current_space:
index = current_space - difference - 2
return spaces[index] + spaces[current_space - 2]
# Space after top right corner of square
elif top_right_space + 1 == current_space:
index = current_space - difference - 3
return spaces[index] + spaces[index + 1] + spaces[current_space - 2] + spaces[current_space - 3]
# Space before top left corner of square
elif top_left_space - 1 == current_space:
index = current_space - difference - 3
return spaces[index] + spaces[index - 1] + spaces[current_space - 2]
# Top left corner of square
elif top_left_space == current_space:
index = current_space - difference - 4
return spaces[index] + spaces[current_space - 2]
# Space after top left corner of square
elif top_left_space + 1 == current_space:
index = current_space - difference - 5
return spaces[index] + spaces[index + 1] + spaces[current_space - 2] + spaces[current_space - 3]
# Space before bottom left corner of square
elif bottom_left_space - 1 == current_space:
index = current_space - difference - 5
return spaces[index] + spaces[index - 1] + spaces[current_space - 2]
# Bottom left corner of square
elif bottom_left_space == current_space:
index = current_space - difference - 6
return spaces[index] + spaces[current_space - 2]
# Space after bottom left corner of square
elif bottom_left_space + 1 == current_space:
index = current_space - difference - 7
return spaces[index] + spaces[index + 1] + spaces[current_space - 2] + spaces[current_space - 3]
# Bottom right corner of square
elif bottom_right_space == current_space:
index = current_space - difference - 8
return spaces[index] + spaces[index + 1] + spaces[current_space - 2]
# Right spaces of square
elif top_right_space > current_space:
index = current_space - difference - 1
return spaces[index - 1] + spaces[index] + spaces[index + 1] + spaces[current_space - 2]
# Top spaces of square
elif top_left_space > current_space:
index = current_space - difference - 3
return spaces[index - 1] + spaces[index] + spaces[index + 1] + spaces[current_space - 2]
# Left spaces of square
elif bottom_left_space > current_space:
index = current_space - difference - 5
return spaces[index - 1] + spaces[index] + spaces[index + 1] + spaces[current_space - 2]
# Bottom spaces of square
elif bottom_right_space > current_space:
index = current_space - difference - 7
return spaces[index - 1] + spaces[index] + spaces[index + 1] + spaces[current_space - 2]
# difference changes by 8 each time
def test_part2(target_value):
spaces = [1, 1, 2, 4, 5, 10, 11, 23, 25, 26, 54]
current_square = 5
current_space = 12
difference_square = 9
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
current_square += 2
difference_square = 17
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
# current_square += 2
# difference_square = 16
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
spaces.append(determine_diagonal(current_square, current_space, spaces, difference_square))
current_space += 1
print(spaces)
"""
Max spaces to add together is 4:
4 - 3 spaces to the right, space before
4 - Space next to diagonal, space before, space 2 before, diagonal of previous square, space before previous square diagonal
3 - Space before diagonal, space before, 2 spaces in previous square
3 - Bottom right diagonal, space before, above, diagonal of previous square
2 - Diagonal of square, space before, diagonal of previous square
2 - Beginning of new square, space before, beginning of last square
"""
def part2(target_value):
spaces = [1, 1, 2, 4, 5, 10, 11, 23, 25]
current_square = 5
current_space = 10
value = 0
difference_square = 9
square_max = current_square * current_square
while value < target_value:
value = determine_diagonal(current_square, current_space, spaces, difference_square)
spaces.append(value)
current_space += 1
if current_space > square_max:
current_square += 2
difference_square += 8
square_max = current_square * current_square
print(value)
part1(day3_input)
# test_part2(day3_input)
part2(day3_input)
|
498fcb32cbd75682e4b94ab6dde60d19f7a81c04 | pragmatizt/Intro-Python-I | /src/05_lists.py | 1,311 | 4.6875 | 5 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
"""this is a good link for some list methods: https://lucidar.me/en/python/insert-append-extend-concatanate-lists/"""
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.insert(3, 4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
"""It becomes a list within a list, so that's not right"""
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
"""Removing element from lists: https://note.nkmk.me/en/python-list-clear-pop-remove-del/"""
x.pop(4)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
"""Inserting elements in python lists: https://developers.google.com/edu/python/lists"""
x.insert(5,99)
print(x)
# Print the length of list x
# YOUR CODE HERE
print(len(x))
# Print all the values in x multiplied by 1000
"""multiplying elements in a list by a number: https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number/35166717"""
"""Does this solution count?"""
product = []
for i in x:
product.append(i*1000)
print(product)
# Asked someone else how they did it, this was their code:
print([i * 1000 for i in x]) |
0c9fc9ac2724fa7b8d51392018e7a15ffd028c1b | deppwater/- | /17_二叉树的先序遍历中序遍历和后序遍历的递归实现.py | 2,864 | 4.09375 | 4 | """
三种遍历顺序的说明:
假设有一颗数的节点为1-7 即为一个三层的满二叉树
如果不考虑打印 那么递归函数来到树上节点的顺序为(当当前节点继续往下的时遇到空还会再走一遍当前节点):
1、2、4、4(左空)、4(右空)、2、5、5、5、2、1、3、6、6、6、3、7、7、7、3、1
如果把打印时机放在第一次来到这个节点的时候为先序遍历 第二次为中序遍历 第三次为后序遍历
先序遍历:1、2、4、5、3、6、7
中序遍历:4、2、5、1、6、3、7
后序遍历:4、5、2、6、7、3、1
"""
class Node(object):
def __init__(self, item):
self.elem = item
self.lChild = None
self.rChild = None
class Tree(object):
def __init__(self):
self.root = None
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.lChild is None:
cur_node.lChild = node
return
else:
queue.append(cur_node.lChild)
if cur_node.rChild is None:
cur_node.rChild = node
return
else:
queue.append(cur_node.rChild)
def preOrderRecur(self, tree): # 前序遍历
if tree is None: # 从根节点寻找,当树不是空时
return
print(tree.elem) # 打印根
self.preOrderRecur(tree.lChild) # 打印左子树
self.preOrderRecur(tree.rChild) # 打印右子树
def inOrderRecur(self, tree): # 中序遍历
if tree is None: # 从根节点寻找,当树不是空时
return
self.inOrderRecur(tree.lChild) # 打印左子树
print(tree.elem) # 打印根
self.inOrderRecur(tree.rChild) # 打印右子树
def posOrderRecur(self, tree): # 后序遍历
if tree is None: # 从根节点寻找,当树不是空时
return
self.posOrderRecur(tree.lChild) # 打印左子树
self.posOrderRecur(tree.rChild) # 打印右子树
print(tree.elem) # 打印根
# def preOrderRecur(nobe_head):
# print(nobe_head.elem)
# if nobe_head.lChild is None:
# return
# preOrderRecur(nobe_head.lChild)
# if nobe_head.rChild is None:
# return
# preOrderRecur(nobe_head.rChild)
if __name__ == '__main__':
tree = Tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.preOrderRecur(tree.root)
print('=' * 30)
tree.inOrderRecur(tree.root)
print('=' * 30)
tree.posOrderRecur(tree.root) |
483c69aa28ee6ebcb482ad2e1ecda34c2e50c785 | AlexandruBurlacu/bv-algorithm | /tests/test_space_tagger.py | 1,094 | 3.5 | 4 | import unittest
from src import space_tagger
class TestSpaceTagger(unittest.TestCase):
def test_space_tagger_match(self):
space_dict = {
"Terra Obscura": "earth",
"Vulcan": "other planets",
"Counter-Earth": "other planets",
"Phaëton": "other planets",
"Earth": "earth"
}
ts = "Earth and Vulcan are very related planets"
self.assertEqual([space_tagger(t, space_dict) for t in ts.split()],
[("earth", "Earth"), None, ("other planets", "Vulcan"),
None, None, None, None])
def test_space_tagger_no_match(self):
space_dict = {
"Terra Obscura": "earth",
"Vulcan": "other planets",
"Counter-Earth": "other planets",
"Phaëton": "other planets",
"Earth": "earth"
}
ts = "Joe and Valerian are such an assholes"
self.assertEqual([space_tagger(t, space_dict) for t in ts.split()],
[None, None, None, None, None, None, None])
|
2d5e792e0b1876d607476ef77ba6bef719ee5af2 | poorvavm/practice-fun | /funNLearn/src/main/java/leetcode/algorithms/P101_P200/P200_NumberOfIslands.py | 1,671 | 3.75 | 4 | """
Tag: dfs, matrix
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid
are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
"""
class P200_NumberOfIslands:
def numIslands(self, grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '#'
self.dfs(grid, i+1, j)
self.dfs(grid, i-1, j)
self.dfs(grid, i, j+1)
self.dfs(grid, i, j-1)
def test_code():
obj = P200_NumberOfIslands()
island = [[] for _ in range (4)]
island[0]=['1', '1', '1', '1', '0']
island[1]=['1', '1', '0', '1', '0']
island[2]=['1', '1', '0', '0', '0']
island[3]=['0', '0', '0', '0', '0']
assert obj.numIslands(island) == 1
m_island = [[] for _ in range (4)]
m_island[0]=['1', '1', '0', '0', '0']
m_island[1]=['1', '1', '0', '0', '0']
m_island[2]=['0', '0', '1', '0', '0']
m_island[3]=['0', '0', '0', '1', '1']
assert obj.numIslands(m_island) == 3
print "Tests Passed!"
test_code() |
37eda9fedc8620023dbaf7e2c2e60dee040a0cb0 | mesapejarvis/pdsnd_github | /bikeshare.py | 7,248 | 4.09375 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
while True:
city = input('Enter name of city you would like to explore. chicago, new york city, or washington? ').lower()
if city in ['chicago', 'new york city', 'washington']:
break
else:
print('That is not a valid city, please enter one of the three cities.')
while True:
month = input('Enter the month you would like to explore or all: ').lower()
if month in ['january', 'february', 'march', 'april', 'may', 'june', 'all']:
break
else: print('Sorry, that is not a valid entry.')
while True:
day = input('Enter the day of the week you would like to explore or all: ').lower()
if day in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']:
break
else: print('Sorry, that is not a valid entry.')
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
if month != 'all':
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'all':
df = df[df['day'] == day.title()]
return df
def time_stats(df):
"""
Loads a dataframe(file) based on the city prints out the stats about the travels.
Args:
(object) df - a dataframe
"""
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
month = df['month'].value_counts().idxmax()
print( "The most common month of travel is : {}".format(month))
day = df['day'].value_counts().idxmax()
print("The most common day of the week is : {}".format(day))
hour = df['hour'].value_counts().idxmax()
print("The most common start hour is : {}".format(hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""
Loads a dataframe(file) based on the city prints out the stats about the stations.
Args:
(object) df - a dataframe
"""
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
start_station = df['Start Station'].mode()[0]
print( "The most commonly used start station is : {}".format(start_station))
end_station = df['End Station'].mode()[0]
print( "The most commonly used end station is : {}".format(end_station))
frequent_combination = start_station + ' to ' + end_station
frequent_combination_back = start_station + ' and back to ' + end_station
if start_station == end_station :
print( "The most frequent combination of start station and end station trip is taken from : {}".format(frequent_combination_back))
else :
print( "The most frequent combination of start station and end station trip is taken from : {}".format(frequent_combination))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""
Loads a dataframe(file) based on the city prints out the stats about the trip duration.
Args:
(object) df - a dataframe
"""
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
total_travel_time = df['Trip Duration'].sum()
print( "The total travel time is : {} seconds".format(total_travel_time))
mean_travel_time = df['Trip Duration'].mean()
print( "The mean travel time is : {} seconds".format(mean_travel_time))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""
Loads a dataframe(file) based on the city prints out the stats about the user.
Args:
(object) df - a dataframe
"""
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
user_type_count = df['User Type'].value_counts()
print( "The user types count is : \n {}".format(user_type_count))
gender = "Gender"
birth = "Birth Year"
if gender in df.columns and birth in df.columns:
gender_count = df['Gender'].value_counts()
print( "The gender count is : \n {}".format(gender_count))
earliest_year = df['Birth Year'].min()
most_recent_year = df['Birth Year'].max()
most_common_year = df['Birth Year'].mode()[0]
print( "The earliest year of birth is : {:.0f}".format(earliest_year))
print( "The recent year of birth is : {:.0f}".format(most_recent_year))
else :
print("The summary stats (Gender and Birth Year) are not avalibale for this city!!!")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
# added this section as per previous feedback!
def display_data(df):
"""
Loads a dataframe(file) based on the city prints out the stats about the data with 5 records.
Args:
(object) df - a dataframe
"""
count = 0
user_input = input('\nDo you want to see 5 lines of raw data? Enter yes or no.\n').lower()
while True :
if user_input == 'yes':
print(df.iloc[count : count + 5])
count += 5
user_input = input('\nDo you want to see more raw data? Enter yes or no.\n')
else:
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
6e069f8a3bf94906263dc9b7a776f2766bab8cce | iTenki/Python-Crash-Course | /Chapter 1~11 Python 基础知识/alien.py | 1,489 | 3.75 | 4 | #简单的字典 使用字典 访问字典中的值
alien_0 = {'color': 'green', 'points': 5 }
print(alien_0['color'])
print(alien_0['points'])
new_point = alien_0['points']
print("You just earned " + str(new_point) + " points!")
#字典添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#字典不关心键-值的顺序,只关心键-值的关系。
#分行对字典添加键-值
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
#修改字典键-值
alien_0 = {'color' : 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is " + alien_0['color'] + ".")
alien_0 = {'x_position' : 0,'y_position' : 25,'speed' : 'meidum' }
print("Original x_position: " + str(alien_0['x_position']))
#向右移动外星人
#据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] =='meidum':
x_increment = 2
else:
#这个外星人的速度一定很快
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x_position: " + str(alien_0['x_position']))
#删除字典键-值
alien_0 = {'color': 'green' , 'points' : 5}
print(alien_0)
del alien_0['points']
print(alien_0)
#由类似对象组成的字典
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python'
}
print("Sarah's favorite languages is " +
favorite_languages['sarah'].title() +
".")
|
fef1b9b939586d8116466664acb4cc401a865158 | Hutchby/chess | /src/game.py | 2,465 | 3.5625 | 4 | # TODO: modify h_turn in order not to let player move if it's not a correct move
# TODO: allow h_player to be player 1 & c_player to be player -1
# from src.gui import *
from src.ai import *
from src.pieces import *
player = -1
players = {}
ia_type = "viral"
difficulty = 3
def select_game_type():
global players
game_type = 1
if game_type != -1:
print("There is a shortcut for the test, game_type = ", game_type)
while game_type < 0 or 2 < game_type:
game_type = input("""What kind of game? (H:human, C: computer)
# HvC: 0
HvH: 1
CvC: 2
your choice: """)
players[-1] = "h"
players[1] = "h"
if game_type == 0:
players[random.choice([-1, 1])] = "c"
if game_type == 2:
players[-1] = "c"
players[1] = "c"
def turn(coordfrom=(), coordto=()):
global dict_pieces, players, player, ia_type, difficulty
print("start turn player : ", player)
if coordfrom != () and coordto != ():
if h_turn(coordfrom, coordto):
dict_pieces[coordto].has_moved = True
print(dict_pieces[coordto].has_move, " ", dict_pieces[coordto].symbol )
player *= -1
#while players[player] == 'c':
# disable input
# c_turn(ia_type, difficulty)
# refresh_board()
# enable input
# no longer used
def move_input():
print("move (x1,y1) to (x2,y2):")
x1 = int(input("x1: "))
y1 = int(input("y1: "))
x2 = int(input("x2: "))
y2 = int(input("y2: "))
return (x1, y1), (x2, y2)
def h_turn(coordfrom, coordto):
global player, dict_pieces
move = (coordfrom, coordto)
print("Turn: Player ", player)
if dict_pieces[move[0]].player == player:
if move[1] in dict_pieces[move[0]].list_move(move[0], dict_pieces):
dict_pieces[move[1]] = dict_pieces.pop(move[0])
if is_check(dict_pieces, player) == -player:
print("Joueur ", -player, " en echec ! ")
dict_pieces[move[1]].has_move = True
return True
return False
else:
print("Pas votre pièce")
return False
def c_turn(ia_type, difficulty):
global player, dict_pieces
print("Turn: Computer ", player)
# calcule le coup a faire
move = main_ia(player, dict_pieces, ia_type, difficulty)
dict_pieces[move[1]] = dict_pieces.pop(move[0])
dict_pieces[move[1]].has_moved = True
return False
|
8cf7e3c243906a556c7b364ae8929db16f807e4b | pyziko/python_basics | /oop/private and Public.py | 442 | 3.90625 | 4 | class Player:
def __init__(self, name, age):
self._name = name
self._age = age
def run(self):
print('run')
def speak(self):
print(f"my name is {self._name}, and I am {self._age} years old")
player1 = Player("Ezekiel", 100)
# there's really no privacy in python we can still override it ::: see below
# but for convention sake, we still use underscore
player1.speak = 500
print(player1.speak)
|
c53a874aed800389ef4a7d34eca70ca0fe5f7cbe | gh4683/PythonWorkshop | /ListsTuplesDicts.py | 484 | 4.15625 | 4 | #List Ex: A list of the breakfast items in your kitchen
breakfast = ['Cereal', 'Milk', 'Eggs', 'Waffles', 'Coffee']
print(breakfast)
print(breakfast[3])
#Tuples Ex: Months in the year
months = ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
print(months)
#Dictionaries Ex: Save phone numbers
Contacts = {'Nidhi':5551234, 'Saloni':2486957, 'Hafsa':7348325}
print(Contacts)
Contacts["Tia"] = 3132001 #Adds another key
print(Contacts) |
7e367d81835a5feaaa895a58a905fb806bffa107 | YMSPython/Degiskenler | /Lesson1/OperatorlerOrnekler.py | 1,726 | 3.8125 | 4 | # Örnek 1) Disaridan alinan
# iki sayının toplamiyla farkinin birbirine bolumunden kalanin sonucu kactir?
sayi1 = int(input("Lütfen birinci sayiyi giriniz : "))
sayi2 = int(input("Lütfen ikinci sayiyi giriniz : "))
toplam = sayi1 + sayi2
fark = sayi1 - sayi2
mod = toplam % fark
print("Islem sonucu :", mod)
# Örnek 2) Disaridan girilen bir sayının 10 eksiginin 20 fazlasinin
# 2ye bolumunden kalaninin karesi kactir?
sayi3 = int(input("Lütfen bir sayi giriniz :"))
sonuc = ((sayi3 - 10 + 20) % 2 ) ** 2
print(sonuc)
# Örnek 3) Disaridan girilen iki sayının karelerinin toplami
# ile karelerinin farki toplami kactir?
sayi4 = int(input("Lütfen birinci sayiyi giriniz :"))
sayi5 = int(input("Lütfen ikinci sayiyi giriniz : "))
kare1 = sayi4 * sayi4
kare2 = sayi5 * sayi5
kare3 = sayi4 **2
kare4 = sayi5 **2
toplam = kare1 + kare2
fark = kare1 - kare2
sonuc = toplam + fark
print("islem sonucu :", sonuc)
# Örnek 4) Vize notu'nun % 30'u, final notu'nun % 70'ini alıp öğrencinin not ortalamasini
#cikartan bir uygulama yaziniz...
final = float(input("Lütfen Final Notunuzu Giriniz : "))
vize = float(input("Lütfen Vize Notunuzu Giriniz : "))
not_ortalamasi = (vize * 0.30) + (final * 0.70)
print("Not ortalamanız :", not_ortalamasi)
# Örnek 5) Kullanıcı ilk Adını, 2. Olarak Soyadını girsin ve kullanıcıya mesaj olarak
# [email protected]
ondalikli_sayi = 14.1111111111
print(round(ondalikli_sayi,7)) # virgulden sonraki haneyi belirlemek için kullaniriz.
isim = input("Lütfen adınız giriniz : ")
soyisim = input("Lütfen soyadınız giriniz : ")
mail = isim + "."+ soyisim+"@hotmail.com"
print(mail)
# [email protected]
|
e7deb4de032c109bfc552e93888ce0e74da6147d | jke-zq/my_lintcode | /Tweaked Identical Binary Tree.py | 779 | 4 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
# Write your code here
def helper(nodea, nodeb):
if not nodea and not nodeb:
return True
if nodea and nodeb and nodea.val == nodeb.val:
return (helper(nodea.left, nodeb.right) and helper(nodea.right, nodeb.left)) or (helper(nodea.left, nodeb.left) and helper(nodea.right, nodeb.right))
else:
return False
return helper(a, b) |
e69ba129d1d7f449f5544ec5e1cf89c75ce644c0 | mkuehn10/Intro-to-Interactive-Programming-in-Python | /01+_RPSLS.py | 3,220 | 4.3125 | 4 | # GUI-based version of RPSLS
###################################################
# Student should add code where relevant to the following.
import simplegui
import random
#global variables
player_wins = 0
computer_wins = 0
ties = 0
#helper functions
def init():
global player_wins, computer_wins, ties
player_wins = 0
computer_wins = 0
ties = 0
print "New game started!"
print_game_status()
def print_game_status():
print "Player: " + str(player_wins) + " Computer: " + str(computer_wins) + " Ties: " + str(ties) + "\n"
def number_to_name(number):
# fill in your code below
# convert number to a name using if/elif/else
# don't forget to return the result!
if number == 0:
return 'rock'
elif number == 1:
return 'Spock'
elif number == 2:
return 'paper'
elif number == 3:
return 'lizard'
elif number == 4:
return 'scissors'
else:
return None
def name_to_number(name):
# fill in your code below
# convert name to number using if/elif/else
# don't forget to return the result!
if name == 'rock':
return 0
elif name == 'Spock':
return 1
elif name == 'paper':
return 2
elif name == 'lizard':
return 3
elif name== 'scissors':
return 4
else:
return None
def rpsls(name):
# fill in your code below
# convert name to player_number using name_to_number
player_number = name_to_number(name)
player_string = "Player chooses " + number_to_name(player_number)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0,5)
# compute difference of player_number and comp_number modulo five
difference = (player_number - comp_number) % 5
# use if/elif/else to determine winner
if difference == 1 or difference == 2:
result_string = "Player wins!"
global player_wins
player_wins += 1
elif difference == 3 or difference == 4:
result_string = "Computer wins!"
global computer_wins
computer_wins += 1
else:
result_string = "Player and computer tie!"
global ties
ties += 1
# convert comp_number to name using number_to_name
comp_string = "Computer chooses " + number_to_name(comp_number)
# print results
print player_string
print comp_string
print result_string + "\n"
print_game_status()
#event handlers
def rock_handler():
rpsls("rock")
def paper_handler():
rpsls("paper")
def scissors_handler():
rpsls("scissors")
def lizard_handler():
rpsls("lizard")
def spock_handler():
rpsls("Spock")
def reset_handler():
init()
# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("GUI-based RPSLS", 300, 300)
frame.add_button("Rock",rock_handler,100)
frame.add_button("Paper",paper_handler,100)
frame.add_button("Scissors",scissors_handler,100)
frame.add_button("Lizard",lizard_handler,100)
frame.add_button("Spock",spock_handler,100)
frame.add_button("Reset Game",reset_handler,100)
# Start the frame animation
frame.start()
init()
|
923a350a9e6d9dbe0d51897501610c21904b9c37 | vitaliksokil/pythonlabs | /lab9/lab91.py | 4,218 | 3.59375 | 4 | import random
def blackjack(num_of_players):
if num_of_players > 4 or num_of_players < 2:
exit('Maximum of players is 4 and minimum is 2')
blackjack_dictionary = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 10,
'Q': 10,
'K': 10,
'A': [11, 1]
}
# creating deck of cards
cards = []
for key in blackjack_dictionary:
cards += [key] * 4
# shuffle cards
random.shuffle(cards)
# creating players
players = {}
for i in range(0, num_of_players):
# player = [] - array with cards he or she has
players['Player ' + str(i + 1)] = []
# starting game
game = True
stoped_players = 0
num_of_stoped_players = [] # players whose said stop -> have no chance to take one more card
isWinner = False
sums = {} # sums of players' cards
while game:
for player in list(players):
if player in num_of_stoped_players:
continue
player_cards = players[player]
print(player, ' : ')
choice = input('1. One more card\n2. Skip\n3. Stop\n')
if choice == '1':
# adding card to player cards
player_cards += cards.pop()
# counting sum of cards if it's less then 21
player_cards_sum = 0
for card in player_cards:
# if card is A
if isinstance(blackjack_dictionary[card], list):
# taking first grater value
player_cards_sum += blackjack_dictionary[card][0]
# if it's sum > 21 then remove this value(11) from sum and add less one (1)
if player_cards_sum > 21:
player_cards_sum -= blackjack_dictionary[card][0]
player_cards_sum += blackjack_dictionary[card][1]
# if anyway sum is grater then 21 , so player lost
if player_cards_sum > 21:
print(player_cards)
print(player, 'Bust!!!')
players.pop(player)
if player_cards_sum == 21:
print(player_cards)
print(player, 'WINS!!!')
isWinner = True
game = False
break
else:
player_cards_sum += blackjack_dictionary[card]
if player_cards_sum > 21:
print(player_cards)
print(player, 'Bust!!!')
players.pop(player)
elif player_cards_sum == 21:
print(player_cards)
print(player, 'WINS!!!')
isWinner = True
game = False
break
sums[player] = player_cards_sum
elif choice == '2':
pass
elif choice == '3':
stoped_players += 1
num_of_stoped_players.append(player)
else:
pass
# if everyone said stop -> game will end
if stoped_players == num_of_players:
game = False
if len(players) == 1:
print(players[next(iter(players))])
print(next(iter(players)), 'WINS!!!')
isWinner = True
game = False
break
print(players)
if not isWinner:
winner = next(iter(sums))
biggest_sum = sums[next(iter(sums))]
for player in sums:
if sums[player] > biggest_sum:
biggest_sum = sums[player]
winner = player
print('Score', biggest_sum)
print('Winner', winner)
number_of_players = int(input('Enter number of players(max:4): '))
blackjack(number_of_players)
|
9788d401a09a2e32c73641eed8883b25adf1f596 | twitu/bot_programming | /state_manager.py | 1,402 | 3.71875 | 4 | class StateManager:
""" State Management Module """
def __init__(self, unit_id, state_id=None):
"""
Initializes the State Manager with the unit type and initial state
Args:
unit_id: Unit Type of AI
state_id: Starting state (optional)
"""
if state_id is None:
self.state_id = unit_id
else:
self.state_id = state_id
self.unit_id = unit_id
def advance(self, *args):
"""
Perform the current state action and update next state
Args:
*args: any and all external arguments necessary. Avoid usage if possible.
Use local variables instead.
Return:
Current state output. Also updates the next state.
"""
self.state_id, output = self.state_table[self.state_id](self, *args)
return output
# Test states
def tank_attack(self, danger=False):
if danger:
return 'G1', 'aaaaa!'
else:
return 'T0', "BOOM"
def rifleman_attack(self, danger=False):
if danger:
return 'G1', 'aaaaa!'
else:
return 'R0', "boom"
def run(self):
return 'G1', "aaaaa!"
# Dictionary of all states
state_table = {'T0': tank_attack,
'R0': rifleman_attack,
'G1': run}
|
af7044d66ea51fd8f39e168fee7864cb5c13546c | Dzhevizov/SoftUni-Python-Fundamentals-course | /Functions - More Exercises/02. Center Point.py | 416 | 4.03125 | 4 | import math
def find_closest_point(x1, y1, x2, y2):
distance1 = (x1 ** 2 + y1 ** 2) ** 0.5
distance2 = (x2 ** 2 + y2 ** 2) ** 0.5
if distance1 <= distance2:
return f'({math.floor(x1)}, {math.floor(y1)})'
else:
return f'({math.floor(x2)}, {math.floor(y2)})'
X1 = float(input())
Y1 = float(input())
X2 = float(input())
Y2 = float(input())
print(find_closest_point(X1, Y1, X2, Y2))
|
399ddf157e0dd11a540b76bd624b7d0230f342c0 | jainjayesh24/Ch-9-Flow-of-Control | /p.9.py | 315 | 4.375 | 4 | char=input("Enter your character: ")
if char>="A" and char<="Z":
print("Your character is an Uppercase")
elif char>="a" and char<="z":
print("Your character is an Lowercase")
elif char>="0" and char<="9":
print("Your character is a digit")
else:
print("You have entered special Character")
|
8cec860a090b6d0945baafc30a35be4b4d98bf7c | ssooda/pajang | /ksy/300제/2ndWeek4.py | 4,938 | 3.703125 | 4 | #241
import datetime
print(datetime.datetime.now())
#datetime모듈의 datetime객체??의 now함수
#242
now = datetime.datetime.now()
print(type(now))
#243
now = datetime.datetime.now()
for i in range(5,0,-1) :
print(now - datetime.timedelta(days=i))
#244
now = datetime.datetime.now()
print(now.strftime("%H:%M:%S"))
#245
print(datetime.datetime.strptime("2020-05-04", "%Y-%m-%d" ))
#246
import time
import datetime
#while True :
# now = datetime.datetime.now()
# print(now)
# time.sleep(1)
#247
# import datetime
# from datetime import *
# from datetime import datetime
# import datetime as dt
#248
import os
print(os.getcwd())
#249
#250
# import numpy as np #왜 import가 안 될까
# for i in np.arange(0.0, 5.0, 0.1) :
# print(i)
#251
#252
class Human :
pass
#253
areum = Human() #바인딩
#254
class Human :
def __init__(self):
print("응애응애")
areum = Human()
#255
class Human :
def __init__(self, name, age, gender) :
self.name = name
self.age = age
self.gender = gender
areum = Human("아름" ,25, "여자")
print(areum.name)
#256
print(areum.age)
print(areum.gender)
#257
class Human :
def __init__(self, name, age, gender) :
self.name = name
self.age = age
self.gender = gender
def who(self) :
print("이름 : {} , 나이 : {} , 성별 : {}" .format(self.name, self.age, self.gender))
areum = Human("조아름", 25, "여자")
areum.who()
#258 ==> 블로그로 옮기기
class Human :
def __init__(self, name, age, gender) :
self.name = name
self.age = age
self.gender = gender
def who(self) :
print("이름 : {} , 나이 : {} , 성별 : {}" .format(self.name, self.age, self.gender))
def setInfo(self, name, age, gender) :
self.name = name
self.age = age
self.gender = gender
areum = Human("모름", 0, "모름")
print(areum.name)
areum.setInfo("아름", 25, "여자")
print(areum.name)
#259
class Human:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def __del__(self):
print("나의 죽음을 알리지마라")
def who(self):
print("이름: {} 나이: {} 성별: {}".format(self.name, self.age, self.sex))
def setInfo(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
areum = Human("아름", 25, "여자")
del(areum)
#261
class Stock :
pass
#262
class Stock :
def __init__(self, name, code) :
self.name = name
self.code = code
#263
class Stock :
def __init__(self, name, code) :
self.name = name
self.code = code
def set_name(self, name) :
self.name = name
a = Stock(None, None)
a.set_name("삼성전자")
print(a.name)
#264
class Stock :
def __init__(self, name, code) :
self.name = name
self.code = code
def set_name(self, name) :
self.name = name
def set_code(self, code) :
self.code = code
a = Stock(None, None)
a.set_code("005930")
#265
class Stock :
def __init__(self, name, code) :
self.name = name
self.code = code
def set_name(self, name) :
self.name = name
def set_code(self, code) :
self.code = code
def get_name(self) :
return self.name
def get_code(self) :
return self.code
삼성 = Stock("삼성전자", "005930")
print(삼성.get_name())
print(삼성.get_code())
#266
class Stock :
def __init__(self, name, code, PER, PBR, rate) :
self.name = name
self.code = code
self.PER = PER
self.PBR = PBR
self.rate = rate
def set_name(self, name) :
self.name = name
def set_code(self, code) :
self.code = code
def get_name(self) :
return self.name
def get_code(self) :
return self.code
#267
삼성전자 = Stock("삼성전자", "005930",15.79, 1.33, 2.83)
#268
class Stock :
def __init__(self, name, code, per, pbr, devidend) :
self.name = name
self.code = code
self.per = per
self.pbr = pbr
self.devidend = devidend
def set_name(self, name) :
self.name = name
def set_code(self, code) :
self.code = code
def set_per(self, per) :
self.per = per
def set_pbr(self,pbr) :
self.pbr = pbr
def set_dividend(self,devidend) :
self.devidend = devidend
def get_name(self) :
return self.name
def get_code(self) :
return self.code
#269
삼성전자 = Stock("삼성전자", "005930",15.79, 1.33, 2.83)
삼성전자.set_per(12.75)
print(삼성전자.per)
#270
현대차 = Stock("현대차", "005380", 8.70, 0.35, 4.27)
LG전자 = Stock("LG전자", "066570", 317.34, 0.69, 1.37)
stock_list = [삼성전자, 현대차, LG전자]
for i in stock_list :
print(i.code, i.per)
|
ab5ff80cd41fadc1e85636a9a3bd3ac44ec8e553 | VieVie31/bonapity | /examples/simplest.py | 2,392 | 3.78125 | 4 | from bonapity import bonapity
@bonapity
def add(a: int, b: int = 0) -> int:
""" Add `a` with `b` if `b` is provided, otherwise returns `a` only.
Example:
------------------
>>> add(4, 5)
9
"""
return a + b
@bonapity
def concatenate(s1: str, s2: str) -> str:
""" Return the concatenation of `s1` with `s2`. """
return s1 + s2
# Note that the decorator can be used to change the name of the served API.
@bonapity("hello")
def g():
""" This function returns a fixed string. """
return "Like we say in french : 'Bon Appétit !'"
# Without decorator this function is _private_ (not accessible via the API).
def function_wo_api():
return 23
@bonapity(timeout=6)
def wait(s: int=1) -> int:
"""
The purpose of this function is only to show that
the miltithreading is supported by your API server ! :D
Go to your terminal and write:
```bash
for i in 1 2 3 4 5;
do
curl "http://localhost:8888/wait?s=5" &
done
```
All the 5 should be printed at the same time just after 5 seconds
and not one after the other which would take instead : 5s * 5s = 25s
before printing the last one.
:param s: the number of seconds before returning its value `s`
:return: `s` the number of seconds asked to wait
"""
import time
time.sleep(s)
return s
if __name__ == "__main__":
port = 8888
print(f"""
★ Bravo ! Bravissimo ! Your first API is running ! ★
----------------------------------------------------
- list functions : http://localhost:{port}/help/
- display the hello world message : http://localhost:{port}/hello
- test the `add` function : http://localhost:{port}/add?a=1&b=3
- look at the doc of the `add` function : http://localhost:{port}/help/add
- try the `concatenate` function : http://localhost:{port}/concatenate?s1=3&s2=4
- test the `wait` function : http://localhost:{port}/wait?s=4
* Try to give only the `a` parameter (`b` is default)
then only `b` then an extra parameter
* Try to give non `int` parameters
* Try ti delete the specific `timeout` parameter in the wait function
* Hack this file :)
Cool ! You did it ! Now read the doc and enjoy ! :)
""")
bonapity.serve(port=port, timeout=10) #by default, every function will stop after 10s execution completed or not
|
3d71406fa45c294b773acd9761a8b261045cc5af | IgorEM/Estudos-Sobre-Python | /variaveis.py | 254 | 3.53125 | 4 | # -*- coding: utf-8 -*-
var1 = 1 #variavel inteira
var2 = 1.1 #variavel float
var3 = "Eu sou uma string" #variável string
var4 = True #variavel boleana, True-False.
var5 = False
print(var1)
print(var2)
print(var3)
print(var4)
print(var5)
|
d8c0ef258b53c53db625a4499bdf1549fb7dd461 | BinDannyMa/chem991e | /02_introduction_to_python_part_ii/class_assignment_solution.py | 151 | 3.765625 | 4 | nums = input("Enter your list: ")
smallest = 10000000000
for n in nums.split(","):
if int(n) < smallest:
smallest = int(n)
print(smallest)
|
1e60fd9b8f70e47b6c41de92e44d57d71cf79dc1 | AgileMathew/AnandPython | /Module II/pgm35.py | 526 | 3.75 | 4 | """Problem 35: Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?"""
def word_frequency(words):
frequency={}
for w in words:
frequency[w]=frequency.get(w, 0)+1
return frequency
def main(filename):
frequency = word_frequency(read_words(filename))
for word, count in frequency.items():
print word, count
if __name__ == "__main__":
import sys
main(sys.argv[1])
|
129ae1bf16926ddf4c4657500731dac25afdb5e5 | Mega-Barrel/Quiz-Game | /questions/Geography_question.py | 466 | 3.8125 | 4 | def geography_question():
question = []
question.append(['Which continent is the largest?', 'Asia'])
question.append(['Which of the Seven Wonders is located in Egypt?', 'Pyramid of Giza'])
question.append(['What is the capital of New Zealand?', 'Wellington'])
question.append(['Which desert is the largest in the world?', 'Sahara Desert'])
question.append(['Which city in India would you find the Taj Mahal in?', 'Agra'])
return question |
007645adf46f0a3b5ca6aa35c08125377f438857 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/mini-scripts/python_Cummulative_Sum.txt.py | 86 | 3.546875 | 4 | import numpy as np
arr = np.array([1, 2, 3])
newarr = np.cumsum(arr)
print(newarr)
|
84fd443b056c3c08ef99a7179b12e7c77a95d02d | Dharadharu/hi | /factors.py | 81 | 3.53125 | 4 | fa=int(input())
for i in range(1,fa+1):
if fa%i==0:
print(i,end=" ")
|
494e5bc7b7a2693005a2691d3e99c618e2652869 | ffadullgu/programaciondecomputadores | /codigo/python3/11_comprenhension.py | 1,217 | 4.125 | 4 | ## El siguiente procedimiento:
#squares = []
#for x in range(10):
#squares.append(x**2)
#print(squares)
## Se puede escribir como:
#squares = list(map(lambda x: x**2, range(10)))
#print(squares)
## O como:
#squares = [x**2 for x in range(10)] # list comprenhension
#print(squares)
## El siguiente procedimiento:
#combinaciones = []
#for x in [1,2,3]:
#for y in [3,1,4]:
#if x != y:
#combinaciones.append((x, y))
#print(combinaciones)
## Se puede escribir utilizando una "list comprenhension":
#combinaciones = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
#print(combinaciones)
# Nested list comprenhensions
matriz = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
# El siguiente código transpone la matriz
transpuesta = [[fila[i] for fila in matriz] for i in range(4)]
print(transpuesta)
# El siguiente código es equivalente:
transpuesta = []
for i in range(4):
transpuesta.append([fila[i] for fila in matriz])
print(transpuesta)
# Y este también:
transpuesta = []
for i in range(4):
fila_transpuesta = []
for fila in matriz:
fila_transpuesta.append(fila[i])
transpuesta.append(fila_transpuesta)
print(transpuesta)
|
6ab9187e927160155db78dd756bebc81f9b7fc6d | PedroOspina17/academy | /Week-0/matrix.py | 12,037 | 3.59375 | 4 |
class Matrix(object):
def __init__(self, data):
self.numRows = len(data)
self.numColumns = len(data[0])
self.data = data
@staticmethod
def convertSetToList(data):
return [list(item) for item in data]
def clone(self):
return Matrix(self.data)
def show(self):
for row in self.data:
rowToShow = ""
for column in row:
rowToShow += "{:>10} ".format(column)
print(rowToShow)
print("")
def add(self, matrixToAdd):
if (isinstance(matrixToAdd,Matrix) == False):
raise Exception("the element to add should be of type 'Matrix' ")
if(self.numRows != matrixToAdd.numRows and self.numColumns != matrixToAdd.numColumns):
raise Exception("the element to add should be {}x{}".format(self.numRows,self.numColumns))
for i,row in enumerate(self.data):
for j,column in enumerate(row):
self.data[i][j] += matrixToAdd.data[i][j]
def scalarMultiplication(self, scalar):
for i,row in enumerate(self.data):
for j,column in enumerate(row):
self.data[i][j] = round(self.data[i][j] * scalar,2)
def multiply(self, matrixToMultiply):
if (isinstance(matrixToMultiply,Matrix) == False):
raise Exception("the element to add should be of type 'Matrix' ")
if(self.numColumns != matrixToMultiply.numRows):
raise Exception("the element to multiply should have {} columns".format(self.numRows))
result = []
calculatedRow = []
for i in range(0,(self.numRows)):
calculatedRow = []
for j in range(0,(matrixToMultiply.numColumns)):
rowSum = 0
for k in range(0,(matrixToMultiply.numRows)):
rowSum += self.data[i][k] * matrixToMultiply.data[k][j]
calculatedRow.append(rowSum)
result.append(calculatedRow)
self.data = result
def transpose(self):
result = []
for j in range(0,(self.numColumns)):
row = []
for i in range(0,(self.numRows)):
row.append(self.data[i][j])
result.append(row)
matrixResult = Matrix(result)
return matrixResult
def determinant(self): # i have to validate nxn
det = 0
if(self.numRows == 2 and self.numColumns == 2):
det = (self.data[0][0] * self.data[1][1]) - (self.data[0][1] * self.data[1][0])
return det
if(self.numRows != self.numColumns):
raise Exception("the matrix needs to be nxn.")
#choose the better row to calculate the determinant, is the one that has max ceros count
cerosCount = [item.count(0) for item in self.data]
# print(cerosCount)
betterRow = max(enumerate(cerosCount),key=lambda p: p[1],default=[0,0]) # ToDo: verify if the matrix doesn't have ceros !
betterRowIndex = betterRow[0]
# print(betterRow)
for j in range(0,(self.numColumns)):
if(self.data[betterRowIndex][j]==0):
continue
cof = self.getCofactorMatrix(betterRowIndex,j)
# print("---")
cofMatrix = Matrix(cof)
# cofMatrix.show()
# print("...")
det += ( Matrix.determinant(cofMatrix) * self.data[betterRowIndex][j]) * (-1 if(j%2 == 0) else 1)
# print(det)
return det
def getCofactorMatrix(self,iToDelete,jToDelete):
return [[ colunm for j,colunm in enumerate(row) if j!=jToDelete] for i,row in enumerate(self.data) if i != iToDelete] #get the cofactor matrix. to do so, we eliminate the row what we have selected to work on and the column that it is being processed
def invert(self):
#validate if the determinant is equals to 0 then the matrix cannot be enverted.
det = self.determinant()
if(det <= 0):
raise Exception("the matrix cannot be inverted.")
adjugate = self.adjugate()
adjugateTransposed = adjugate.transpose()
adjugateTransposed.scalarMultiplication(1/det)
return adjugateTransposed
def adjugate(self):
result = []
for i in range(0,(self.numRows)):
resultRow = []
for j in range(0,(self.numColumns)):
cof = self.getCofactorMatrix(i,j)
cofMatrix = Matrix(cof)
det = cofMatrix.determinant()
sign = 1 if ((i%2==0 and j%2!=0) or (i%2!=0 and j%2==0)) else -1
det = det * sign
resultRow.append(det)
result.append(resultRow)
return Matrix(result)
def getRows(self, desiredRowIndex):
return Matrix.convertSetToList({tuple(item) for i,item in enumerate(self.data) if i in desiredRowIndex})
def getColumns(self, desiredColumnIndex):
temp = self.transpose()
return temp.getRows(desiredColumnIndex)
def getPart(self, rowIndexFrom, rowIndexTo,columnIndexFrom, columnIndexTo):
return [[column for j, column in enumerate(row) if j >= columnIndexFrom and j <= columnIndexTo] for i, row in enumerate(self.data) if (i >= rowIndexFrom and i <= rowIndexTo)]
#########################################################
import pytest
print("---- Addition ----")
matrix = Matrix([[1,2,3],[4,5,6],[7,8,9]])
matrix.show()
matrix2 = Matrix([[1,0,1],[0,2,2],[0,3,0]])
matrix2.show()
matrix.add(matrix2)
matrix.show()
print("---- Multiplication ----")
matrix3 = Matrix([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])
matrix3.show()
matrix4 = Matrix([[1,2,3,1],[4,5,6,1],[7,8,9,1],[10,11,12,1],[13,14,15,1]])
matrix4.show()
matrix3.multiply(matrix4)
matrix3.show()
print("---- Scalar multiplication ----")
matrix2.show()
matrix2.scalarMultiplication(2)
matrix2.show()
print("---- Transpose ----")
matrix4.transpose()
matrix4.show()
print("---- Determinant ----")
print("2x2")
matrix5 = Matrix([[1,-1],[3,-2]])
matrix5.show()
print(matrix5.determinant())
print("3x3")
matrix6 = Matrix([[3,2,-1],[4,0,3],[2,-3,5]])
matrix6.show()
print(matrix6.determinant())
print("4x4")
matrix7 = Matrix([[2,3,3,6],[2,3,6,7],[21,82,0,3],[2,23,1,1]])
matrix7.show()
print(matrix7.determinant())
print("---- adjugate ----")
matrix8 = Matrix([[1,0,0,0],[2,3,0,0],[4,2,1,0],[-2,3,1,1]])
matrix8.show()
matrix8.adjugate().show()
print ("---- inverse ----")
matrix8.invert().show()
print ("---- get specific rows and columns ----")
matrix9 = Matrix([[92,33,34,6],[2,3,6,7],[21,82,0,3],[2,23,1,1],[25,232,21,41],[52,263,18,16],[82,2003,16,1443],[2,203,1,13]])
matrix9.show()
print("getting 2nd 4th 6th and 7th rows")
print(matrix9.getRows([1,3,5,6]))
print("getting 2nd and 3rd column")
print(matrix9.getColumns([1,2]))
print("getting 2nd, 3rd and 4th repeated rows and 1st, 3rd columns")
matrix10 = Matrix([[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6]])
matrix10.show()
print(matrix10.getRows([2,3,4]))
print(matrix10.getColumns([0,1,3]))
print("getting a 10x2 from column 5 part from a 10x10 matrix")
matrix11 = Matrix([[932,353,334,313,66,932,353,334,313,66],[9,3,34,33,6,932,353,3,3,6],[2,3,63,364,363,66,94,3,6,9],[92,33,34,33,6,932,353,334,313,66],[952,353,354,353,652,353,334,313,6,0],[962,363,364,363,66,9,3,3,3,6],[2,3,63,364,363,66,94,3,6,9],[9,36,34,31,6,90,24,4,3,46],[92,350,3504,303,6502,350,3034,3103,60,00],[9621,3631,3641,3631,661,91,31,31,31,61]])
matrix11.show()
Matrix(matrix11.getPart(0,10,4,5)).show()
def test_add():
matrix = Matrix([[1,2,3],[4,5,6],[7,8,9]])
matrix2 = Matrix([[1,1,1],[2,2,2],[3,3,3]])
matrix.add(matrix2)
assert matrix.data == [[2,3,4],[6,7,8],[10,11,12]]
def test_add_type_validation_someType():
with pytest.raises(Exception):
matrix = Matrix([[1,2,3],[4,5,6],[7,8,9]])
matrix.add(5)
def test_add_type_validation_arrayType():
with pytest.raises(Exception):
matrix = Matrix([[1,2,3],[4,5,6],[7,8,9]])
matrix.add([1,1,1])
def test_add_size_validation():
with pytest.raises(Exception):
matrix = Matrix([[1,2,3],[4,5,6],[7,8,9]])
matrix2 = Matrix([[4,5,6],[7,8,9]])
matrix.add(matrix2)
def test_scalarMultiplication():
matrix = Matrix([[1,1,1],[2,2,2],[3,3,3]])
matrix.scalarMultiplication(2)
assert matrix.data == [[2,2,2],[4,4,4],[6,6,6]]
def test_multiply():
matrix3 = Matrix([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])
matrix4 = Matrix([[1,2,3,1],[4,5,6,1],[7,8,9,1],[10,11,12,1],[13,14,15,1]])
matrix3.multiply(matrix4)
matrix3.show()
assert matrix3.data == [[35,40,45,5],[70,80,90,10],[105,120,135,15]]
def test_multiply_type_validation():
with pytest.raises(Exception):
matrix3 = Matrix([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])
matrix3.multiply(5)
def test_multiply_size_validation():
with pytest.raises(Exception):
matrix3 = Matrix([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])
matrix4 = Matrix([[1,2,3,1],[4,5,6,1],[7,8,9,1],[10,11,12,1]])
matrix3.multiply(matrix4)
def test_transpose():
matrix4 = Matrix([[1,2,3,1],[4,5,6,1],[7,8,9,1],[10,11,12,1],[13,14,15,1]])
result = matrix4.transpose()
assert result.data == [[1, 4, 7, 10, 13], [2, 5, 8, 11, 14], [3, 6, 9, 12, 15], [1, 1, 1, 1, 1]]
def test_determinant_size_validation():
with pytest.raises(Exception):
matrix1 = Matrix([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])
matrix1.determinant()
def test_determinant_2x2():
matrix5 = Matrix([[1,-1],[3,-2]])
assert matrix5.determinant() == 1
def test_determinant_3x3():
matrix6 = Matrix([[3,2,-1],[4,0,3],[2,-3,5]])
assert matrix6.determinant() == 11
def test_determinant_4x4():
matrix7 = Matrix([[2,3,3,6],[2,3,6,7],[21,82,0,3],[2,23,1,1]])
assert matrix7.determinant() == -4627
def test_adjugate():
matrix8 = Matrix([[1,0,0,0],[2,3,0,0],[4,2,1,0],[-2,3,1,1]])
assert matrix8.adjugate().data == [[3, -2, -8, 20], [0, 1, -2, -1], [0, 0, 3, -3], [0, 0, 0, 3]]
def test_inverse():
matrix8 = Matrix([[1,0,0,0],[2,3,0,0],[4,2,1,0],[-2,3,1,1]])
assert matrix8.invert().data == [[1.0, 0.0, 0.0, 0.0], [-0.67, 0.33, 0.0, 0.0],[-2.67, -0.67, 1.0, 0.0],[6.67, -0.33, -1.0, 1.0]]
def test_nonInvertable_validation():
matrix9 = Matrix([[0,0,0,0],[2,3,0,0],[4,2,1,0],[-2,3,1,1]])
with pytest.raises(Exception):
matrix9.invert()
def test_getRows():
matrix9 = Matrix([[92,33,34,6],[2,3,6,7],[21,82,0,3],[2,23,1,1],[25,232,21,41],[52,263,18,16],[82,2003,16,1443],[2,203,1,13]])
assert matrix9.getRows([1,3,5,6]) == [[82, 2003, 16, 1443], [2, 23, 1, 1], [2, 3, 6, 7], [52, 263, 18, 16]]
def test_getColumns():
matrix9 = Matrix([[92,33,34,6],[2,3,6,7],[21,82,0,3],[2,23,1,1],[25,232,21,41],[52,263,18,16],[82,2003,16,1443],[2,203,1,13]])
assert matrix9.getColumns([1,2]) == [[33, 3, 82, 23, 232, 263, 2003, 203], [34, 6, 0, 1, 21, 18, 16, 1]]
def test_getRepeatedRows():
matrix10 = Matrix([[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6]])
assert matrix10.getRows([2,3,4]) == [[92,33,34,33,6]]
def test_getRepeatedColumns():
matrix10 = Matrix([[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6],[92,33,34,33,6]])
assert matrix10.getColumns([0,1,3]) == [[92, 92, 92, 92, 92, 92], [33, 33, 33, 33, 33, 33]]
def test_get10X2Part():
matrix11 = Matrix([[932,353,334,313,66,932,353,334,313,66],[9,3,34,33,6,932,353,3,3,6],[2,3,63,364,363,66,94,3,6,9],[92,33,34,33,6,932,353,334,313,66],[952,353,354,353,652,353,334,313,6,0],[962,363,364,363,66,9,3,3,3,6],[2,3,63,364,363,66,94,3,6,9],[9,36,34,31,6,90,24,4,3,46],[92,350,3504,303,6502,350,3034,3103,60,00],[9621,3631,3641,3631,661,91,31,31,31,61]])
result = Matrix(matrix11.getPart(0,10,4,5))
assert result.numRows == 10 and result.numColumns == 2 |
0ae10072426575f3785a2bf431f4b61de28d46ae | Johnathan-Xie/Siena-Youth-Center-Code-Examples | /Day3/card_picker_class_proj3.py | 1,584 | 3.921875 | 4 | import random
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def get_value(self):
return self.value
def get_suit(self):
return self.suit
def __str__(self):
return self.value + ' of ' + self.suit
def __repr__(self):
return "Card(%s, %s)" % (self.value, self.suit)
class Deck:
'''Deck of cards example class'''
#static variables(shared across class instances)
values = ['two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'jack', 'queen',
'king', 'ace']
suits = ['spades', 'clubs', 'hearts', 'diamonds']
#initalize non-static variables(unique for each class instance)
def __init__(self):
self.cards = []
for val in Deck.values:
for suit in Deck.suits:
self.cards.append(Card(val, suit))
random.shuffle(self.cards)
def pick(self, num_cards):
chosen_cards = [str(card) for card in self.cards[:num_cards]]
del self.cards[:num_cards]
return chosen_cards
#have students type on their own
def peek(self, num_cards):
chosen_cards = [str(card) for card in self.cards[:num_cards]]
return chosen_cards
def __getitem__(self, idx):
return self.cards[idx]
def pop(self):
return self.cards.pop()
def append(self, card):
self.cards.append(card)
if __name__ == '__main__':
deck = Deck()
deck.peek(10)
deck.pick(10)
deck.pick(10) |
85e5fd2576dc040cd3330f3a7e92eda77f4a614c | tapishr/Interview-Prep | /priya/interviewbit/Number of 1 bits.py | 295 | 3.609375 | 4 | class Solution:
# @param A : integer
# @return an integer
def numSetBits(self, A):
count = 0
while(A!=0):
if(A&1):
count+=1
A = A>>1
return count
# Question at : https://www.interviewbit.com/problems/number-of-1-bits/
|
c139e47059479fbb71179d7905ac4193bb1f8f46 | psh89224/Bigdata | /01_Jump_to_Python/Chapt03/124-2.py | 282 | 3.5625 | 4 | #coding=cp949
prompt="""
1.Add
2.Del
3.List
4.Quit
Enter number:"""
number=0
while True:
print(prompt,end='')
number=int(input())
if number ==4:
break #while ᰡ Ǵ 2 ̻϶
else:
if number ==5:
break
|
539997a066346e122873fb28429ed3ed145b7cfe | vadim-ivlev/pytest | /hello.py | 654 | 4.21875 | 4 | #%%%
print("hello")
print('hello1')
print('hello2')
#%%%
a=5
b=6
c=a+b
print(a+b)
# %%
# %%
# import an excel file into a dataframe and save it to sqlite3 database
def import_excel_to_sqlite():
import pandas as pd
import sqlite3
# read the excel file into a dataframe
df = pd.read_excel('data.xlsx')
# save the dataframe to sqlite3 database
conn=sqlite3.connect('data.db')
df.to_sql('data', conn, if_exists='replace', index=False)
# read the data from the database
df = pd.read_sql('SELECT * FROM data', con=sqlite3.connect('data.db'))
# print the dataframe
print(df)
import_excel_to_sqlite()
# %%
|
57a93c185a3f8e21a86dbc2ece77a0a75edcecd1 | shenhuaze/leetcode | /python/symmetric_tree.py | 857 | 3.875 | 4 | # @author Huaze Shen
# @date 2020-01-12
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_symmetric(root):
if root is None:
return True
return is_equal(root.left, root.right)
def is_equal(left, right):
if left is None and right is None:
return True
elif left is None:
return False
elif right is None:
return False
elif left.val != right.val:
return False
return is_equal(left.right, right.left) and is_equal(left.left, right.right)
if __name__ == '__main__':
root_ = TreeNode(1)
root_.left = TreeNode(2)
root_.right = TreeNode(2)
root_.left.left = TreeNode(3)
root_.right.right = TreeNode(3)
root_.left.right = TreeNode(4)
root_.right.left = TreeNode(4)
print(is_symmetric(root_))
|
97214616b4b0a4ffb8cc46dd6eae1305a6f8c87a | whyj107/Algorithm | /Puzzle/012_Sqrt.py | 1,236 | 3.671875 | 4 | # 제곱근의 숫자
# 문제
# 제곱근을 소수로 나타내었을 때 0 ~ 9의 모든 숫자가 가장 빨리 나타나는 최소 정수를 구해 보세요.
# 단 여기서는 양의 제곱근만을 대상으로 합니다.
# 정수 부분을 포함하는 경우와 소수 부분만 취하는 경우 각각에 대해 모두 구해 보세요.
# 힌트
# 포인트는 소수의 '유효 숫자'를 의삭하고 있느냐가 되겠습니다.
# 소수를 다루는 형에는 float형이나 double형 등이 있습니다.
from math import sqrt
# 정수 부분을 포함하는 경우
i = 1
while True:
i += 1
# 소수점을 제거하고 왼쪽 10문자 추출
string = '{:10.10f}'.format(sqrt(i)).replace('.', '')[0:10]
# 중복을 제거해서 10문자라면 종료
if len(set(string)) == 10:
break
print('정수 부분을 포한하는 경우 :', i)
# 소수 부분만 계산하는 경우
i = 1
while True:
i += 1
# 소수점으로 붖ㄴ할하여 소수 부분만을 취득
string = '{:10.10f}'.format(sqrt(i)).split('.')[1]
# 소수 부분의 중복을 제거하고 10문자라면 종료
if len(set(string)) == 10:
break
print('소수 부분만 계산하는 경우 :', i) |
6d7aa904a771c55c590c10dbd67f10c697cfd94d | ko9ma7/cse_project | /coding practice/Programmers/Skill Check/Level2/2.py | 618 | 3.515625 | 4 | def solution(heights):
answer = []
re_heights = list(reversed(heights))
for i in range(len(re_heights)):
for j in range(i+1, len(re_heights)):
print(re_heights[i], re_heights[j])
if re_heights[i] < re_heights[j]:
answer.append(j)
break
else:
if j == len(re_heights)-1
print(answer)
answer = list(reversed(answer))
result = []
for a in answer:
if a == 0:
result.append(0)
else:
result.append(len(heights)-a)
return result
print(solution([6,9,5,7,4])) |
43c03d8297634cb68e0204f0824db13244572422 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/krmtsi001/question4.py | 800 | 4.0625 | 4 | marks=input("Enter a space-separated list of marks:\n").split() #is is to make what the user has inputted into a list for manipulation
first_class=0
upper_second=0 #line 2 to 5 making each grade a category
lower_second=0
third_class=0
fail=0
for grade in marks:
if eval(grade)<50: #looping through the mark so that they can be put into their respective grades
fail+=1
elif eval(grade) < 60:
third_class+=1
elif eval(grade)< 70:
lower_second+=1
elif eval(grade)<75:
upper_second+=1
else:
first_class+=1
print("1 |"+"X"*first_class)
print("2+|"+"X"*upper_second) #displaying the grades with each mark grouped in a histogram
print("2-|"+"X"*lower_second)
print("3 |"+"X"*third_class)
print("F |"+"X"*fail) |
f18b46c4a3dff8b2f1ae9073956aefda9ab30690 | gutus/100DaysPythonAngelaWu | /Day02/Day02Section01.py | 874 | 3.96875 | 4 | # TIP CALCULATOR
# Untuk menghitung tagihan per orang beserta tip nya
print("Selamat datang, mari kita hitung tagihan tiap orang.")
tagihan = int(input("Berapa besaranya tagihan bill total? "))
tip = int(input("Berapa besaran tip untuk pelayan, 10, 12 atau 15% ? "))
orang = int(input("Berapa banyaknya orang yg akan ditagih? "))
tip_persentase = tip/100
besaran_tip = tip_persentase * tagihan
total_tagihan_semua = tagihan + besaran_tip
tagihan_per_orang = total_tagihan_semua / orang
tagihan_final = round(tagihan_per_orang, 0)
print(f"Besar tagihan awal {tagihan}")
print(f"Besaran tip yg dipilih {tip}% dengan besaran {besaran_tip}")
print(
f"Total tagihan {tagihan} + tip {besaran_tip} = {total_tagihan_semua}")
print(
f"Total tagihan semua {total_tagihan_semua} / {orang} = {tagihan_per_orang}")
print(f"Jadi tiap orang membayar sebesar Rp {tagihan_final}")
|
7a5153a4f2bd556a0ff448953e9329ec8745b236 | sarenvs/guvi | /9.py | 74 | 3.59375 | 4 | b=input()
a=len(b)
ba=b[::-1]
if b==ba:
print(b[:a-1])
else:
print(b)
|
78f98af6b91e927c6d4ecca88f216137eeba2452 | terasakisatoshi/pythonCodes | /iterators/iter_next.py | 205 | 3.65625 | 4 | def count():
c = 0
while True:
yield c
c += 1
gen = count()
print(next(gen)) # 0と表示
print(next(gen)) # 1と表示
print(next(gen)) # 2と表示
print(next(gen)) # 3と表示 |
3b7d8e19dbe705b573b3a71ad17ce7d95bbd0ce2 | bupt-yl/TF | /homework-copy/zy1.py | 2,103 | 3.546875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cv2
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)
# print("输入数据的shape",mnist.train.images.shape)
# import pylab
im = mnist.train.images[1]
# im1 = mnist.train.images[2]
#print(im)
#im = im.reshape(28,28)
#im = im.reshape(-1,28)
# pylab.imshow(im)
# pylab.show()
tf.reset_default_graph()
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
W = tf.Variable(tf.random_normal(([784,10])))
b = tf.Variable(tf.zeros([10]))
pred = tf.nn.softmax(tf.matmul(x,W) + b) #pred的shape为[None,10],b会自动广播为[None,10]
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),\
reduction_indices = 1)) #cost为交叉熵,reduction_indices=1 表示对行向量求和
saver = tf.train.Saver()
# with tf.Session() as sess:
# sess.run(tf.global_variables_initializer())
# print(sess.run(tf.matmul(x,W) + b,feed_dict={x:[im,im1]}))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #梯度下降最小化损失函数
training_epochs = 25
batch_size = 100 #一次训练batch_size项数据
display_step = 1
with tf.Session() as sess:
with tf.device("/gpu:0"):
sess.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
avg_cost = 0.0
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
_,c = sess.run([optimizer,cost],feed_dict \
={x:batch_xs,y:batch_ys})
avg_cost += c/total_batch
#if(epoch+1)%display_step == 0:
#print("Epoch:",'%04d'%(epoch + 1),"cost=","{:.9f}".format(avg_cost))
saver.save(sess,"saver/mnist.cpkt")
print("finished!")
#print(sess.run(pred,feed_dict={x:[im]})) #给出预测
|
da86fb792fbf2552bf3b7c4d180d366b85453c0b | tlind15/Algorithms_python | /search_algorithms/src/run_times2.py | 1,610 | 3.6875 | 4 | from random import randint
from rand_array import rand_array
from binary_search import *
from linear_search import *
from math import log2
print("Input a size: ")
size = int(input()) #takes in input
while size <= 0: #ensuring a valid size
print("Not a valid size input a size: ")
size = int(input())
array = rand_array(size, -5000, 5000)
array[len(array)-1] = 7000
key = 7000
#Linear Search Result
position = linear_search(array,key)
print("The position of the key is from Linear Search is %s" % position)
#Binary Search Result
array.sort()
position = binary_search(array,key)
print("The position of the key from Binary Search is %s" % position)
#Linear Search Worst Case
worst_time = linear_srch_runtime(10^6, -5000, 5000, True)
print("The worst case run time for linear search is %s seconds" % worst_time)
single_lin = worst_time/100000
#Binary Search Worst Case
worst_time = binary_srch_runtime(100000, -5000, 5000, True)
print("The worst case run time for binary search is %s seconds" % worst_time)
single_step = worst_time/log2(100000)
#Linear Search Projected Runtime
print("\nThe projected runtime for linear search for n= 10^6 is %s seconds" % (single_lin*1000000))
actual = linear_srch_runtime(1000000, -5000, 5000, True)
print("The actual runtime for linear search for n= 10^6 is %s seconds" % actual)
#Binary Search Projected Runtime
print("\nThe projected runtime for binary search for n=10^6 is %s seconds" % (single_step*log2(1000000)))
actual = binary_srch_runtime(1000000, -5000, 5000, True)
print("The actual runtime for binary search for n= 10^6 is %s seconds" % actual)
|
e4f3946f5c863136f4aa0077ca979c718658947e | Nanofication/PersonalChatbot | /Interface.py | 649 | 3.65625 | 4 | """
Chatbot interface
Run this script to interact with the chatbot
"""
import Brain
def interactWithChatbot(user_input):
"""
Processes the user_input and come up with the correct response
"""
memory = Brain.parseUserInput(user_input)
if memory != None:
print Brain.processMemory(memory)
else:
print "I did not catch that"
if __name__ == "__main__":
Brain.parseMemoryDB()
print "What can I do for you?"
user_input = raw_input(">: ")
while user_input != "FINISH":
interactWithChatbot(user_input)
print "What else can I do for you?"
user_input = raw_input(">: ")
|
55985dcc0db14580d4e59b23945a2d2fa27781e3 | Lovelyjha/GeeksforGeeks | /2.Easy/Anagram.py | 168 | 3.671875 | 4 | t=int(input())
for _ in range(t):
a,b=input().split()
if set(a)==set(b) and len(a)==len(b):
print("YES")
else:
print("NO")
|
3cecd0940a755266e48efbf4e2f4eb21fc81617c | arminale/ProjectEuler | /102_Triangle_Containment/p102.py | 1,087 | 3.75 | 4 | # https://projecteuler.net/problem=102 Triangle Containment
# For any 3 non collinear points ABC:
# The sum of the areas of the three triangles OAB, OAC, and OBC is equal to the area of a triangle ABC if and only if
# O is contained in ABC
# The area of a triangle can be calculated from the coordinates of its vertices using the formula here:
# https://www.mathopenref.com/coordtrianglearea.html
with open("p102_triangles.txt", 'r') as file:
contains = 0
for line in file:
coordinates = line.split(',')
coordinates[5] = coordinates[5][:-1] # removes the newline character
coordinates = list(map(int, coordinates))
ax = coordinates[0]
ay = coordinates[1]
bx = coordinates[2]
by = coordinates[3]
cx = coordinates[4]
cy = coordinates[5]
s_abc = abs(ax*(by-cy) + bx*(cy-ay) + cx* (ay-by))/2
s_obc = abs(bx*cy - cx*by)/2
s_oab = abs(ax*by - bx*ay)/2
s_oac = abs(ax*cy - cx*ay)/2
if s_abc == s_oab + s_oac + s_obc:
contains += 1
print(contains) |
76198dfa6b068a4451886a7f12c057cf6906e9e0 | DiamondGo/leetcode | /python/GrayCode.py | 771 | 4.03125 | 4 | '''
Created on 20160501
@author: Kenneth Tse
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
'''
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n == 0: return []
if n == 1: return [0, 1]
l = self.grayCode(n -1)
return [code * 2 for code in l] + [code * 2 + 1 for code in reversed(l)]
if __name__ == '__main__':
pass |
5362d1c07ac02b5859d350530c3e84b76eae358c | ribal-aladeeb/state-space-search | /node.py | 2,685 | 3.6875 | 4 | from __future__ import annotations # in order to allow type hints for a class referring to itself
from typing import List, Tuple
from board import Board
import numpy as np
class Node:
def __init__(self,
move: dict = None,
parent: Node = None,
simple_cost: int = 0,
is_root: bool = False,
board: Board = None,
heuristic_func=None):
self.is_root = is_root
if is_root:
assert board != None, "There should be a board argument if is_root=True"
self.board = board
self.start = (np.nan, np.nan)
self.end = (np.nan, np.nan)
self.simple_cost = 0
self.total_cost = 0
else:
assert move != None, "A node should always be created with a move argument when not root"
assert parent != None, "If a node is not root, parent cannot be None"
self.start: tuple = move['start']
self.end: tuple = move['end']
self.board: Board = move['board']
self.simple_cost = move['simple_cost']
self.total_cost = self.simple_cost + parent.total_cost
self.g_n = self.total_cost
self.parent: Board = parent
if heuristic_func:
self.h_n = heuristic_func(self)
self.g_n = self.total_cost
self.f_n = self.g_n + self.h_n
def successors(self, heuristic_func=None) -> List[Node]:
moves: List[dict] = self.board.generate_all_moves()
successors: List[Node] = []
for move in moves:
child = Node(move=move, parent=self, heuristic_func=heuristic_func)
successors.append(child)
return successors
def is_goal_state(self) -> bool:
return self.board.is_goal_state()
def generate_solution_string(self, algo: str) -> Tuple[str, str]:
'''
This function returns the strings needed to create the solution.txt and
search.txt files. The algo parameter takes one of ['ucs' , 'gbf', 'a*'].
'''
solution = ''
current_node = self
while current_node.parent != None:
moved_tile_index = current_node.start
moved_tile_value = current_node.board.puzzle[moved_tile_index]
board_as_string = current_node.board.line_representation()
solution = f'{moved_tile_value} {current_node.simple_cost} {board_as_string}\n' + solution
current_node = current_node.parent
root_node = current_node.board.line_representation()
solution = f'0 0 {root_node}\n' + solution
return solution
|
05434c09a84d35b809ab74e5c24d73f777012a48 | stgleb/problems | /python/tree/ddl_to_tree.py | 1,517 | 3.953125 | 4 | """
Convert sorted ddl to binary search tree
"""
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def find_mid(left, right):
slow = left
fast = left
while fast != right:
fast = fast.next
if fast == right:
slow = slow.next
break
fast = fast.next
slow = slow.next
return slow
def convert(head, tail):
if head == tail:
head.next = None
head.prev = None
tail.next = None
tail.prev = None
return head
mid = find_mid(head, tail)
root = mid
if head != mid:
left_root = convert(head, mid.prev)
else:
left_root = None
if mid != tail:
right_root = convert(mid.next, tail)
else:
right_root = None
root.prev = left_root
root.next = right_root
return root
def inorder_traversal(root):
if not root:
return
inorder_traversal(root.prev)
print(root.value)
inorder_traversal(root.next)
if __name__ == "__main__":
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.prev = node5
node5.prev = node4
node4.prev = node3
node3.prev = node2
node2.prev = node1
root = convert(node1, node5)
inorder_traversal(root)
|
3a0f4e68e62982755c98dffc8e0f14e63c9a0fbe | wp-lai/xpython | /code/month_day.py | 526 | 3.96875 | 4 | """
Task:
Convert date from day of the month to day of the year.
>>> month_day(1988, 60)
(2, 29)
"""
def month_day(year, day):
daytab = [[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
leap = 1 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 0
i = 1
while (day > daytab[leap][i]):
day -= daytab[leap][i]
i += 1
return (i, day)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
506434e071543e78caeb394af28b980dbd41e922 | rexarabe/Python_projects2 | /string_methode/020_casefold.py | 141 | 3.875 | 4 | """In this example we will use method that will lower case the text"""
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
|
1cb3381142bcd6dc5d62711104037226922c9021 | lisettemalacon/MOSTECEECS2019 | /MOSTEC EECS work 2/collision.py | 545 | 3.546875 | 4 | def collision(coord1,w1,h1,coord2,w2,h2):
x1 = coord1[0]
y1 = coord1[1]
x2 = coord2[0]
y2 = coord2[1]
width1 = x1 + w1
height1 = y1 + h1
width2 = x2 + w2
height2 = x2 + h2
x_intersection = [x for x in list(range(x1,width1 + 1)) if x in list(range(x2,width2 + 1))]
y_intersection = [y for y in list(range(y1,height1 + 1)) if y in list(range(y2,height2 +1))]
if (len(x_intersection) >= 1) and (len(y_intersection) >= 1):
return True
else:
return False
|
548880a6cbb881dadfad5db2370eff60ccd96121 | ashukrishna100/Python_Data_Analysis | /numpy_tutorial.py | 2,009 | 3.984375 | 4 |
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
## determine size and shape of an array
array1=np.array([(2,3,4,5),(1,0,3,6)])
print(array1.size)
print(array1.shape)
# In[3]:
## Reshape an array
array1=np.array([(2,3,4,5),(1,0,3,6)])
print(array1.reshape(4,2))
# In[4]:
## Datatype
print(array1.dtype)
##change datatype
float_array1=array1.astype(np.float64)
print(float_array1)
print(float_array1.dtype)
# In[5]:
##indexing and slicing
array2=np.arange(10)
print(array2)
print(array2[5])
print(array2[3:5])
# In[6]:
##change elements of 1-D array
array2[5]=100
print(array2)
# In[7]:
## slicing
array2_slice=array2[:6]
print(array2_slice)
# In[8]:
## 2-D array, array1=[[2, 3, 4, 5],[1, 0, 3, 6]]
print(array1[1])
print(array1[1,3])
# In[9]:
##slicing in 2-d array
print(array1[:2,3:])
print(array1[:2,3])
# In[10]:
##transposing and dot product
array3=np.arange(10).reshape(5,2) ##5*2=10,5*2 matrix/array
print(array3)
# In[11]:
print(array3.T)
## becomes 2*5 matrix/array
# In[12]:
##dot product
print(np.dot(array3.T,array3))
# In[13]:
## Universal functions ; array2=[ 0 1 2 3 4 100 6 7 8 9]
print(array2.sum())
print(array2.max())
print(array2.std())
print(array2.var())
print(np.median(array2))
print(np.sqrt(array2))
# In[21]:
##conditional logic on Array operations
array4=np.random.randn(2,3)
print(array4)
print(array4>0)
print(np.where(array4 > 0, 2, -2))
# In[39]:
## operations of rows and columns ,axis
print(array3)
print(array3.sum(axis=0))
print(array3.sum(axis=1))
print(array3.sum(axis=None))
# In[48]:
##concatenate arrays
array5=np.random.randn(2,4)
print(np.concatenate((array1, array5)))
# In[73]:
##sorting
#print(array5)
array5.sort(1)
print(array5)
# In[71]:
##unique and sets
names = np.array(['Chandu','Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
print(np.unique(names))
print(sorted(set(names)))
# In[83]:
## identity matrix
print(np.identity(2))
print(np.eye(2,4,k=2))
|
97ddfd2f21b8ff623531d6d7010019ea682096f6 | 77Ladybug/python-converter | /inputccyconvv1.py | 418 | 3.84375 | 4 | def conv_CHF_in_EUR(CHF):
EUR = CHF * 0.88
return "As per today " + str(CHF) + " chf equal " + str(EUR) + " eur"
user_input = input("Please enter amount of CHF you want to convert in EUR: ")
result = (conv_CHF_in_EUR (float(user_input) * 0.88))
print(result)
if float(user_input) <= 100000:
print("you are not rich!")
if float(user_input) > 100000:
print("you are rich!")
|
ea11d79e06f98b6f7abdd6fd9113483c506075f1 | prabhamerlin/Analysis-of-COVID-cases-in-different-states-of-India | /convert_csv_to_json.py | 597 | 3.5 | 4 | import json # This is for working on JSON data
import csv # This is for working on .csv FILE
with open ("Population.csv", "r") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append({"Rank" : row[0],
"State/UT" : row[1],
"Population" : row[2]
# "Active cases" : row[3],
# "Cured/Discharged" : row[4],
# "Death" : row[5]
})
with open("Population.json", "w") as f:
json.dump(data,f,indent=4) |
c5681d2393a23eea2b3f9b53a53300e17b30c6ba | rodrigobn/Python | /Lista de exercicio 5 (Lista e Matrizes)/ex02.py | 235 | 4.0625 | 4 | """
2 - Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa.
"""
lista = [1,2,3,4,5,6,7,8,9,10]
if lista == []:
print("Lista vazia")
else:
for i in range(len(lista)-1, -1, -1):
print(lista[i])
|
b46b30517fdc59d3569d27f08d82d7e049ef8982 | blackrain15/Python_Basics | /07_Dictionary/Sample Problem 2.py | 692 | 3.828125 | 4 | from datetime import datetime, timedelta
start_day = input()
days_to_reach = int(input())
start_date = input()
week_days = {'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4, 'Friday':5, 'Saturday':6, 'Sunday':7}
start_date = datetime.strptime(start_date, '%d-%m-%Y')
start = week_days.get(start_day)
start = start+1
i=1
while(i<days_to_reach):
if(start == 6):
start = start+1
start_date = start_date + timedelta(days=1)
elif(start == 7):
start = 1
start_date = start_date + timedelta(days=1)
else:
i += 1
start = start+1
start_date = start_date + timedelta(days=1)
print(start_date.strftime('%d-%m-%Y')) |
fba0caa7aeffc2bebf1b4ea94a15289dcb595902 | southpawgeek/perlweeklychallenge-club | /challenge-056/lubos-kolouch/python/ch-2.py | 757 | 4 | 4 | #!/usr/bin/env python
""" https://perlweeklychallenge.org/blog/perl-weekly-challenge-056/
Task 2
You are given a binary tree and a sum, write a script to find if the tree has a path such that adding up all the values along the path equals the given sum. Only complete paths (from root to leaf node) may be considered for a sum.
"""
import networkx as nx
g = nx.DiGraph()
g.add_edge(5, 4)
g.add_edge(4, 11)
g.add_edge(11, 7)
g.add_edge(11, 2)
g.add_edge(5, 8)
g.add_edge(8, 13)
g.add_edge(8, 9)
g.add_edge(9, 1)
start = 5
my_sum = 22
external_vertices = (x for x in g.nodes() if g.out_degree(x)==0 and g.in_degree(x)==1)
for vert in external_vertices:
path = nx.shortest_path(g, start, vert)
if sum(path) == my_sum:
print(path)
|
101068ab3872236ce5bbffa778febe5fc49ce58d | daianasousa/POO | /LISTA DE EXERCÍCIOS/Semana02_postagem_extra_Q01.py | 3,352 | 3.890625 | 4 | class Radio:
#Atributos
ligado = True
cor = None
faixa = None
peso = None
altura = None
volume = 0
estacao = None
volume_max = 0
volume_min = 0
#Construtores
def __init__(self, ligado=False, volume_max=100, volume_min=0):
self.ligado = ligado
self.volume_max = volume_max
self.volume_min = volume_min
#Métodos
def ligar(self):
if self.ligado == False:
self.ligado = True
print('Rádio ligado')
else:
print('Rádio já estava ligado')
def desligar(self):
if self.ligado == True:
self.ligado = False
print('Rádio desligado')
else:
print('Rádio já desligado')
def mudar_faixa(self, valor):
self.faixa = valor
print(f'Faixa: {self.faixa}')
def passar_volume(self, valor):
self.volume = valor
if self.volume > self.volume_max:
print('Passou do volume máximo permitido.')
elif self.volume < self.volume_min:
print('Passou do volume minimo permitido.')
print(f'Volume atual: {self.volume}')
def mudar_estação(self, valor):
if self.ligado == True:
self.estacao = valor
print(f'Estação atual: {self.estacao}')
else:
print('Primeiramente ligue seu rádio')
def passar_estação(self):
self.estacao += 0.1
print(f'Passei a estação para {self.estacao:.1f}')
def aumentar_volume(self):
self.volume += 1
if self.volume > self.volume_max:
print('Passou do volume máximo permitido.')
print(f'volume atual: {self.volume}')
def diminuir_volume(self):
self.volume -= 1
if self.volume < self.volume_min:
print('Passou do volume minimo permitido.')
print(f'volume atual: {self.volume}')
#Objeto_1
print('=='*10,'RÁDIO DO VOVÔ','=='*10)
radio_do_vovo = Radio()
radio_do_vovo.ligado = False
radio_do_vovo.cor = 'Preto'
radio_do_vovo.faixa = 'FM'
radio_do_vovo.peso = 1.5
radio_do_vovo.altura = 15
radio_do_vovo.volume = 25
radio_do_vovo.estacao = 101.0
radio_do_vovo.ligar()
radio_do_vovo.desligar()
radio_do_vovo.mudar_faixa('AM')
radio_do_vovo.mudar_estação(99.0)
radio_do_vovo.ligar()
radio_do_vovo.mudar_estação(99.0)
radio_do_vovo.passar_estação()
radio_do_vovo.diminuir_volume()
radio_do_vovo.desligar()
print(f'A Cor do rádio do meu avô é {radio_do_vovo.cor}')
print('')
#Objeto_2
print('=='*10,'RÁDIO DO PAPAI','=='*10)
radio_do_papai = Radio()
radio_do_papai.ligado = True
radio_do_papai.cor = 'Amarelo'
radio_do_papai.faixa = 'AM'
radio_do_papai.peso = 1.0
radio_do_papai.altura = 10
radio_do_papai.volume = 30
radio_do_papai.estacao = 94.5
radio_do_papai.ligar()
radio_do_papai.mudar_faixa('FM')
radio_do_papai.aumentar_volume()
radio_do_papai.aumentar_volume()
radio_do_papai.aumentar_volume()
radio_do_papai.mudar_estação(78.4)
radio_do_papai.passar_volume(101)
radio_do_papai.diminuir_volume()
radio_do_papai.diminuir_volume()
radio_do_papai.diminuir_volume()
radio_do_papai.passar_estação()
radio_do_papai.passar_estação()
radio_do_papai.desligar()
radio_do_papai.mudar_estação(99.9)
radio_do_papai.ligar()
print(f'A Cor do rádio do meu Pai é {radio_do_papai.cor}') |
Subsets and Splits