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 |
|---|---|---|---|---|---|---|
f6dae67f120d4f1b9a677d12445ad851c69b5158 | ychang0821/tlg_learning_test | /tuple_practice.py | 631 | 3.765625 | 4 | import time
tuple_record = ('eth0', 'AA:BB:CC:DD:11:22', '192.168.0.1', '5060', 'UDP')
print(tuple_record)
print(tuple_record * 2)
print(tuple_record[0:2])
print(tuple_record[1])
records = ['eth0', 'AA:BB:CC:DD:11:22', '192.168.0.1', '5060', 'UDP']
# list is mutable, tuple is immutable
#tuple_record.
#records.
localTime = time.localtime(time.time())
print(localTime)
print(localTime[0:2]) # year and month
print('The year is {}'.format(localTime[0])) # the year is ...
print('The minutes is', localTime[4]) # the minute is ...
print('{}/{}/{}'.format(localTime[0],localTime[1],localTime[2])) # year/month/date
|
b59ae61f83d2e8b33896251441d9ff3cba8d37ef | Gazizova/smallPythonProgramms | /small_calc_apps/small_calc.py | 2,743 | 4.1875 | 4 | # 1.12 - 2
a = int(input("enter the number"))
if ((-15) < a <= 12) or (14 < a < 17) or (a >= 19):
print(True)
else:
print(False)
# 1.12 - 3
a = float(input("Input first value"))
b = float(input("Input second value"))
c = str(input("Input one of operations:'+', '-', '/', 'mod', 'div', 'pow' "))
def calc():
if c == '+':
print(a + b)
elif c == '-':
print(a - b)
elif c == '/' and b != 0:
print(a / b)
elif c == '/' and b == 0:
print("Деление на 0!")
elif c == '*':
print(a * b)
elif c == 'mod'and b != 0:
print(a % b)
elif c == 'mod'and b == 0:
print("Деление на 0!")
elif c == 'pow':
print(a ** b)
elif c == 'div' and b != 0:
print(a // b)
elif c == 'div' and b == 0:
print("Деление на 0!")
else:
print("Operation do not supported")
calc()
# 1.12 - 4
name = str(input("Input figure name"))
if name == "прямоугольник":
a = float(input("Input the length of the first side"))
b = float(input("Input the length of the second side"))
count = a * b
print(count)
elif name == "треугольник":
a = float(input("Input the length of the first side"))
b = float(input("Input the length of the second side"))
c = float(input("Input the length of the third side"))
p = (a+b+c)/2
count = (p*(p-a)*(p-b)*(p-c))**0.5
print(count)
elif name == "круг":
r = float(input("Input radius"))
pi = 3.14
count = pi * (r**2)
print(count)
# 1.12 - 4
a = int(input("enter the number"))
b = int(input("enter the number"))
c = int(input("enter the number"))
if (a >= b and a >= c) and c >= b:
print(a, "\n", b, "\n", c)
elif (a >= b and a >= c) and b >= c:
print(a, "\n", c, "\n", b)
elif (b >= a and b >= c) and a >= c:
print(b, "\n", c, "\n", a)
elif (b >= a and b >= c) and c >= a:
print(b, "\n", a, "\n", c)
elif (c >= a and c >= b) and a >= b:
print(c, "\n", b, "\n", a)
elif (c >= a and c >= b) and b >= a:
print(c, "\n", a, "\n", b)
# 1.12 - 5
a = int(input("Сколько программистов в комнате? "))
if a == 0 or 5 <= a <= 20 or a % 10 >= 5 or 11 <= a % 100 <= 15 or a % 10 == 0:
print(a, "программистов")
elif a % 10 == 1 or a == 1:
print(a, "программист")
else:
print(a, "программиста")
# 1.12 - 6
n = int(input("Узнай, счастливый ли твой билет. Введи номер билета:"))
a = n // 1000
b = n % 1000
c1 = (a // 100 ) + (a%100//10) + (a%100%10)
c2 = (b // 100 ) + (b%100//10) + (b%100%10)
if c1 == c2:
print("Счастливый")
else:
print("Обычный") |
b2f292863698ef4c3c28ff681fa6cf0773ece25f | lozdan/oj | /HakerRank/algorithms/implementation/kangaroo.py | 430 | 3.515625 | 4 | # author: Daniel Lozano
# source: HackerRank ( https://www.hackerrank.com )
# problem name: Algorithms: Implementation: Kangaroo
# problem url: https://www.hackerrank.com/challenges/kangaroo/problem
# date: 8/10/2017
x1, v1, x2, v2 = [int(x) for x in input().split()]
if v1 > v2:
while x1 < x2:
x1 += v1
x2 += v2
if x1 == x2:
print("YES")
exit()
print("NO")
else:
print("NO") |
77bb6e755479e7585c38d0f10a9af609e8903e32 | remon/pythonCodes | /Functions/lambda_en.py | 116 | 3.96875 | 4 | #what is the output of this code?
gun = lambda x:x*x
data = 1
for i in range(1,3):
data+=gun(i)
print(gun(data))
|
4042b2b1fd6ef6652ca7cf655e1179c6e89d6144 | tashakim/puzzles_python | /assignCookies.py | 1,204 | 3.640625 | 4 | import heapq
class Solution:
def findContentChildren(self, g, s):
"""
Purpose: Given greed factor g[i] of each child, returns the max. number
of children that are content after distributing cookies of size s[i].
Note: A child is content if they eat a cookie that has size greater than
or equal to their greed factor.
Sample Input: g = [1,2,3], s= [1,1]
Sample Output: 1
"""
g.sort()
s.sort()
child = cookie = 0
num_cookies = len(s)
num_children = len(g)
while cookie < num_cookies and child < num_children:
if s[cookie] >= g[child]:
child += 1
cookie += 1
return child
def findContentChildren1(self, g, s):
"""
Purpose: Min. heap approach.
"""
heapq.heapify(s)
count = 0
g.sort()
for child in g:
# end if no cookies exist
if not s: return count
x = float('-inf')
while x < child and s:
x = heapq.heappop(s)
if x >= child:
count += 1
return count
|
3829f3c7d57756dc054e8af387463262701fe29b | Jriosv/Roya-Prediction-Tree | /primera_interface.py | 318 | 3.53125 | 4 | from tkinter import *
raiz = Tk()
raiz.title("Calculador de roya")
raiz.config(bg="chocolate3")
myFrame = Frame()
myFrame.pack(fill="both",expand="True")
myFrame.config(bg = "tan1")
myFrame.config(width="650",height="350")
myFrame.config(bd=35)
myFrame.config(relief="groove")
print("Hola mundo")
raiz.mainloop() |
43df5de1ebbfd1417292fef82cfbc70c82c4f94c | muyisanshuiliang/python | /wrapper/ernary_expression.py | 224 | 4.0625 | 4 | # res = 条件成立的返回值 if 条件 else 条件不成立的返回值
res = 1111 if 1 > 2 else 2222
print(res)
# expression for item1 in iterable1 if condition1
list = [x * x for x in range(3) if x >= 2]
print(list)
|
6d8d0604548f790e7712bf7b61092dea724749cd | MytnikAA/fibonacci | /fib.py | 446 | 4.15625 | 4 | #!/usr/bin/python3
import sys
def fibRec(n):
if n < 2:
return n
else:
return fibRec(n - 1) + fibRec(n - 2)
def fibIter(n):
prv = 0;
nxt = 1;
for i in range(1, n):
cur = prv + nxt
prv = nxt
nxt = cur
return nxt
n = int(sys.argv[1])
method = sys.argv[2]
fibonacci = 0
if method == "i":
fibonacci = fibIter(n)
elif method == "r":
fibonacci = fibRec(n)
print("Python 3 done " + method + "\n" + str(fibonacci))
|
f9b5b176ff1f2fc4b44fadcf1acf72f9a8e4d8bc | Kallehz/Python | /Próf1/FilterAndSum.py | 802 | 3.71875 | 4 | # Write a function filter_sum(lis) that takes a list of integers as an argument.
# The function returns a pair (2-tuple). The second element of the tuple are the
# elements of the list lis where all the integers smaller than 10 and larger than
# 95 have been removed. The first element of the tuple is the sum of the elements of
# that list.
def filter_sum(lis):
l = []
for x in lis:
if 10 <= x <= 95:
l.append(x)
return tuple((sum(lis), l))
##def filter_sum(lis):
## l = []
## for x in lis:
## if x >= 10 and x <= 95:
## l.append(x)
## return(sum(l), l)
print(filter_sum([1, 9, 30, 12]))
print(filter_sum([88, 1, 119, -12, -10, -18, 117, 26, 46, 37, 9, 63, 9, 125, 18, 111, 6, 8, 34, 116, 75, 21, -7, 94, 32, 61, -28, 10, 61, 86],))
|
cea0801b2efcdb817869d44cacab85622a05c87a | bryrodri/Proyecto_python_1_b | /modulos/lista_vacias.py | 168 | 3.765625 | 4 | def is_empty(data_structure):
if data_structure:
#print("No está vacía")
return False
else:
#print("Está vacía")
return True |
ed96447d5a704a5e300645ad67ace742199e590f | nataliakusmirek/CS50x---Portfolio | /pset6/mario/mario.py | 214 | 3.890625 | 4 | from cs50 import get_int
height = get_int("Height: ")
while height > 8 or height < 1:
height = get_int("Height: ")
# create the spaces
for i in range(height):
print(" " * (height - i - 1) + "#" * (i + 1)) |
92655503969fbfd7ea46939131ad19356b6e0ffe | LauraIsCool/Practicals | /agentframework6.py | 795 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 15:40:22 2019
@author: laurapemberton
"""
import random
class Agent():
def __init__(self, environment):
self.x = random.randint(0,99)
self.y = random.randint(0,99)
self.environment = environment
self.store = 0
def move(self):
if random.random() < 0.5:
self.x = (self.x + 1) % 100
else:
self.x = (self.x - 1) % 100
if random.random() < 0.5:
self.y = (self.y + 1) % 100
else:
self.y = (self.y - 1) % 100
def eat(self):
if self.environment[self.x][self.y] > 10:
self.environment[self.y][self.x] -=10
self.store += 10
|
f5a96640f2f7f43b1b73a75326be40d410529892 | OohGitEm/sql-dice | /flasksql/rolltide.py | 358 | 3.59375 | 4 | import random
def roll_dice(num_of_dice, num_of_sides):
dice_rolls = {roll+1: 0 for roll in range(num_of_sides)}
for i in range(num_of_dice):
roll = random.randint(1, num_of_sides)
dice_rolls[roll] += 1
return dice_rolls
if __name__== "__main__":
rolls = roll_dice(1000, 16)
print(rolls)
print(sum(rolls.values()))
|
469bb511f5090cf6919d3935e2dd1245e5935436 | nancydemir/Hackerrank | /hackerDay2.py | 518 | 3.6875 | 4 | import math
import os
import random
import re
import sys
def solve(meal_cost, tip_percent, tax_percent):
sub_total = meal_cost * (tax_percent * 1/100)
with_tip = meal_cost * (tip_percent * 1/100)
total_bill = round(sub_total + meal_cost + with_tip)
print(total_bill)
def main():
meal_cost = float(input())
tip_percent = float(input())
tax_percent = float(input())
solve(meal_cost, tip_percent, tax_percent)
if __name__ == "__main__":
main()
|
c6ade0ee62489eabf89ec6d9dc1e7fe21f7a0923 | jamarflowers/dazn-interview | /2.PYTHON/declarations.py | 304 | 4.0625 | 4 | variable = 89
variableTwo = 0
while variable > variableTwo:
variableTwo = variableTwo + 1
print variableTwo
if(variableTwo % 3 == 0):
print("FIZZ")
elif(variableTwo % 5 == 0):
print("BUZZ")
if variable % 3 == 0 or variableTwo % 5 == 0:
print("FIZZBUZZ") |
678747ee16eb3fddaeed2381923fa624e0fa2467 | carter144/Leetcode-Problems | /problems/994.py | 3,197 | 3.8125 | 4 | """
994. Rotting Oranges
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Solution:
Perform a bfs and keep track of the depth of each 'node' that gets added to the queue
Store the result in a variable and update it each time we see a larger depth.
Check if there are any remaining fresh oranges, if there is then we return -1 since it is not possible to rot these
Runtime: O(m*n)
Space: O(m*n)
"""
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
queue = []
# Add the first rotted oranges to the queue with a depth of 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 2:
queue.append({"coord": [row, col], "depth": 0})
res = 0
while len(queue) > 0:
current_orange = queue.pop(0)
current_row = current_orange["coord"][0]
current_col = current_orange["coord"][1]
depth = current_orange["depth"]
res = max(res, depth)
# check if in bounds and if the element is a fresh orange, we want to rot it then add it to the queue with a new depth
if current_row - 1 >= 0 and grid[current_row - 1][current_col] == 1:
grid[current_row - 1][current_col] = 2
queue.append({"coord": [current_row - 1, current_col], "depth": depth + 1})
if current_row + 1 <= len(grid) - 1 and grid[current_row + 1][current_col] == 1:
grid[current_row + 1][current_col] = 2
queue.append({"coord": [current_row + 1, current_col], "depth": depth + 1})
if current_col - 1 >= 0 and grid[current_row][current_col - 1] == 1:
grid[current_row][current_col - 1] = 2
queue.append({"coord": [current_row, current_col - 1], "depth": depth + 1})
if current_col + 1 <= len(grid[0]) - 1 and grid[current_row][current_col + 1] == 1:
grid[current_row][current_col + 1] = 2
queue.append({"coord": [current_row, current_col + 1], "depth": depth + 1})
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1:
return -1
return res |
f7c8411d1ca9cf0799481db2690a4b8f2bf895d2 | emeric75/uvsq_licence | /BI423/TD1/aire.py | 391 | 3.859375 | 4 | print "Calculer l'aire d'une figure"
choix = raw_input("Rectangle(R)/Triangle(T) ? ")
if choix == 'R':
lo = input("Quelle est sa longueur ? ")
la = input("Quelle est sa largeur ? ")
print "Aire du rectangle : ", lo*la
elif choix == 'T':
b = input("Quelle est sa base ? ")
h = input("Quelle est sa hauteur ? ")
print "Aire du triangle : ", b*h/2.0
else:
print "pas de choix de figure"
|
36a84b11d45324cfab08a36faa9f545dff9da4bb | Mitchell-boop/gaphor | /gaphor/misc/rattr.py | 1,227 | 3.953125 | 4 | """Recursive attribute access functions."""
def rgetattr(obj, attr):
"""
Get named attribute from an object, i.e. getattr(obj, 'a.a') is
equivalent to ``obj.a.a''.
- obj: object
- attr: attribute name(s)
>>> class A: pass
>>> a = A()
>>> a.a = A()
>>> a.a.a = 1
>>> rgetattr(a, 'a.a')
1
>>> rgetattr(a, 'a.c')
Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'c'
"""
attrs = attr.split(".")
obj = getattr(obj, attrs[0])
for name in attrs[1:]:
obj = getattr(obj, name)
return obj
def rsetattr(obj, attr, val):
"""
Set named attribute value on an object, i.e. setattr(obj, 'a.a', 1)
is equivalent to ``obj.a.a = 1''.
- obj: object
- attr: attribute name(s)
- val: attribute value
>>> class A: pass
>>> a = A()
>>> a.a = A()
>>> a.a.a = 1
>>> rsetattr(a, 'a.a', 2)
>>> print(a.a.a)
2
>>> rsetattr(a, 'a.c', 3)
>>> print(a.a.c)
3
"""
attrs = attr.split(".")
if len(attrs) > 1:
obj = getattr(obj, attrs[0])
for name in attrs[1:-1]:
obj = getattr(obj, name)
setattr(obj, attrs[-1], val)
|
1df1fa1dc3b1088127701ed55a50ce33fb44fdb3 | tabletenniser/leetcode | /689_maximum_sum_of_3_non_overlapping_subarrays.py | 988 | 4.125 | 4 | '''
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.
Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example:
Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Note:
nums.length will be between 1 and 20000.
nums[i] will be between 1 and 65535.
k will be between 1 and floor(nums.length / 3).
'''
class Solution(object):
def maxSumOfThreeSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
s = Solution()
print s.maxSumOfThreeSubarrays([1,2,1,2,6,7,5,1], 2)
|
2870fae10418d3e4d0bf8be52d99661d0393cc11 | sirajmuneer123/anand_python_problems | /5_chapter/p7.py | 521 | 3.78125 | 4 | '''
Write a program split.py, that takes an integer n and a filename as command line arguments and splits the file into multiple small files with each having n lines.
'''
import sys
def split(n,filename):
i=0
n=int(n)
f=open(filename)
lines=f.read().split('\n')
for line in range(0,len(lines),n):
new_line=lines[line:line+n]
new_file_name='file'+str(i)+'.txt'
new_file=open(new_file_name,'w+')
new_file.write('\n'.join(new_line))
new_file.close()
i=i+1
split(sys.argv[1],sys.argv[2])
|
10406219e58ea4c4bcfbcb0aa338e9173838ebb9 | stefsiekman/aoc2019 | /06/first.py | 1,440 | 3.859375 | 4 | import aoc.input
from queue import Queue
class Planet:
def __init__(self, name, parent=None):
self.name = name
self.parent = parent
self.children = []
def create_planet(planets, name):
if name in planets:
return planets[name]
else:
p = Planet(name)
planets[name] = p
return p
if __name__ == "__main__":
lines = aoc.input.input_lines()
planets = dict()
for line in lines:
line_planets = line.split(')')
p1 = create_planet(planets, line_planets[0])
p2 = create_planet(planets, line_planets[1])
p2.parent = p1
p1.children.append(p2)
queue = Queue()
queue.put((0, planets["COM"]))
total = 0
while not queue.empty():
depth, planet = queue.get()
total += depth
for c in planet.children:
queue.put((depth + 1, c))
print(total)
queue = Queue()
queue.put((0, planets["YOU"].parent))
visited = set()
while not queue.empty():
distance, planet = queue.get()
visited.add(planet)
found = any(c.name == "SAN" for c in planet.children)
if found:
print(distance)
if planet.parent is not None and planet.parent not in visited:
queue.put((distance + 1, planet.parent))
for c in planet.children:
if c not in visited:
queue.put((distance + 1, c))
|
8ad2a9c1a03c8b58255c9924d6ca6c46044269b0 | wentilin/algorithms-study | /python/interview/回文/回文数.py | 1,463 | 4.3125 | 4 | """
9. 回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
"""
# 1
class Solution:
# 方法:负数或者结尾为0的数字都不是回文;然后对整数后面一半的数字进行颠倒,看是不是和前面一半相同
# 注意//和int()都是round down, math.ceil()是round up, 而/会直接得到float
# 时间:O(n)
# 空间:O(1)
def isPalindrome(self, x: int) -> bool:
if x < 0 or x % 10 == 0 and x != 0:
return False
reverse = 0
while x > reverse:
tmp = x % 10
x //= 10 # 注意这一步不能是x /= 10, 否则x为float
reverse = 10 * reverse + tmp
return x == reverse or x == reverse // 10 # 偶数位和奇数位(reverse为x的10倍, 注意是//而不是/)
if __name__ == '__main__':
print(Solution().isPalindrome(0))
print(Solution().isPalindrome(121))
print(Solution().isPalindrome(1221))
print(Solution().isPalindrome(-121))
print(Solution().isPalindrome(10))
|
84da1a824d1b8e8ddd2b70bb0fdff0447d41208e | N02775223/ELSpring2017 | /code/logTemperature.py | 986 | 3.625 | 4 | #!/usr/bin/python
import os
import time
import sqlite3 as mydb
import sys
""" Log Current Time, Temperature in Celsius and Fahrenheit
Returns a list [time, tempC, tempF] """
def readTemp():
tempfile = open("/sys/bus/w1/devices/28-00044a3b10ff/w1_slave")
tempfile_text = tempfile.read()
currentTime=time.strftime('%x %X %Z')
tempfile.close()
tempC=float(tempfile_text.split("\n")[1].split("t=")[1])/1000
tempF=tempC*9.0/5.0+32.0
return [currentTime, tempC, tempF]
def logTemp():
con = mydb.connect('/home/pi/Desktop/ELSpring2017/temperature.db')
with con:
try:
[t,C,F]=readTemp()
print "Current temperature is: %s F" %F
cur = con.cursor()
#sql = "insert into TempData values(?,?,?)"
cur.execute('insert into TempData values(?,?,?)', (t,C,F))
print "Temperature logged"
except:
print "Error!!"
#print readTemp()
logTemp()
|
e7324e66da8f249f25f3dd8ea857d85a8939df7b | Lennysky/Python | /my_progs/findsymb.py | 928 | 4.25 | 4 | str1 = 'Hello, World! This is me again!'
index = str1.find('This')
print(index)
index = str1.find('again')
print(index)
#Искать с определенной позиции:
index = str1.find('m', str1.find('This'), str1.find('again'))
print(index)
# Проверить, начинается ли наша строка с этой подстроки
yesno = str1.startswith("Hello")
print(yesno)
# startswith можно реализовать 1 в 1 через метод find:
print (str1.find("Hello")==0)
# заканчивается ли строка на нашу подстроку
yesno = str1.endswith("again!")
print(yesno)
# метод endswith можно тоже реализовать через find
# если найдем подстроку "again" и оно будет равняться смещению len(str1)-len("again!"), будет true
print (str1.find("again!")==len(str1)-len("again!")) |
7b738f0cb73ecdd57d9ee7d2c2c52cd1cdbb6a56 | 4Noyis/Python | /Python/Kullanici_Girisi_2.py | 790 | 3.6875 | 4 | print("""
***********************
Kullanıcı Giriş Paneli
***********************
""")
sys_kullanici= "noyis"
sys_sifre="123"
Giris_Hakki=3
while True:
Id=input("Kullanıcı Adını Girin: ")
sifre=input("Sifrenizi girin: ")
if(Id != sys_kullanici and sifre==sys_sifre):
print("Kullanıcı Adı Hatalı..")
Giris_Hakki -=1
elif(Id==sys_kullanici and sifre !=sys_sifre):
print("Şifre Hatalı...")
Giris_Hakki-=1
elif(Id != sys_kullanici and Id !=sys_sifre):
print("Kullanıcı Adı ve Şifre Hatalı...")
Giris_Hakki -=1
else:
print("Giris Yapıldı")
break
if(Giris_Hakki==0):
print("Giriş Hakkınız Kalmamıştır..")
break |
869e11a920196831f11abfed1a447265fb76f703 | here0009/LeetCode | /Python/MaximumLevelSumofaBinaryTree.py | 1,384 | 3.953125 | 4 | """
1161. Maximum Level Sum of a Binary Tree
User Accepted:2594
User Tried:2667
Total Accepted:2633
Total Submissions:3626
Difficulty:Medium
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
Example 1:
Input: [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Note:
The number of nodes in the given tree is between 1 and 10^4.
-10^5 <= node.val <= 10^5
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxLevelSum(self, root) -> int:
val_sum = root.val
bfs = [root]
level = 1
res = 1
while len(bfs) > 0:
tmp = sum([node.val for node in bfs])
if tmp > val_sum:
res = level
val_sum = tmp
bfs_2 = []
for node in bfs:
if node.left:
bfs_2.append(node.left)
if node.right:
bfs_2.append(node.right)
bfs = bfs_2
level += 1
return res
|
81d2927ffdef01b7a80d16c3785a0e63e45879c6 | rajeshsvv/Lenovo_Back | /1 PYTHON/0 CODECAMP/16 If statement or.py | 137 | 3.9375 | 4 | is_male=False
is_tall=False
if is_male or is_tall:
print("You are male or tall or both")
else:
print("You neither male or tall") |
47a1e0aa86ab54674c468a7430a995a04cc07d1a | maiconsaraiva/estudos_python | /decorators/decoradores.py | 2,336 | 4.09375 | 4 | """
Decoradores (Decorators)
O que são?
- Decorators são funções;
- Decorators envolvem outras funções, e aprimoram seus comportamentos;
- Decorators também são exemplos de HOF (Higher Order Functions);
- Decorators tem uma sintaxe própria, usando o "@" (Syntax Sugar / Açucar Sintático)
- Não confunda Decorators com Decorator Function
- Decorator Function é a função propriamente dita que é usada para decorar a função desejada
- Decorator é o uso/aplicação do Decorator Function na função desejada.
"""
# Decorators como funções (forma não recomendada, sintaxe não recomendada, Sem Açucar Sintático)
def seja_educado(funcao):
def sendo():
print('Foi um prazer conhecer você!')
funcao()
print('tenha um ótimo dia!')
return sendo
def saudacao():
print('Seja bem vindo(a) à Geek University')
# Testando 1 (forma não recomendada)
teste = seja_educado(saudacao)
teste()
# Decoradores com Syntax Sugar / Açucar Sintático
def seja_educado_mesmo(funcao):
def sendo_mesmo():
print('Foi um prazer conhecer você!')
funcao()
print('Tenha um excelente dia!')
return sendo_mesmo
# O "@" é o chamado Açucar Sintático (Existe em Python, Java Ruby e outras que usam iterators)
@seja_educado_mesmo
def apresentando():
print('Meu nome é Pedro')
# Testando 2
apresentando()
"""
Exemplo prático:
Imagime que você um site e 4 itens de menu
|-------------------------------------------|
|Home | Serviços | Produtos | Administrativo|
|-------------------------------------------|
links:
/home
/servicos
/produtos
/admin
# Obs: Não é código funcional, é apenas um exemplo
def checa_login(request):
if not request.usuario:
redirect('/home')
usuarios_admins = ['maicon', 'glenda']
it not request.usuario in usuarios_admins:
redirect('/home')
def home(request):
return 'Pode acessar a Home'
def servicos(request):
return 'Pode acessar serviços'
def produtos(request):
return 'Pode acessar Produtos'
@checa_login # << Neste exemplo a função que dá acesso ao admin checa antes o login do usuário.
def admin(request):
return 'Pode acessar Admin'
Supondo que você queira que apenas usuários com acesso administrativos possam acessar o menu Administrativo
"""
|
53c5d149f884a8230316602815dee948b03fdee2 | kevivforever/pythonWorkspace | /derek banas/exceptions.py | 479 | 3.5 | 4 | import exceptions
class Dog:
__secret = 2
def main():
#raise Exception('JustDisagreeable')
for i in dir(exceptions):
print i
try:
zeroDivision = notHere/0
except (NameError,ZeroDivisionError), e:
print "You can't divide by zero"
print e
else:
print zeroDivision
print "This only occurs if exceptions are raised"
finally:
print "This will always occur"
if __name__ == '__main__': main()
|
baa843b91b62162dfdbdd12b3f7cca6b2174be65 | SilverMaple/LeetCode | /4.median-of-two-sorted-arrays.py | 1,524 | 3.71875 | 4 | #
# @lc app=leetcode id=4 lang=python
#
# [4] Median of Two Sorted Arrays
#
# https://leetcode.com/problems/median-of-two-sorted-arrays/description/
#
# algorithms
# Hard (25.64%)
# Total Accepted: 391.3K
# Total Submissions: 1.5M
# Testcase Example: '[1,3]\n[2]'
#
# There are two sorted arrays nums1 and nums2 of size m and n respectively.
#
# Find the median of the two sorted arrays. The overall run time complexity
# should be O(log (m+n)).
#
# You may assume nums1 and nums2 cannot be both empty.
#
# Example 1:
#
#
# nums1 = [1, 3]
# nums2 = [2]
#
# The median is 2.0
#
#
# Example 2:
#
#
# nums1 = [1, 2]
# nums2 = [3, 4]
#
# The median is (2 + 3)/2 = 2.5
#
#
#
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums = sorted(nums1 + nums2)
length = len(nums)
if length % 2 == 1:
return nums[length//2]
else:
return (nums[length//2-1] + nums[length//2]) / 2.0
# sorted_joined = sorted(nums1 + nums2)
# if len(sorted_joined) % 2 == 0:
# index = int(len(sorted_joined) / 2)
# return (sorted_joined[index] + sorted_joined[index-1])/2
# else:
# index = (int(len(sorted_joined)/2))
# return sorted_joined[index]
# l1 = [1, 3, 4, 5, 8]
# l2 = [2, 1, 4]
l1 = [1, 2]
l2 = [3, 4]
s = Solution()
print(s.findMedianSortedArrays(l1, l2))
|
b3de59228d5c1d0f878536d85c3e7d9b32c5b87d | liuqun/py | /可爱的Python/cdctools.py | 197 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def ListFileSystemTree(dir):
tree = ""
for root, dirs, files in os.walk(dir):
tree += ("%s;%s;%s\n" % (root, dirs, files))
print(tree)
|
e7cbd486b090698d66acebf28f5f6725cf5c7d1d | matthewfowles/python-course | /caser.py | 631 | 4.03125 | 4 | #!/usr/bin/python3
#
# A Truly Awesome Program
# caser.py
#
# by: Matthew Fowles
#
#
def capital(e) :
return e.capitalize();
def titilate(e) :
return e.title()
def up(e) :
return e.upper()
def down(e) :
return e.lower()
def exit(e):
return 'Goodbye for now!'
matrix = {
"capitalize": capital,
"title": titilate,
"upper": up,
"lower": down,
"exit": exit
}
if __name__ == "__main__":
while True:
function = input('Enter a function name (capitalize, title, upper, lower, or exit): ')
string = input('Enter a string: ')
result = matrix[function](string)
print(result)
if function == 'exit':
break |
bf3cd4bdac42b8720c0e13a5670e96e68c1e32da | AmilaSamith/snippets | /Python-data-science/for_loop.py | 1,162 | 4.40625 | 4 | # For-loop condition
"""
for-loop
--------------------------------
for (iter) in (iterable):
(code to be executed while have iter in iterable)
"""
for num in [1,2,3,4]:
print(num)
# range() function
"""
range(start*,stop,step*) - * optional params
"""
for num in range(2,10,2):
print(num)
# Loop control statements
""" break keyword """
for num in range(10):
if num == 5:
break # break the loop when if condition is satisfied
print(num)
""" continue keyword """
for num in range(10):
if num == 5:
continue # continue to next iteration skipping the code below.
print(num)
"""
pass keyword
----------------------------------------------------------------
This is used as a placeholder when running the code.
Used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
Examples
--------
def myfunction():
pass
for x in [0, 1, 2]:
pass
""" |
c0baa889c7c76925973d64d652fbfb3e71ce6eed | Busymeng/MyPython | /ClassNote/08_Set_Student.py | 4,723 | 3.640625 | 4 | ################################################################
## Sets
################################################################
################################################################
## Essential ideas about set
"""
* Two interesting features of a set
- You can store only one example of an element in a set. No duplicates
are allowed. Attemps to store a duplicate is ignored.
- Special set operators (like union, intersection, etc) are possible
on a set.
"""
################################################################
## Creating a set
"""
* Use {} like a dictionary, but only if the values are not key:value pairs
(no colon in the elements).
* The set() constructor can create a set from any iterable.
"""
## Empty set is essential
"""
* You can't create an empty set with {}, as that is an empty dictionary.
* Empty set is made with set()
"""
################################################################
## Basic Features about Set
"""
* It is a mutable data structure.
* It allows for storage of mixed types.
* It likes a dictionary that is not a sequence.
- There is no order to a set.
- Unlike a dictionary, there is no [] operation of any kind on a set.
"""
################################################################
## Set Operations
"""
* len() for length
* in: membership
* Intersection: &
* Union: |
* Difference: - (order is important)
* Symmetric difference: ^ (opposite of intersection)
* Subset: <
* Superset: >
* Others: add(), discard(), clear(), remove()
"""
################################################################
## Set Application: Common and Unique Words in Documents
"""
* Lets' look at two documents, the Gettysburg Address and the Declaration
of Independence and look for:
- common words in both documents
- unique words in both documents
- maybe some other fun stuff
"""
## Recycling get_words() from the word frequency example
"""
* We wrote a function get_words() that collected the words of a text file
into a dictionary.
* We are going to use that code and change it slightly to gather sets of
unique file words.
"""
################################################################
## More about Comprehension
"""
* Comprehensions are a convenient way to build collections.
* One of the most common tasks we as Python programmers need to do is:
- examine every element of a data structure (a list, a dictionary, a set)
- perform some operation on each element
- collect the resulting elements together into another data structure
* Python has a group of shortcuts called comprehension which make the
process easier.
- while shortcuts are short, they can make things more difficult to read
- if you do things the long way, that's fine. Shortcuts are something
you can pick up as you become more experienced.
- One good thing about comprehensions. They are fast. If performance ever
become an issue, a comprehension version of the same code is typically
a lot faster.
"""
################################################################
## General Comprehension
"""
* A Comprehension has 4 parts:
- what kind of data structure is going to be generated (indicated by the
enclosing elements).
- what expression is being collected.
- what is being iterated over.
- an optional condition that determines if an element is collected.
[element**2 for element in my_list if element%2==0]
"""
################################################################
## Set and Dictionary Comprehension
"""
* Enclose the comprehension in curly braces {}.
- You make a dictionary if the elements are key:value pairs.
- You make a set if you just collection elements.
"""
################################################################
## Ternary operator
"""
* The expressions you collect in your comprehensions have to be just
expressions.
- These are Python statements r=that return a value. That exclude control
statements as things to collect.
* However, at least for very simple selection alternatives, there is a
special form of an if expression called a ternary (meaning three parts)
expression.
- It is in fact an expression and returns one of two values depending
on the condition.
"Hi Mother" if age_int > 18 else "Hi Mom"
"""
|
81d322872b53934afacb6d5abf7656e57bcae833 | chenxu0602/LeetCode | /1862.sum-of-floored-pairs.py | 1,506 | 3.734375 | 4 | #
# @lc app=leetcode id=1862 lang=python3
#
# [1862] Sum of Floored Pairs
#
# https://leetcode.com/problems/sum-of-floored-pairs/description/
#
# algorithms
# Hard (27.19%)
# Likes: 188
# Dislikes: 19
# Total Accepted: 4.1K
# Total Submissions: 15K
# Testcase Example: '[2,5,9]'
#
# Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for
# all pairs of indices 0 <= i, j < nums.length in the array. Since the answer
# may be too large, return it modulo 10^9 + 7.
#
# The floor() function returns the integer part of the division.
#
#
# Example 1:
#
#
# Input: nums = [2,5,9]
# Output: 10
# Explanation:
# floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
# floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
# floor(5 / 2) = 2
# floor(9 / 2) = 4
# floor(9 / 5) = 1
# We calculate the floor of the division for every pair of indices in the array
# then sum them up.
#
#
# Example 2:
#
#
# Input: nums = [7,7,7,7,7,7,7]
# Output: 49
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^5
# 1 <= nums[i] <= 10^5
#
#
#
# @lc code=start
from collections import Counter
import itertools
class Solution:
def sumOfFlooredPairs(self, nums: List[int]) -> int:
incs, counter = [0] * (max(nums) + 1), Counter(nums)
for num in counter:
for j in range(num, len(incs), num):
incs[j] += counter[num]
quots = list(itertools.accumulate(incs))
return sum(quots[num] for num in nums) % (10**9 + 7)
# @lc code=end
|
ee627d8ea17043da565e6bc293e511c46e1e9b08 | hector-han/leetcode | /dp/prob0122.py | 1,402 | 3.671875 | 4 | """
122. 买卖股票的最佳时机 II
easy
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
dp[i][0]: 第i天不持有股票
dp[i][1]: 第i天持有股票
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + price[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - price[i])
"""
dp_i_0 = 0
dp_i_1 = -float('inf')
for p in prices:
tmp = dp_i_0
dp_i_0 = max(dp_i_0, dp_i_1 + p)
dp_i_1 = max(dp_i_1, tmp - p)
return dp_i_0
if __name__ == '__main__':
prices = [7,1,5,3,6,4]
sol = Solution()
assert sol.maxProfit(prices) == 7
|
bd25e46030449c6207dcae1d6cfe5d66210232fc | TehraniZadehAli/Python | /ChangeVars.py | 416 | 4.25 | 4 | #Define a function for changing value of two variables
def changevar(a,b):
a = a + b #Assign a+b to a
b = a - b #Assign a-b to b
a = a -b #Assign a-b to a
print("a2 is : " ,a) #Printing new value for a
print("b2 is : " ,b) #Printing new value for b
a = int(input("a")) #Getting number from user
b = int(input("b"))
print(changevar(a,b)) #Call the function and print output
|
9bf9436abd3c99293b3182acb225f6ed6850f2ac | DT021/data_structures_and_algorithms | /basic_algorithms/euclid_gcd.py | 185 | 3.796875 | 4 | def gcd(a, b):
rem = a % b
while(rem != 0):
a = b
b = rem
rem = a%b
return b
print(gcd(20,8))
print(gcd(36,14))
print(gcd(99,11))
print(gcd(173,57)) |
7287d3c7e9b5724b15b5025eb19a7e5a727b8f55 | johnsonjosev/Algorithmic_Toolbox | /Assignment_bootstrap/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py | 1,018 | 4.0625 | 4 | # Uses python3
import sys
def total_sum_of_ascending_series(k):
# series_sum = 1 + 2 + ... + k = k * ( k + 1) /2
# this must be a integer, so we adopt integer division here.
series_sum = k*(k+1)//2
return series_sum
def optimal_summands(n):
summands = []
#write your code here
upper_bound = int( (2*n)**(1/2)+1 )
for k in range(1, upper_bound):
current_sum = total_sum_of_ascending_series( k )
next_sum = total_sum_of_ascending_series( k+1 )
if current_sum <= n < next_sum:
delta = n - current_sum
# make a ascending series from 1 to k (including k)
summands = list( range(1, k+1) )
# compensate final term for delta to meets the value of n
summands[-1] += delta
break
return summands
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
summands = optimal_summands(n)
print(len(summands))
for x in summands:
print(x, end=' ')
|
094667162c817261f4a96f2b508a73822da979a3 | aitutor22/tetris | /test.py | 3,242 | 3.65625 | 4 | from blocks import Block
from tetris import *
board = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# assert detect_collisions(board, None, [(1, 14), (2, 15), (1, 15), (2, 16)]) == True
# assert detect_collisions(board, None, [(1, 13), (2, 14), (1, 14), (2, 15)]) == True
# print(valid_placement_helper(board, Block("t", 0, 0, 0)))
# print(valid_placement_helper(board, Block("t", 1, 0, 0)))
# print(valid_placement_helper(board, Block("t", 2, 0, 0)))
# print(valid_placement_helper(board, Block("t", 3, 0, 0)))
# for b in valid_placement(board, Block("t", 0, 0, 0), [0, 16]):
# print(b.get_coords())
assert space_above_occupied(board, 2, 4) == False
# board = [[0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1, 1, 1], [0, 1, 1, 0, 1, 0, 1, 1], [0, 1, 1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]]
# block = Block("o")
# print_matrix(board)
# for b, bl in potential_moves(board, block):
# print(bl.x, bl.y)
# board = [[0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# # block = Block("o")
# # print_matrix(board)
# # for b, bl in potential_moves(board, block):
# # print(bl.x, bl.y)
app = TetrisApp([-1.73952898, -1.35679522, -3.89298252, -1.2184164], True, board)
app.run()
print(app.score)
# board = [[0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# block = Block("l", 3, 6, 1)
# print(block.value)
# print_matrix(board)
# print("******")
# print(detect_collisions(board, block))
# temp_board = add_block_to_board(board, block)
# print_matrix(temp_board)
# print(potential_moves(board, block))
# print(valid_placement_helper(board, block))
# print(detect_collisions(board, Block("l", 3, 6, 0)))
# (6, 2)
# print(len(potential_moves(board, block)))
# for b, bl in potential_moves(board, block):
# print(bl.x, bl.y)
|
2f9ab52a9697cb5f363239410062f99d644a7581 | Sebas1130/Python_Ejemplos | /proyecto5/node_based_queue.py | 1,235 | 4.03125 | 4 |
class TwoWayNode():
def __init__(self,data=None,next=None,previous=None) -> None:
self.data = data
self.next = next
self.previous = previous
class Queue:
def __init__(self) -> None:
self.head = None
self.tail = None
self.count = 0
def enqueue(self, data):
new_node = TwoWayNode(data,None,None)
if self.head is None:
self.head = new_node
self.tail = self.head
else:
new_node.previous = self.tail
self.tail.next = new_node
self.tail = new_node
self.count += 1
def dequeue(self):
current = self.head
if self.count == 1:
self.count -= 1
self.head = None
self.tail = None
elif self.count > 1:
self.head = self.head.next
self.head.previous = None
self.count -= 1
return current.data
"""
from node_based_queue import Queue
food = Queue()
food.enqueue('eggs')
food.enqueue('ham')
food.enqueue('spam')
print(food.head.data)
print(food.head.next.data)
print(food.tail.data)
print(food.tail.previous.data)
print(food.count)
print(food.dequeue())
print(food.head.data)
""" |
fd874e235234ea4374088cca253d328fcca60d5d | ZU3AIR/DCU | /Year2/ca268Labs/Revision/recursive_sum.py | 116 | 3.671875 | 4 | def sumto(a, b):
if int(a) == int(b):
return a
else:
return a + (sumto((a + 1), b))
print(sumto(4, 10)) |
56a0bf355f4259157ca4260be0cef75c4c3c7899 | thonyeh/Numerical-analysis-2 | /crank-nicolson k=0.001, h=0.1 (r=0.1).py | 2,302 | 3.640625 | 4 | from math import *
from time import sleep
from Tkinter import *
from numpy import *
import matplotlib.pyplot as plt
def matriz(n,m):#DEFINA LA MATRIZ
M=[]
for i in range(n):
M.append([float(0)]*m)
return M
def vector(n): #DEFINE EL VECTOR
v=[]
for i in range(n):
v.append(float(0))
return v
def puntos(xG,uG,N,k):
plt.title('x vs u(x,t)')
for j in range(N+1):
plt.plot(xG,uG[j],'b--')
plt.axis([0,1,-1,1])
#f='sin(pi*x)*'
#c=exp((-1)*(pi**2)*j*k)
#f+=str(c)
#x=arange(float(0),float(1),0.00001)
#f_x=eval(f)
#plt.plot(x,f_x,'r--')
plt.show()
print 'Metodo de Crank-Nicolson'
print ''
print 'k=0.001, h=0,1'
print 'r=0.1'
#DATOS
l=float(1)
alfa=float(1)
m=10
N=50
w=vector(m+1)
L=vector(m)
u=vector(m-1)
#paso 1
h=l/float(m)
k=0.001
lamb=(alfa**2)*k/(h**2)
w[m]=0
#paso 2
for i in range(1,m):
w[i]=sin(pi*i*h) #w[i]=f(i*h)
#paso 3
L[1]=1+lamb
u[1]=(-1)*lamb/(2*L[1])
#paso 4
for i in range(2,m-1):
L[i]=1+lamb+lamb*u[i-1]/2
u[i]=(-1)*lamb/(2*L[i])
#paso 5
L[m-1]=1+lamb+lamb*u[m-2]/2
#paso 6
xG=[]
for i in range(m+1):
xG.append(i*h)
uG=matriz(N+1,m+1)
for i in range(m+1):
uG[0][i]=sin(pi*xG[i])
for j in range(1,N+1):
#paso 7
t=j*k
z=vector(m)
z[1]=((1-lamb)*w[1]+(lamb/2)*w[2])/L[1]
#paso 8
for i in range(2,m):
z[i]=((1-lamb)*w[i]+(lamb/2)*(w[i+1]+w[i-1]+z[i-1]))/L[i]
#paso 9
w[m-1]=z[m-1]
#paso 10
i=m-2
while i>=1:
w[i]=z[i]-u[i]*w[i+1]
i=i-1
#paso 11
#print 'xi wi---> u(xi,t)'
#print '0 0'
for i in range(1,m):
uG[j][i]=w[i]
uG[j][m]=0
#for i in range(1,m):
# x=i*h
#print x,' ',w[i]
#print '0 0'
for j in range(N+1):
if j==N:
print ''
t=j*k
print 'xi'.rjust(30),'w(i,%f)'.rjust(30)%t,'u(xi,t)'.rjust(30),'|u(xi,t)-w(i,%f)|'.rjust(30)%t
for i in range(0,m):
print str(xG[i]).rjust(30),repr(uG[j][i]).rjust(30),repr(exp((-1)*(pi**2)*(t))*sin(pi*xG[i])).rjust(30),repr(abs(exp((-1)*(pi**2)*(t))*sin(pi*xG[i])-uG[j][i])).rjust(30)
print str(xG[m]).rjust(30),repr(uG[j][m]).rjust(30),'0'.rjust(30)
puntos(xG,uG,N,k)
sleep(13)
|
8040ab7d28731a80dc03f0fd8b837086b81e5b04 | Yang-Jianxing/- | /第三题.py | 241 | 3.78125 | 4 | #第三题
print("根据够的年龄算出您的大概年龄")
a = input("请输入您的狗的年龄:")
a = float(a)
if 0<a<=2:
print(a*10.5)
elif a>2:
print(21+(a-2)*4)
elif a<=0:
print("您输入的数字有误!") |
82989f4ca6425fd1775ce7a351bb8097e28860f6 | JSitter/Tweet-Generator | /rearrange.py | 260 | 3.734375 | 4 | import sys
from random import randint
def randomize_words(words):
#create a set
words = set()
while (len(words) != len(sys.argv)-1):
randomNum = randint(1, len(sys.argv)-1)
words.add(sys.argv[randomNum])
print(" ".join(words)) |
67c55f2fb7453b74f7e8422ba5e68af062ea113f | iamyoona/sparta_algorithm | /week_1/homework/02_find_count_to_turn_out_to_all_zero_or_all_one.py | 381 | 3.75 | 4 | input = "011110"
def find_count_to_turn_out_to_all_zero_or_all_one(string):
temp_array = [string[0]]
for i in range(1, len(string)):
if string[i] != string[i-1]:
temp_array.append(string[i])
result = min(temp_array.count('0'), temp_array.count('1'))
return result
result = find_count_to_turn_out_to_all_zero_or_all_one(input)
print(result) |
e066d7dcc822eb7e5cea0c19de70cd536339e4bb | zpoint/Reading-Exercises-Notes | /core_python_programming/8/8-8.py | 159 | 4.0625 | 4 | def Factorial(num):
N = 1
for i in range(1,num+1):
N *= i
return N
print Factorial(int(raw_input('Please enter a number to N!:\n'))) |
d8fe35d411f2414b46368447967b1184ce6c606a | DikshaRai1/FST-M1 | /Python/Activities/Activity9.py | 584 | 4.1875 | 4 | #Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list.
list1=[1,2,3,4]
list2=[6,7,8,9]
list3=[]
for number in list1: #Adding odd numbers from list1 to list3
if (number%2)!=0 :
list3.append(number)
for number in list2:
if (number%2)==0 : #Adding even numbers to list3 from list2
list3.append(number)
print(list3) #Printing list3 |
e8920df89ecc7c0d3c88874720b87f899ae26256 | Thaistav/introduction-to-python | /list_01/exp05.py | 174 | 4.21875 | 4 | #Faça um Programa que converta metros para centímetros.
m=float(input('Digite a medidade em metros '))
c=m*100
print('O valor corresponde a {} centimentros'.format(c))
|
8bfe1acc2011d3966ea68c72c3728a770b7a486d | malachyenglish1/selwood-python | /practice-exercises/exponent.py | 163 | 3.5625 | 4 | b_input = float(input("Enter a base: "))
exp_input = float(input("Enter an exponent: "))
print(f"{b_input} to the power of {exp_input} = ", b_input ** exp_input)
|
c6ea18bc92a31d272a07c6015536adcd46a7d555 | tommaso1311/sNNake | /src/food.py | 195 | 3.546875 | 4 | import numpy as np
class food:
def __init__(self):
"""
Class used to create food
Attributes
----------
position : array
position of food
"""
self.position = np.array([0, 0]) |
1d4b3a95d87ed91c06f8c5f01c3d26faf7735c0d | lishuchen/Algorithms | /lintcode/96_Partition_List.py | 849 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
# write your code here
if not head:
return None
small_head = small = ListNode(-1)
large_head = large = ListNode(-1)
while head:
if head.val < x:
small.next = head
small = small.next
else:
large.next = head
large = large.next
head = head.next
large.next = None
small.next = large_head.next
return small_head.next
|
85c46d8edef63c48b396d47ae09bcb5f657b78d6 | gomesfilipe/curso-em-video-python | /ex014.py | 144 | 3.90625 | 4 | celsius = float(input('Temperatura em °C '))
farenheit = 9 * celsius / 5 + 32
print('Temperatura em farenheit: {:.2f} °F'. format(farenheit))
|
598de55612f90f476e8cdbb631942995067e9387 | aastronautss/programming-exercises | /210-small-problems/easy_2.py | 2,589 | 3.8125 | 4 | import random
import re
import math
from functools import reduce
# Ddaaiillyy ddoouubbllee
def crunch(string):
new_string = ''
for idx, char in enumerate(string):
if idx == 0 or char != string[idx - 1]:
new_string += char
return new_string
# Bannerizer
def print_in_box(string):
length = len(string)
print('+-{}-+'.format('-' * length))
print('| {} |'.format(' ' * length))
print('| {} |'.format(string))
print('| {} |'.format(' ' * length))
print('+-{}-+'.format('-' * length))
# Stringy Strings
def rotate(items):
items.append(items.pop(0))
def stringy(num):
values = ['1', '0']
output = ''
for i in range(num):
output += values[0]
rotate(values)
return output
# Fibonacci Number Location by Length
# Right Triangles
def triangle(height):
for row in range(1, height + 1):
print(('*' * row).rjust(height))
# Madlibs
def madlibs():
noun = input('Enter a noun: ')
verb = input('Enter a verb: ')
adjective = input('Enter an adjective: ')
adverb = input('Enter an adverb: ')
sentences = [
'Do you {verb} your {adjective} {noun} {adverb}? That\'s hilarious!',
'The {adjective} {noun} {verb}s {adverb} over the lazy dog.',
'The {noun} {adverb} {verb}s up {adjective} Joe\'s turtle.'
]
print(random.choice(sentences).format(noun=noun, verb=verb, adjective=adjective, adverb=adverb))
# Double Doubles
def is_double_number(num):
num_str = str(num)
center = int(len(num_str) / 2)
return num_str[0:center] == num_str[center:]
def twice(num):
return num if is_double_number(num) else 2 * num
# Grade Book
def avg(*nums):
return reduce(lambda mem, val: mem + val, nums) / len(nums)
def get_grade(*scores):
average = avg(*scores)
if average >= 90:
return 'A'
elif average >= 80:
return 'B'
elif average >= 70:
return 'C'
elif average >= 60:
return 'D'
else:
return 'F'
# Clean Up the Words
def cleanup(string):
return re.sub(r'[^A-Za-z]+', ' ', string)
# Which Century is That
def is_special_th_suffix(num):
return num % 100 in (11, 12, 13)
def nth_suffix(num):
special_suffixes = { 1: 'st', 2: 'nd', 3: 'rd' }
if is_special_th_suffix(num):
return 'th'
last_digit = num % 10
if last_digit in special_suffixes:
return special_suffixes[last_digit]
else:
return 'th'
def century(year):
century_num = math.ceil(year / 100)
return '{}{}'.format(century_num, nth_suffix(century_num))
|
60271a82d5bcf3aecbd82eec5fb651ed460bee26 | chuanyedadiao/Python-Practice | /course/11/test_cities.py | 432 | 3.71875 | 4 | import unittest
from city_functions import city_combine
class CityTestCase(unittest.TestCase):
def test_city_country(self):
city_nation = city_combine('changde','china')
self.assertEqual(city_nation,'Changde,China')
def test_city_country_population(self):
city_nation = city_combine('changde','china',80000)
self.assertEqual(city_nation,'Changde,China - population 80000')
unittest.main()
|
2363650a0a177b169836645dbba27c189bb474c5 | synerjay/arithmetic-formatter | /arithmetic_arranger.py | 2,493 | 3.890625 | 4 | import re
# import regex for checks
# Input is arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
# Output is
# 32 3801 45 123
# + 698 - 2 + 43 + 49
# ----- ------ ---- -----
def arithmetic_arranger(problems, solve = False):
#First make variables to make the final product
if (len(problems) > 5):
return "Error: Too many problems."
first = ""
second = ""
lines = ""
sumx = ""
string = ""
for problem in problems:
if(re.search(r"[^\s0-9.+-]", problem)):
if (re.search("[/]", problem) or re.search("[*]", problem)):
return "Error: Operator must be '+' or '-'."
return "Error: Numbers must only contain digits."
firstNumber = problem.split(" ")[0]
operator = problem.split(" ")[1]
secondNumber = problem.split(" ")[2]
# Another check to see if number length is greater than or equal to 5
if(len(firstNumber) >= 5 or len(secondNumber) >= 5):
return 'Error: Numbers cannot be more than four digits.'
# Try to solve the sum IF the bool is true in the second argument
sum = ""
if (operator == "+"):
sum = str(int(firstNumber) + int(secondNumber))
elif(operator == "-"):
sum = str(int(firstNumber) - int(secondNumber))
length = max(len(firstNumber), len(secondNumber)) + 2
top = str(firstNumber).rjust(length) # justifies the number to the right
bottom = operator + str(secondNumber).rjust(length - 1) #since operator here we subtract length by 1
line = ""
res = str(sum).rjust(length)
for _ in range(length):
line += "-"
# making the dash lines between the answers and the operators
# To prevent spacing on the last problem we must have a condition
#[-1] indicates the last problem item on the problem array
# Because we are in a loop, we must connect all the lines in every iteration
if problem != problems[-1]:
first += top + ' '
second += bottom + ' '
lines += line + ' '
sumx += res + ' '
else:
first += top
second += bottom
lines += line
sumx += res
# Check to see if solve argument is TRUE,
# This should be outside the loop
if solve:
string = first + "\n" + second + "\n" + lines + "\n" + sumx
else:
string = first + "\n" + second + "\n" + lines
return string
|
b9da0f24d9a23354c8fad9083653decd344c2b76 | RRoundTable/CPPS | /DP/Combination_Sum_III.py | 1,688 | 3.8125 | 4 | '''
link: https://leetcode.com/problems/combination-sum-iii/
Find all valid combinations of k numbers that sum up to n such that the following conditions are true:
Only numbers 1 through 9 are used.
Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
Example 3:
Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations. [1,2,1] is not valid because 1 is used twice.
Example 4:
Input: k = 3, n = 2
Output: []
Explanation: There are no valid combinations.
Example 5:
Input: k = 9, n = 45
Output: [[1,2,3,4,5,6,7,8,9]]
Explanation:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
There are no other valid combinations.
Constraints:
2 <= k <= 9
1 <= n <= 60
'''
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
def backtracking(target, k, count, curr):
nonlocal res
if target < 0 or k < 0 or curr > 10: return
if target == 0 and k == 0:
res.append([i for i in range(1, 10) if count & 2 ** i])
return
backtracking(target - curr, k - 1, count | 2 ** curr, curr + 1)
backtracking(target, k, count, curr + 1)
return res
backtracking(n, k, 1 << 10, 1)
return res |
6c50549858a7433dad4f2294958d2f9a0f5f01be | lichengchengchloe/leetcodePracticePy | /ReverseInteger.py | 744 | 3.828125 | 4 | # -*- coding: UTF-8 -*-
# https://leetcode-cn.com/problems/reverse-integer/
def reverse(x):
"""
:type x: int
:rtype: int
"""
res = 0
while x!=0:
# Python3 的取模运算在 x 为负数时也会返回 [0, 9) 以内的结果,因此这里需要进行特殊判断
tmp = x%10
if x<0 and tmp>0:
tmp = tmp-10
# 同理,Python3 的整数除法在 x 为负数时会向下(更小的负数)取整,因此不能写成 x //= 10
x = (x-tmp)//10
if (res==214748364 and tmp>7) or (res>214748364):
return 0
if (res==-214748364 and tmp<-8) or (res<-214748364):
return 0
res = res*10 + tmp
return res
x = 0
print(reverse(x))
|
eba3269d3ccf99ab63199764671f57a18f7928b2 | elsayed-issa/2021-task1 | /evaluation/evallib.py | 666 | 3.59375 | 4 | """Evaluation functions for sequence models."""
from typing import Iterator, List, Tuple
Labels = List[str]
def wer(correct: int, incorrect: int) -> float:
"""Computes WER."""
return 100 * incorrect / (correct + incorrect)
def tsv_reader(path: str) -> Iterator[Tuple[Labels, Labels]]:
"""Reads pairs of strings from a TSV filepath."""
with open(path, "r") as source:
for line in source:
(gold, hypo) = line.split("\t", 1)
# Stripping is performed after the fact so the previous line
# doesn't fail when `hypo` is null.
hypo = hypo.rstrip()
yield (gold.split(), hypo.split())
|
8825e74e03b84d848a79074066116d004816825d | CMSTrackerDPG/TkDQMDoctor | /utilities/luminosity.py | 894 | 3.515625 | 4 | from decimal import Decimal
from utilities.manip import strip_trailing_zeros
def format_integrated_luminosity(int_luminosity):
"""
Example:
>>> format_integrated_luminosity(Decimal("0.000000266922"))
'0.267 µb⁻¹'
>>> format_integrated_luminosity(Decimal("1.12345678901234567890"))
'1.123 pb⁻¹'
:param int_luminosity: integrated luminosity value in 1/pb^-1
:return: Formatted luminosity with 3 decimal points precision
"""
value = Decimal(int_luminosity)
if '{:.3f}'.format(value) == "0.000":
value = Decimal("1E6") * value
value_string = "{:.3f}".format(value)
formatted_value = strip_trailing_zeros(value_string)
return "{} µb⁻¹".format(formatted_value)
value_string = "{:.3f}".format(value)
formatted_value = strip_trailing_zeros(value_string)
return "{} pb⁻¹".format(formatted_value)
|
ffd6cdd51431b4cbf79a0be1e24b73e717cb633f | fredmorcos/attic | /Projects/PlantMaker/archive/20100420/plant.py | 3,587 | 3.734375 | 4 | """
This module provides the Plant and Machine classes.
CraneMoveTime is the time a crane takes from one Machine to another in the
Plant.
"""
from xml.dom import minidom
from extra import *
CraneMoveTime = 1
class Machine(object):
"""
Provides the implementation of a Machine in a Plant.
"""
def __init__(self, name, quantity = 1, minDelay = 0, canUnhook = False):
"""
name is the unique Machine name.
minDelay is the minimum (constant) delay a Machine introduces for any
Order.
canUnhook is whether a crane can leave an Order at this Machine or not.
quantity is the number of available machines of this type (name) in
the Plant.
"""
object.__init__(self)
assert name != None
assert name != ""
assert quantity >= 1
assert minDelay >= 0
self.quantity = quantity
self.minDelay = minDelay
self.canUnhook = canUnhook
self.name = name
def toXml(self, xmlDoc):
"""
Exports the Machine instance to an XML tree node and returns the node
instance. xmlDoc to used to create the XML tree node element.
"""
node = xmlDoc.createElement("machine")
node.setAttribute("name", self.name)
node.setAttribute("quantity", str(self.quantity))
node.setAttribute("minDelay", str(self.minDelay))
node.setAttribute("canUnhook", str(self.canUnhook))
return node
@staticmethod
def fromXml(element):
"""
Creates a Machine instance from XML node tree element and returns it.
"""
return Machine(
name = element.getAttribute("name"),
quantity = int(element.getAttribute("quantity")),
minDelay = int(element.getAttribute("minDelay")),
canUnhook = strToBool(element.getAttribute("canUnhook"))
)
class Plant(object):
"""
Provides the implementation of a Plant (factory) with a list of Machine
instances.
"""
def __init__(self):
"""
machines is a list of ordered Machine instances (by sequence in Plant).
minProcTime is the minimum (constant) processing time for any Order
going through the Plant. This is the summation of all the times between
every two Machine instances in the Plant.
"""
object.__init__(self)
self.machines = []
def toXml(self):
"""
Creates an XML tree node from the Plant instance and returns it.
"""
domImp = minidom.getDOMImplementation()
xmlDoc = domImp.createDocument(None, "plant", None)
for m in self.machines:
xmlDoc.documentElement.appendChild(m.toXml(xmlDoc))
return xmlDoc.documentElement
def toXmlFile(self, filename):
"""
Saves the Plant instance to an XML file.
"""
file = open(filename, "w")
file.write(self.toXml().toprettyxml())
file.close()
@staticmethod
def fromXml(xmlDoc):
"""
A static method that loads a Plant instance (and returns it) from
an XML document. xmlDoc is the document instance.
"""
plant = Plant()
for e in xmlDoc.getElementsByTagName("machine"):
plant.addMachine(Machine.fromXml(e))
return plant
@staticmethod
def fromXmlFile(filename):
"""
A static methods that loads a Plant instance (and returns it) from
an XML file (str filename).
"""
file = open(filename, "r")
doc = minidom.parse(file)
plant = Plant.fromXml(doc)
file.close()
return plant
def addMachine(self, machine):
"""
Add a Machine instance to the Plant. If the Machine instance or its
name is already in the list of machines, an Exception will be thrown.
After adding a Machine instance, minProcTime is updated.
"""
assert machine not in self.machines
for m in self.machines:
if m.name == machine.name:
raise Exception("Machine name already in plant")
self.machines.append(machine)
|
4e24ecda8559a40f93c55ac55a4f9a8993db81e9 | sai-byui/NEO2D | /pathfinder.py | 9,070 | 3.8125 | 4 | from agent import Agent
class Pathfinder(Agent):
"""uses the A* path finding algorithm to determine the red_ai_pilot's movement"""
def __init__(self):
"""sets up path finding variables for use in the A* algorithm"""
super(Pathfinder, self).__init__("pathfinder")
# nodes which we know the f cost for but have not yet searched
self.open_list = []
# nodes whose connections we have searched
self.closed_list = []
# we will stick our chain of nodes that form our final path in here
self.final_path_list = []
# the list of all the nodes we start with in our graph
self.unvisited = []
self.end_node = None
self.current_node = None
self.target = None
self.red_coordinate = self.ask("neo", "red_coordinate")
self.GRID_INCREMENT = self.ask("map_builder", "GRID_INCREMENT")
self.NODE_STEP = self.ask("map_builder", "node_step")
self.start_node = None
self.start_node_index = None
def determine_starting_point(self):
"""finds the node closest to NEO's position and sets it as the start node"""
self.target = self.ask("neo", "red_coordinate")
self.determine_goal()
return self.end_node
def determine_goal(self):
"""finds the closest node to the given target coordinates"""
# for each node in our graph, we check the coordinates to see if it's "close enough" to our goal coordinates
for node in self.unvisited:
if self.GRID_INCREMENT * self.NODE_STEP >= abs(node.x - self.target[0]) and \
self.GRID_INCREMENT * self.NODE_STEP >= abs(node.y - self.target[1]):
print("matched coordinates with node# " + str(node.name))
# use the matched node as the end node which we find the path to
self.end_node = node
# our next start node will be our current end_node for the next time we find a path
self.start_node_index = self.unvisited.index(node)
break
def find_path(self, target_coordinates):
"""uses the A* algorithm to find the best path from starting point to the end position
key variables:
unvisited: the list of all the nodes we start with in our graph
closed_list: nodes whose connections we have searched
open_list: nodes which we know the f cost for but have not yet searched
The find_path method works in the following steps:
1. the first node in your open_list becomes your current node whose connections you are searching
2. remove the current node from the open_list and place it into the closed_list
3. for each connection to the current node, find the connected node in our unvisited list and determine its F cost
4. once a node's F cost is determined, sort it into the open_list from lowest F cost to Highest
5. when all the current node's connections have been checked, repeat steps 1 - 4 until your end goal is reached
"""
# ask the map_builder for the entire graph of nodes which we will search through
self.unvisited = self.ask("map_builder", "node_list")
if self.start_node_index is None:
self.start_node = self.determine_starting_point()
else:
self.start_node = self.unvisited[self.start_node_index]
# find our end node based on the passed coordinates
self.target = target_coordinates
self.determine_goal()
# reset our lists as empty
self.open_list = []
self.closed_list = []
self.final_path_list = []
# we set our start node as the current node and search it's connections
self.closed_list.append(self.start_node)
self.current_node = self.start_node
# if we happen to already be at our end node, put our start node as the only one in the list and return
if self.start_node.name == self.end_node.name:
self.final_path_list.append(self.start_node)
return
# remove the starting node from our list
self.unvisited.remove(self.start_node)
# this will be false until we reach our goal
path_found = False
while not path_found:
# loop through all of connections in our node object (ex. "190", "194", "198")
for connection in self.current_node.connections:
if path_found:
break
# find that corresponding node in the list of our unvisited nodes
for unvisited_node in self.unvisited:
if unvisited_node.name == connection:
# once we find a match, we pass it in to our determine_cost method to find its f cost
determine_cost(self.current_node, unvisited_node, self.end_node)
# print("unvisited Node " + str(unvisited_node.name) + " f cost: " + str(unvisited_node.f))
# check to see if we have reached our goal node
if self.end_node.name == unvisited_node.name:
self.end_node = unvisited_node
self.end_node.previous_node = self.current_node
path_found = True
break
# now move the node from our unvisited list to our open list since we know its f cost
self.transfer_open_node(unvisited_node)
if not path_found:
# now we move on the the first node found in our open list, this is the most likely candidate
# based on it's f cost.
self.current_node = self.open_list.pop(0)
self.closed_list.append(self.current_node)
# Once we have found the path to the end node, will will place the linked nodes into a list to make it easier
# to read our path. this setup is not necessary as we could just access the "previous_node" field directly, but
# for this example we will organize it into a list
while self.end_node.name != self.start_node.name:
# insert the current node of our chain into the front of the list
self.final_path_list.insert(0, self.end_node)
# if our current node does not have a previous node to point to, exit the loop
if not self.end_node.previous_node:
break
# move to the previous connected node
self.end_node = self.end_node.previous_node
# finally insert our start_node
self.final_path_list.insert(0, self.start_node)
return self.final_path_list
def find_node_index(self, node):
"""searches our list of nodes and returns the index of the passed no"""
node_name = node.name
node_graph = self.unvisited
for node in node_graph:
if node.name == node_name:
return self.node_graph.index(node)
def transfer_open_node(self, unvisited_node):
"""removes a node from the unvisited list and adds it to the open list"""
# first remove the node from the unvisited list
self.unvisited.remove(unvisited_node)
# link our node to the previous node we are coming from so we can keep track of our path
unvisited_node.previous_node = self.current_node
# now check if our open_list is empty, in which case we place it in the front
if not self.open_list:
self.open_list.append(unvisited_node)
return
# else we iterate through our list and place our unvisited node into the open_list based on it's f cost
i = 0
inserted = False
for current_node in self.open_list:
if unvisited_node.f < current_node.f:
self.open_list.insert(i, unvisited_node)
inserted = True
break
else:
i += 1
# if our node's f cost is the largest, insert it at the back
if not inserted:
self.open_list.append(unvisited_node)
def determine_cost(current_node, unvisited_node, end_node):
""" uses the pythagorean theorem to determine the g and h cost of an unvisited node
we determine the distance by measuring a straight line from our current node to our starting and ending node
g = distance from the start node
h = guess of how far we are from the end node
f = total estimated cost
"""
# determine the distance based on the difference in our x and y coordinates,
# then add on the distance we already are from the start node
unvisited_node.g = (((current_node.x - unvisited_node.x) ** 2 +
(current_node.y - unvisited_node.y) ** 2) ** .5) + current_node.g
h = ((end_node.x - unvisited_node.x) ** 2 + (end_node.y - unvisited_node.y) ** 2) ** .5
unvisited_node.f = unvisited_node.g + h
|
48fa7cb8660abf6d164d4f0978001b235c847f78 | hg-pyun/hello-python | /02-2 문자열 자료형.py | 1,199 | 4.0625 | 4 | # 파이썬에서는 ', ", ''', """을 사용해서 문자열을 나타낼 수 있음
food = "Python's favorte food is perl"
print(food);
multiLine = '''
This is linebreak
You use this!
'''
print(multiLine)
# 문자열 더하기
head = "Python"
tail = " is Fun!"
print(head + tail)
# 문자열 곱하기
multiple = "multi"
print(multiple*2)
# 문자열 곱하기 응용
print("=" * 50)
print("My Program")
print("=" * 50)
# 문자열 indexing
w = "Hello World!"
print(w[0], w[2], w[-1])
# 문자열 slicing
s = w[0:5]
print([s]) # 0~4 까지
s1 = w[6:]
s2 = w[:5]
print(s1, s2)
# 문자열 formatting
number = 3
print("I eat %d apples." % number)
# 문자열 관련 function
# count / find
text = "hobby"
print(text.count('b')) # 2
print(text.find('y')) # 4
# join
comma = ","
print(comma.join('abcd'))
# 공백 제거
spaceText = " hi "
print(spaceText.lstrip(), spaceText.rstrip())
print(spaceText.strip())
# formating 2
print("I eat {0} apples".format(3))
print("I eat {number} {something}".format(number=5, something="bananas"))
print("{0:<10}".format("hi"))
print("{0:>10}".format("hi"))
print("{0:^10}".format("hi"))
print("{0:=^10}".format("hi"))
print("{0:!<10}".format("hi")) |
bf43cf9839f2fe09ed5cefe2b2b9e4a41edd1b0e | arjun-krishna1/leetcode-grind | /groupAnagrams.py | 2,770 | 3.796875 | 4 | class Solution(object):
'''
GIVEN
INPUT
strs: array of strings
OUTPUT
group the anagrams together
anagram: word or phrase formed by rearranging the letters of a different word or phrase
using all the original letters exactly once
BRUTE FORCE
iterate through each word in strs
count how many of each characters is in the string
find al lother words with same number of characters and add to result
skip already consideres trings
output result
SET -> won't work, we need to know number of each char as well, not just total length and unique chars
create a defaultdict with empty list as default
iterate through each word
turn this word to a set
add this word to the list at key this set
SORT
turn list into tuple with sorted word and initial word
sort the list
iterate through the list and add the second element in the tuple to this result list
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
for i in range(len(strs)):# O(n*m*log(m))
strs[i] = (sorted(strs[i]), strs[i]) # O(m*log(m)) -> sorting time
res = []
i = 0
while i < len(strs): # O(n) time
this_res = []
j = i
# add all the words that are anagrams to this result
while j < len(strs) and strs[i][0] == strs[j][0]:
this_res.append(strs[j][1])
j += 1
# add this group of anagrams to total result
res.append(this_res)
# skip to end of anagrams
i = j
return res
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
cache = defaultdict(lambda: [])
for i in range(len(strs)):
cache[tuple(sorted(strs[i]))].append(strs[i])
res = []
for i in cache:
res.append(cache[i])
return res
'''
from collections import defaultdict
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
def countChars(word):
res = [0 for i in range(26)]
for i in word:
res[ord(i) - ord("a")] += 1
return tuple(res)
cache = defaultdict(lambda: [])
for i in range(len(strs)):
cache[countChars(strs[i])].append(strs[i])
res = []
for i in cache:
res.append(cache[i])
return res
|
bfcaf30207c01a7fbad2fa11e2cad9296131bdaa | noozip2241993/learning-python | /csulb-is-640/deitel-text/exercises/ch05/ex517.py | 3,651 | 4.34375 | 4 | '''
5.17 (Filter/Map Performance) With regard to the following code:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
list(map(lambda x: x ** 2,
filter(lambda x: x % 2 != 0, numbers)))
a) How many times does the filter operation call its lambda argument?
b) How many times does the map operation call its lambda argument?
c) If you reverse the filter and map operations, how many times does the map operation call its lambda argument?
To help you answer the preceding questions, define functions that perform the same tasks
as the lambdas. In each function, include a print statement so you can see each time the
function is called. Finally, replace the lambdas in the preceding code with the names of
your functions.
'''
def get_rando_numbers(count=100, min=1, max=20):
from random import randint
COUNT = count
START = min
END = max
return [randint(START, END) for x in range(COUNT)]
def square_it(x):
#print('maps square_it called')
return x**2
def is_odd(x):
result = False
if x % 2 != 0:
result = True
#print('filters is_odd called')
return result
def lambda_performance_test(verbose=False):
import time
#numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
numbers = get_rando_numbers()
#method a - map then filter w/ lambdas
start_time = time.time()
list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, numbers)))
end_time = time.time()
duration_a = end_time - start_time
#method b - map then filter w/ functions
start_time = time.time()
list(map(square_it, filter(is_odd, numbers)))
end_time = time.time()
duration_b = end_time - start_time
#'a) How many times does the filter operation call its lambda argument? 10')
#'b) How many times does the map operation call its lambda argument? 5')
#method c - filter then map w/ functions
start_time = time.time()
list(filter(is_odd, map(square_it, numbers)))
end_time = time.time()
duration_c = end_time - start_time
#a) How many times does the filter operation call its lambda argument? 10')
#'b) How many times does the map operation call its lambda argument? 10')
durations = [duration_a, duration_b, duration_c]
if verbose:
print(f'with lambdas: {duration_a}')
print(f'no lambdas map|filter: {duration_b}')
print(f'no lambdas filter|map: {duration_c}')
return durations
def stress_test(func, observations=100):
# given a function and a number of observations
# run that function over and over and return a
# list of it's output for each time it ran.
# designed for functions that return a list
# of elapsed durations for the runtime of three
# blocks of code.
results = []
for i in range(observations):
results.append(func())
return results
# run the stress test
test_results = stress_test(lambda_performance_test, 100)
#collate the results
method_a_results = [(x[0]) for x in test_results]
method_b_results = [(x[1]) for x in test_results]
method_c_results = [(x[2]) for x in test_results]
#generate test result stats
import statistics as stats
n = len(test_results) #observations
mean_a = stats.mean(method_a_results) #average execution time for method_a
mean_b = stats.mean(method_b_results) #average execution time for method_b
mean_c = stats.mean(method_c_results) #average execution time for method_c
#report the results out
print(f'observations (n): {n}')
print(f'average execution time for method a: {mean_a:.6f}')
print(f'average execution time for method b: {mean_b:.6f}')
print(f'average execution time for method c: {mean_c:.6f}') |
bf95241d5175ada9f398c26d93fe563652a447a8 | kwappa/gothe_python | /Chapter07/human_sato.py | 477 | 3.78125 | 4 | class Human:
age = 0 # 年齢
lastname = '' # 名前
firstname = '' # 苗字
height = 0.0 # 身長
weight = 0.0 # 体重
sato = Human()
sato.age = 35
sato.lastname = '佐藤'
sato.firstname = '次郎'
sato.height = 174.1
sato.weight = 68.2
if (sato.age >= 35 and sato.lastname == '佐藤'):
print('選ばれた人 -> ' + sato.lastname + ' ' + sato.firstname)
|
d7c75e35deab8a720d8de756e625041f22d34fd7 | ujjwalkar0/Python-Socket-Programming | /Tutorial/server1.py | 1,032 | 3.75 | 4 | import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #AF_INET = ipv4, Stock_stream = tcp
s.bind((socket.gethostname(),1235)) # 1234 --> PORT Number ## The bind() method of Python's socket class assigns an IP address and a port number to a socket instance. The bind() method is used when a socket needs to be made a server socket. As server programs listen on published ports, it is required that a port and the IP address to be assigned explicitly to a server socket.
s.listen(5) # listen --> It listens for connections from clients. A listening socket does just what it sounds like. It listens for connections from clients. When a client connects, the server calls accept() to accept, or complete, the connection. The client calls connect() to establish a connection to the server and initiate the three-way handshake.
while True:
clientsocket,address = s.accept()
print(f"Connection from {address} established !")
clientsocket.send(bytes("Welcome to the server !","utf-8"))
clientsocket.close() |
0f3407d8461151023a3bf78c1148a484b5f55192 | arnoldvaz27/PythonAssignments | /Piazza/NextDayofDate.py | 891 | 3.953125 | 4 | """
Question -
Write a Python program to get next day of a given date.
"""
# Code -
year = int(input("Input a year: "))
if year % 400 == 0:
leap_year = True
elif year % 100 == 0:
leap_year = False
elif year % 4 == 0:
leap_year = True
else:
leap_year = False
month = int(input("Input a month [1-12]: "))
if month in (1, 3, 5, 7, 8, 10, 12):
month_length = 31
elif month == 2:
if leap_year:
month_length = 29
else:
month_length = 28
else:
month_length = 30
day = int(input("Input a day [1-31]: "))
if day < month_length:
day += 1
else:
day = 1
if month == 12:
month = 1
year += 1
else:
month += 1
print("The next date is [yyyy-mm-dd] %d-%d-%d." % (year, month, day))
"""
Answer -
Input a year: 1974
Input a month [1-12]: 5
Input a day [1-31]: 29
The next date is [yyyy-mm-dd] 1974-5-30.
""" |
de5ca7e7069eb50ad8846f48a6070cfed2eecef3 | sungly/nrf | /node.py | 1,125 | 3.53125 | 4 | from random import *
from math import *
'''
Tree Node
- each node has an associated weight
Author: Ly Sung
Date: March 23rd 2019
'''
class Node():
value = -1
parent = None
index = 999999
def __init__(self, parent = None, left = None, right = None, bla=0):
self.left = left
self.right = right
self.weight = round(random(), 2)
self.parent = parent
'''
@TODO: update weights
'''
def update_weight(self, sum_error, input, c = 0.1):
new_weight = (sum_error * input * c + self.weight)
self.weight = new_weight
def set_left_node(self, node):
self.left = node
def set_right_node(self, node):
self.right = node
def set_value(self, value):
self.value = value
def set_index(self, index):
self.index = index
def has_left(self):
if self.left:
return True
return False
def has_right(self):
if self.right:
return True
return False
def get_index(self):
return self.index
def get_value(self):
return self.value |
d5c12a078af891af91004f18db2de312af187714 | Podakov4/pyCharm | /module_8/lesson_2.py | 334 | 4.03125 | 4 | # Задача 2. Сумма нечетных
num_stop = int(input('Подсчет суммы закончится на числе: '))
num_summ = 0
for number in range(1, num_stop // 2 * 2 + num_stop % 2 + 1, 2):
print(number)
num_summ += number
print('Сумма всех нечетных чисел равна:', num_summ) |
0399957e7b0fb0f5e415abe42f1148a3d439538a | MauroEBordon/anfamaf2020 | /codigos/lab1ej4.py | 295 | 3.65625 | 4 | # Este código se ejecuta desde linea de comandos con 'python lib1ej4.py'
# Debido a que 0.1 no puede ser representado como una suma finita de potencias de 2,
# nunca se cumplira la condicion del while y vamos a tener que frenarlo con Ctrl + C
x = 0
while x != 10:
x = x + 0.1
print(x)
|
5ca1369c482ac04d7fe1944359d2bb7270e4b918 | TheodorUngureanu/Advent-of-Code | /2020/day19/day19.py | 1,665 | 3.53125 | 4 | #day 19
# run with python3
import regex
from itertools import count
def parseRules(rules):
rules = rules.splitlines()
rulesDictionary = {}
for rule in rules:
number, values = rule.split(': ')
rulesDictionary[number] = values
return rulesDictionary
def build_regex(ruleKey, part):
rule = rules[ruleKey]
# get characters at the beginning of string that match the regular expression pattern
match = regex.match(r'"(\w)"', rule)
counter = count() # generate unique names
if match:
# get the string matched
return match.group(1)
# rule for 8: adding + to the 42 regex
if part == 2 and ruleKey == "8":
return f"({build_regex('42', 2)}+)"
# rule for 11:
if part == 2 and ruleKey == "11":
a = build_regex("42", 2)
b = build_regex("31", 2)
name = f"r{next(counter)}"
return f"(?P<{name}>{a}(?P>{name})?{b})" # like the rule say: letter-rule11-letter
pattern = "|".join("".join(build_regex(m, part) for m in sub_rule.split()) for sub_rule in rule.split(" | "))
return f"({pattern})"
def computePart1(rules, messages):
return len(regex.findall(f"^{build_regex('0', 1)}$", messages, flags=regex.MULTILINE))
def computePart2(rules, messages):
return len(regex.findall(f"^{build_regex('0', 2)}$", messages, flags=regex.MULTILINE))
if __name__ == "__main__":
with open("input", 'r') as input:
rules, messages = input.read().split('\n\n')
rules = parseRules(rules)
print("Part1: " + str(computePart1(rules, messages)))
print("Part2: " + str(computePart2(rules, messages))) |
49b5fc21afd64116bd950165263e3bad98937eb2 | GustavSvensson3600/decTree | /node.py | 843 | 3.703125 | 4 | class Node:
pass
class TreeNode(Node):
def __init__(self, attribute, label):
self.attribute = attribute
self.label = label
self.children = list()
def add_child(self, child):
self.children.append(child)
def print_deep(self, depth, parent):
print (" " * depth) + parent.name, "=", self.label
for child in self.children:
child.print_deep(depth+1, self.attribute)
def print_node(self):
for child in self.children:
child.print_deep(0, self.attribute)
class LeafNode(Node):
def __init__(self, attribute, label, klass):
self.attribute = attribute
self.label = label
self.klass = klass
def print_deep(self, depth, parent):
print (" " * depth) + self.attribute.name, "=", self.label + ":", self.klass |
a573c107124feb823b59b50d7651c4064e3640f7 | kieda/ForcePhysicsSimulator | /PhysicsOld/src/event.py | 1,111 | 3.5 | 4 | import sys
import numpy as np
class Event:
CollisionType, ZeroVelocityType, BoundaryCrossingType = range(3)
class Collision:
def __init__(self, timeIn, pointIn, manifoldIn):
self.type = Event.CollisionType
self.time = timeIn
self.point = pointIn
self.manifold = manifoldIn
class BoundaryCrossing:
def __init__(self, timeIn, pointIn, manifoldIn):
self.type = Event.BoundaryCrossingType
self.time = timeIn
self.point = pointIn
self.manifold = manifoldIn
if (timeIn < 0):
print "BoundaryCrossing requested at a negative time"
print timeIn
print pointIn
print manifoldIn.normal
print manifoldIn.offset
sys.exit([0])
# velocity will be zeroed in a certain direction only
# (first orthogonal to the driving force, and then in the direction of it)
class ZeroVelocity:
def __init__(self, timeIn, directionIn):
self.type = Event.ZeroVelocityType
self.time = timeIn
self.direction = directionIn
|
8f248eab9a4360990f9f47e0ce7fe60a0d18725b | sunchigg/JrML | /80_00 • Flask/request.py | 454 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""可於local端輸入以下:
http://127.0.0.1:5000/index?name=test&age=666
Output:hello Flask. ur name=test and age=666
"""
from flask import Flask, request
app = Flask(__name__)
@app.route("/index", methods=["GET", "POST"])
def index():
name = request.args.get("name")
age = request.args.get("age")
return "hello Flask. ur name=%s and age=%s" % (name, age)
if __name__ == '__main__':
app.run(debug=True)
|
d03c192c7da76ca2facac8ecb8cc17f6b5f49712 | zhanghcqm/python_test | /random/随机红包.py | 218 | 3.609375 | 4 | import random
def red_packet(total,num):
for i in range(num-1):
per=random.uniform(0.01,total/2)
total=total- per
print('%.2f'% per)
else:
print('%.2f'% total)
red_packet(10,5)
|
63dbc66eba77b4c61937c408a9ba8520535bca05 | helgefmi/moggio | /moggio/state.py | 7,987 | 3.578125 | 4 | import moggio.util as util
import moggio.defines as defs
import moggio.cache as cache
"""Includes the State class."""
class State:
"""Represents the state of a position on the chess board.
This class has the variables:
pieces - Set of bitboards representing the pieces position on the board.
turn - Who's turn it is.
castling - Castling availability.
en_passant - En passant availability.
occupied - Which squares are occupied by white, black, or both.
"""
def __init__(self, fen=None):
"""If fen is not given, the instance will represent an empty board."""
if fen:
self.set_fen(fen)
def reset(self):
"""Forgets everything about the current state."""
self.pieces = (
[0, 0, 0, 0, 0, 0], # WHITE
[0, 0, 0, 0, 0, 0] # BLACK
)
self.turn = defs.WHITE
self.castling = 0
self.en_passant = 0
self.occupied = [
0, 0, 0 # WHITE, BLACK, BOTH
]
def copy(self):
"""Makes an independent copy of a state instance"""
s = State()
s.pieces = (
self.pieces[0][:],
self.pieces[1][:]
)
s.turn = self.turn
s.castling = self.castling
s.en_passant = self.en_passant
s.occupied = self.occupied[:]
return s
def make_move(self, move):
opponent = 1 - self.turn
# Remove the piece that moved from the board.
self.pieces[self.turn][move.from_piece] ^= move.from_square
self.occupied[self.turn] ^= move.from_square
# If it is a capture, we need to remove the opponent piece as well.
if move.capture != None:
# Remember to clear castling availability if we capture a rook.
if self.castling & move.to_square:
self.castling &= ~move.to_square
to_remove_square = move.to_square
if move.from_piece == defs.PAWN and move.to_square & self.en_passant:
# The piece captured with en passant; we need to clear the board of the captured piece.
# We simply use the pawn move square of the opponent to find out which square to clear.
to_remove_square = cache.moves_pawn_one[opponent][move.to_square]
# Remove the captured piece off the board.
self.pieces[opponent][move.capture] ^= to_remove_square
self.occupied[opponent] ^= to_remove_square
# Update the board with the new position of the piece.
if move.promotion:
self.pieces[self.turn][move.promotion] ^= move.to_square
else:
self.pieces[self.turn][move.from_piece] ^= move.to_square
# Update "occupied" with the same piece as above.
self.occupied[self.turn] ^= move.to_square
self.en_passant = 0
if move.from_piece == defs.KING:
#TODO: This can be made more efficient by caching more stuff..
# We could first see if the move was >1 step (one bitwise and and one lookup),
# then we could have a cache element where cached[to_square] gives the place where
# the rook should be positioned (one bitwise xor and one lookup).
left_castle = cache.castling_availability[self.turn][0][move.from_square]
if (left_castle << 2) & move.to_square:
self.pieces[self.turn][defs.ROOK] ^= left_castle | left_castle << 3
self.occupied[self.turn] ^= left_castle | left_castle << 3
right_castle = cache.castling_availability[self.turn][1][move.from_square]
if (right_castle >> 1) & move.to_square:
self.pieces[self.turn][defs.ROOK] ^= right_castle | right_castle >> 2
self.occupied[self.turn] ^= right_castle | right_castle >> 2
# Clear the appropriate castling availability.
self.castling &= ~cache.castling_by_color[self.turn]
elif move.from_piece == defs.ROOK:
# Clear the appropriate castling availability.
self.castling &= ~move.from_square
# Clear / set en_passant
elif move.from_piece == defs.PAWN:
if ~cache.moves_pawn_one[self.turn][move.from_square] & move.to_square & cache.moves_pawn_two[self.turn][move.from_square]:
self.en_passant = cache.moves_pawn_one[self.turn][move.from_square]
self.turn ^= 1
self.occupied[defs.BOTH] = \
self.occupied[defs.WHITE] | self.occupied[defs.BLACK]
def set_fen(self, fen):
"""Sets the board according to Forsyth-Edwards Notation.
See http://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation for more information.
"""
self.reset()
fen_parts = fen.split()
numbers = map(str, range(1, 10))
# Set up the position
fen_position = fen_parts.pop(0)
piece_idx = 8 * 7 # Starting on the A8.
for c in fen_position:
if c == '/':
piece_idx -= 2 * 8
elif c in numbers:
piece_idx += int(c)
else:
try:
piece = util.char_to_piece(c)
color = util.char_to_color(c)
self.pieces[color][piece] |= (1 << piece_idx)
except KeyError:
raise Exception("Invalid FEN: '%s'" % fen)
else:
piece_idx += 1
# Update self.occupied with the occupied squares in self.pieces.
self.occupied[defs.WHITE] = self.occupied[defs.BLACK] = self.occupied[defs.BOTH] = 0
for color, piece in defs.COLOR_PIECES:
self.occupied[color] |= self.pieces[color][piece]
self.occupied[defs.BOTH] |= self.pieces[color][piece]
# Set active color.
fen_color = fen_parts.pop(0)
if fen_color.lower() == 'w':
self.turn = defs.WHITE
elif fen_color.lower() == 'b':
self.turn = defs.BLACK
else:
raise Exception("Invalid FEN: '%s'" % fen)
# Set castling availability.
fen_castling = fen_parts.pop(0)
for c in fen_castling:
if c == 'Q':
self.castling |= defs.A1
elif c == 'K':
self.castling |= defs.H1
elif c == 'q':
self.castling |= defs.A8
elif c == 'k':
self.castling |= defs.H8
# Set en passant.
fen_passant = fen_parts.pop(0)
if fen_passant != '-':
square_idx = util.chars_to_square(fen_passant)
self.en_passant = (1 << square_idx)
# TODO: Halfmove and Fullmove numbers from FEN.
def __str__(self):
"""Makes a pretty string, representing a position."""
seperator = '+---+---+---+---+---+---+---+---+\n'
ret = seperator
for y in xrange(7, -1, -1):
ret += '|'
for x in xrange(0, 8):
idx = 1 << (y * 8 + x)
found = None
for color, piece in defs.COLOR_PIECES:
if self.pieces[color][piece] & idx:
found = util.piece_to_char(color, piece)
break
extra = ' '
if self.en_passant & idx:
extra = '*'
if self.castling and self.castling & idx:
extra = '*'
if found:
ret += ' ' + util.piece_to_char(color, piece) + extra + '|'
else:
squareColor = ' '
if (y ^ x) & 1 == 0:
squareColor = ' .'
ret += squareColor + extra + '|'
ret += "\n" + seperator
ret += 'Turn: %s' % ('White', 'Black')[self.turn]
ret += "\n"
return ret
|
daf58a32eb3db63105ae3c2bd1f1f6f2d612d4a0 | liwb27/leetcode | /786. K-th Smallest Prime Fraction.py | 1,955 | 3.78125 | 4 | # A sorted list A contains 1, plus some number of primes. Then, for every p < q in the list, we consider the fraction p/q.
# What is the K-th smallest fraction considered? Return your answer as an array of ints, where answer[0] = p and answer[1] = q.
# Examples:
# Input: A = [1, 2, 3, 5], K = 3
# Output: [2, 5]
# Explanation:
# The fractions to be considered in sorted order are:
# 1/5, 1/3, 2/5, 1/2, 3/5, 2/3.
# The third fraction is 2/5.
# Input: A = [1, 7], K = 1
# Output: [1, 7]
# Note:
# A will have length between 2 and 2000.
# Each A[i] will be between 1 and 30000.
# K will be between 1 and A.length * (A.length - 1) / 2.
# from queue import PriorityQueue
import heapq
class Solution(object):
def kthSmallestPrimeFraction(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
count = 1
length = len(A)#smallest is A[0]/A[j]
# que = PriorityQueue()
que = []
heapq.heappush(que, (A[0]/A[length-1], (0, 0)))
# que.put((A[0]/A[length-1], (0, 0)))# 先放入第一列
while count <= K:
count = count + 1
(val, (i, j)) = heapq.heappop(que)
# (val, (i, j)) = que.get()
# print(val, str(A[j])+'/'+str(A[length-1-i]))
if i+1 < length: #向下
heapq.heappush(que, (A[j]/ A[length-2-i], (i+1, j)))
# que.put((A[j]/ A[length-2-i], (i+1, j)))
if j+1 < length and i==0: # 向右
heapq.heappush(que, (A[j+1] / A[length-1-i], (i, j+1)))
# que.put((A[j+1] / A[length-1-i], (i, j+1))) # 左下
return [A[j],A[length-1-i]]
# A= [1,3,5,7,11]
# 11 1/11, 3/11,...
# 7 1/7, ...
# 5 1/5, ...
# 3
# 1
# 转化为no. 378 问题
# 用priorityque会不通过,改用heap可以通过...
print(Solution().kthSmallestPrimeFraction([1,3,5,7,11],5)) |
b37ab90d42a85981aca3ee67dea7f9ec73a03de5 | NickYxy/LeetCode | /Algorithms/100_Same Tree.py | 1,266 | 3.90625 | 4 | __author__ = 'nickyuan'
'''
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
def isSameTree1(self, p, q):
return p and q and p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) or p is q
def isSameTree2(self, p, q):
def t(n):
return n and (n.val, t(n.left), t(n.right))
return t(p) == t(q)
def isSameTree3(self, p, q):
if p is None and q is None:
return True
if p is None or q is None:
return False
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
|
cef652417f12b2fec166bdef44c33c4100549894 | Sreenuraj/SoftwareTestingWithPython | /Refresher/decorator.py | 800 | 3.546875 | 4 | import functools
def my_decorator(func):
@functools.wraps(func)
def functions_that_run_func():
print('In decorator')
func()
print('After the decorator')
return functions_that_run_func
@my_decorator
def my_function():
print('in my function')
# my_function()
def decorator_with_arguments(num):
def my_decorator(func):
@functools.wraps(func)
def functions_that_run_func(*args, **kwargs):
print('In decorator')
if num == 56:
print("not running")
else:
func(*args, **kwargs)
print('After the decorator')
return functions_that_run_func
return my_decorator
@decorator_with_arguments(56)
def my_fuction(x, y):
print(x + y)
my_fuction(10, 5)
|
69671cc5d5468d1acc905a7d28f1776110a03e90 | h1iba1/PYTHON | /ARRAY/1_array.py | 456 | 4.34375 | 4 | #数组在python里叫列表
#一些简单特性
print(['hi']*4)
print(3 in [1,2,3])#元素是否在列表中
#迭代
for x in [1,2,3]:
print(x,end=" ")
#确定数组长度
print(len([1,2,3]))
#python 列表截取与拼接
L=['Google', 'Runoob', 'Taobao']
print(L[2])#输出第三个元素
print(L[-2])#输出从右边起,倒数第二个元素
print(L[1:])#输出第一个元素后面的元素
print(L.append('taobo'))
print(L) |
045187e7b97053a75dd654aea99e8ac283322d84 | JohnDoddy/python_challenges | /6_binary_search.py | 701 | 4.3125 | 4 | # implementing binary search
# by John Doddy
# our data set
data = [1, 2, 3, 4, 5, 6]
target_value = int(input("What's the target value: "))
# the binary search algorithm
def binary_search(data, target_value):
minimum = data[0]
maximum = len(data) - 1
while minimum <= maximum:
midium = int(maximum / minimum)
if data[midium] == target_value:
print("Yes {} is on our list".format(target_value))
if target_value > data[midium]:
minimum = midium + 1
else:
maximum = midium - 1
if minimum > maximum:
print("Your value is not on the list")
binary_search(data, target_value)
|
104eddcf8d98d1ab3458924a50a56e7438323874 | camargo800/Python-projetos-PyCharm | /PythonExercicios/ex081.py | 841 | 4.0625 | 4 | #Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
#A) Quantos números foram digitados.
#B) A lista de valores, ordenada de forma decrescente.
#C) Se o valor 5 foi digitado e está ou não na lista.
valores = []
while True:
valores.append(int(input('Digite um número: ')))
resposta = str(input('Deseja continuar [S/N]? ')).strip().upper()[0]
if resposta not in 'SN':
print('Opção inválida!')
if resposta == 'N':
break
print('-='*25)
print('Os valores digitados foram: {}.'.format(valores))
print('-='*25)
print('Foram digitados {} números'.format(len(valores)))
valores.sort(reverse=True)
print('Os números digitados na ordem inversa: {}'.format(valores))
if 5 in valores:
print('O valor 5 foi encontrado.')
else:
print('O valor 5 não foi digitado.')
|
ed5f9295bef6da71a48bbd7198867c53ccb842a7 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio27.py | 179 | 3.6875 | 4 | n = str(input('Informe seu nome completo')).strip()
nome = n.split()
print(f'O primeiro nome é {(nome[0])}')
#ultimo = (nome[-1])
print(f'Seu ultimo nome é {(nome[-1])}')
|
b00314e1ea7bceef4174bfdc00423051bca3d907 | Dex4n/algoritmos-python | /02.py | 4,689 | 4.28125 | 4 | '''4) Escreva uma TAD que implemente uma lista circular ordenada
duplamente encadeada que armazena em cada nó uma chave inteira e um
nome. As seguintes operações abaixo devem ser definidas: a)Buscar um
nome dado o valor da chave;
b) Inserir um novo elemento na lista mantendo a ordem;
c) Remover um elemento da lista;
d) Imprimir os valores da lista;
e) Copiar uma lista l1 para uma lista l2;
f) Concatenar uma lista l1 com uma lista l2;
g) Intercalar l1 e l2;'''
from os import system
chave = 0
lista1 = []
lista2 = []
while True:
print('Menu:\n'
'1 - Buscar um nome dado o valor da chave\n'
'2 - Inserir um novo elemento na lista mantendo a ordem\n'
'3 - Remover um elemento da lista pelo CPF\n'
'4 - Imprimir os valores da lista\n'
'5 - Buscar um nome pelo valor do CPF\n'
'6 - Transformar a lista circular em duas listas L1 e L2, listando-as\n'
'7 - Intercalar l1 e l2\n'
'8 - Sair')
op = input('Sérgio, Escolha a opcao desejada: ')
if int(op) == 1:
try:
buscaChave = input('Sérgio, agora digite a chave para busca, por gentileza: ')
for i in range(len(lista1)):
if int(buscaChave) == lista1[i][0]:
print('Nome: {}'.format(lista1[i][1]))
print('--------------------------')
if len(lista1) == 0:
print('Lista vazia, Sérgio! Escolha a opção 2!\n')
except ValueError:
print('Essa chave digitada está inválida Sérgio!')
elif int(op) == 2:
aux = []
aux.append(chave)
aux.append(input('Nome: '))
aux.append(int(input("CPF: ")))
print('Chave: {}'.format(aux[0]))
print('Nome: {}'.format(aux[1]))
print('CPF: {}'.format(aux[2]))
print('Cadastro efetuado Sr. Sérgio!')
print('-------------------------')
lista1.append(aux[:])
lista2.append(aux[:])
chave += 1
elif int(op) == 3:
try:
buscaCPF = input('Digite o CPF para busca: ')
for i in range(len(lista1)):
if int(buscaCPF) == lista1[i][2]:
del lista1[i]
del lista2[i]
print('Removido com sucesso, Sérgio!')
break
if len(lista1) == 0:
print('Lista vazia!')
print('-----------------------------------')
except ValueError:
print('Chave inválida!')
elif int(op) == 4:
for i in range(len(lista1)):
print('Código : {} nome: {} CPF: {}'.format(lista1[i][0], lista1[i][1], lista1[i][2]))
for i in range(len(lista3)):
print('Código : {} nome: {} CPF: {}'.format(lista3[i][0], lista3[i][1], lista3[i][2]))
for i in range(len(lista5)):
print('Código: {} nome: {} CPF: {}'.format(lista5[i][0], lista5[i][1], lista5[i][2]))
for i in range(len(lista7)):
print('Código : {} nome: {} CPF: {}'.format(lista7[i][0], lista7[i][1], lista7[i][2]))
print('------------------------------------')
elif int(op) == 5:
try:
buscaPeloCPF = input('Sérgio, agora digite o CPF para busca, por gentileza: ')
for i in range(len(lista1)):
if int(buscaPeloCPF) == lista1[i][2]:
print('Nome: {}'.format(lista1[i][1]))
print('--------------------------')
if len(lista1) == 0:
print('Lista vazia, Sérgio!')
except ValueError:
print('Essa chave digitada está inválida Sérgio!')
print('-------------------------------------')
elif int(op) == 6:
listaAUX1 = []
listaAUX2 = []
for i in range(len(lista1)):
if (i % 2 == 0):
listaAUX1.append(lista1[i])
else:
listaAUX2.append(lista1[i])
print('Lista1: {}'.format(listaAUX1))
print('Lista2: {}'.format(listaAUX2))
print('--------------------------------------')
elif int(op) == 7:
lista3 = []
for i in range(len(listaAUX1)):
lista3.append(listaAUX1[i])
if (i < len(listaAUX2)):
lista3.append(listaAUX2[i])
else:
break
print('Lista intercalada:')
for i in range(len(lista3)):
print('Lista intercalada: chave: {} nome: {} CPF: {}'.format(i, lista3[i][0], lista3[i][1], lista3[i][2]))
print('--------------------------------------')
elif int(op) == 8:
print('Fim do programa!')
system('pause')
exit()
else:
print('Opção inválida!')
continue
|
7cdac124184fe6f1567843292535f0e20eb3ed61 | roflmaostc/Euler-Problems | /055.py | 1,620 | 4.03125 | 4 | #!/usr/bin/env python
"""
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
"""
from eulerfunctions import is_palindrome as ip
from eulerfunctions import reverse as rev
def is_lychrel(x, limit=52):
for i in range(limit):
a = x
b = rev(x)
x = a+b
if ip(x):
return False
return True
def solve(n):
counter = 0
for i in range(n):
if is_lychrel(i):
counter += 1
return counter
print(solve(10000))
|
ca619f2d77ec2c0054f66016dd1aec9b20e4b621 | cyct123/LeetCode_Solutions | /378.kth-smallest-element-in-a-sorted-matrix.py | 1,025 | 3.640625 | 4 | #
# @lc app=leetcode id=378 lang=python3
#
# [378] Kth Smallest Element in a Sorted Matrix
#
# https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
#
# algorithms
# Medium (52.05%)
# Likes: 1980
# Dislikes: 114
# Total Accepted: 167.2K
# Total Submissions: 315.9K
# Testcase Example: '[[1,5,9],[10,11,13],[12,13,15]]\n8'
#
# 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 ≤ n^2.
#
# @lc code=start
import heapq
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
hq = []
for l in matrix:
hq.extend(l)
return heapq.nsmallest(k, hq)[-1]
# @lc code=end
|
d93933ccbf53934ee07a5fc5f0d7979ff5804651 | ElenaSat/Python2021 | /Leccion02/EjercicioRectangulo.py | 187 | 3.75 | 4 | alto= int(input("Proporciona el alto: "))
ancho= int(input("Proporciona el ancho: "))
area=alto*ancho
perimetro=(alto + ancho) * 2
print(f'Area: {area}')
print(f'Perímetro: {perimetro}') |
8e23b9c8fa5c9d7c5f42a5f2999c5df3f7c34d4b | CodeWithSamar/ALL-IN-ONE-CALCULATOR-BY-CodeWithSamar | /@CodewithSamar Calculator.py | 2,701 | 4.25 | 4 | # ALL-IN-ONE-CALCULATOR-BY-CodeWithSamar
This is a calculator which will you to do mathematical calculations
import math
import random
import time
print("Welcome to one of the most trusted calculator @codewithsamar calculator")
def add(number1, number2):
return number1 + number2
def subtract(number1, number2):
if number1>number2:
return number1 - number2
elif number1==number2:
return number1 - number2
else:
return number2 - number1
def multiply(number1, number2):
return number1 * number2
def divide(number1, number2):
return number1 / number2
def average(number1, number2):
return number1 + number2 / 2
def random_number(number1, number2):
randomnumber = random.randint(number1, number2)
return randomnumber
def GcD(number1, number2):
return math.gcd(number1, number2)
def reMainder(number1, number2):
return math.remainder(number1, number2)
def Power(number1, number2):
return math.pow(number1, number2)
def LcM(number1, number2):
gcd =math.gcd(number1, number2)
lcm = (number1 * number2) / gcd
return lcm
print("Enter your choice\n"
"1. Add\n"
"2. Subtract\n"
"3.Multiply\n"
"4. Divide\n"
"5. Average\n"
"6. Random Number\n"
"7. GCD or HCF \n"
"8. Remainder \n"
"9. Power \n"
"10.LCM \n")
choice = int(input("What do you want 1, 2, 3, 4, 5, 6, 7, 8, 9, 10: "))
number1 = int(input("Enter first number"))
number2 = int(input("Enter second number"))
if choice == 1:
print(number1, "+", number2, "=",
add(number1, number2))
time.sleep(3)
elif choice == 2:
print(number1, "-", number2, "=",
subtract(number1, number2))
time.sleep(3)
elif choice == 3:
print(number1, "*", number2, "=",
multiply(number1, number2))
time.sleep(3)
elif choice == 4:
print(number1, "/", number2, "=",
divide(number1, number2))
time.sleep(3)
elif choice == 5:
print("the average of", number1, "and", number2, "is =",
average(number1, number2))
time.sleep(3)
elif choice == 6:
print("The Random Number between", number1, "and", number2, "=",
random_number(number1, number2))
time.sleep(3)
elif choice == 7:
print("The GCD of", number1, "and", number2, "=",
GcD(number1, number2))
elif choice == 8:
print("The Remainder of", number1, "and", number2, "=",
reMainder(number1, number2))
elif choice == 9:
print(number1, "raised to power", number2, "=",
Power(number1, number2))
elif choice == 10:
print("The LCM of", number1, "and", number2, "=",
LcM(number1, number2))
else:
print(".......ERROR")
|
f2ec97f2f9bff634f745e7d77b4f03c71efee974 | jannylund/advent-of-code-19 | /day04.py | 1,362 | 3.609375 | 4 | from collections import Counter
from timeit import default_timer as timer
from utils.time import get_time
# Check that we are not decreasing.
def check_increasing(digit):
last = None
for i in str(digit):
if last is not None and i < last:
return False
last = i
return True
# Check that max 2 adjacent are the same.
def check_adjacent(digit):
return max(Counter(str(digit)).values()) >= 2
# Check that at least 2 adjacent are the same.
def check_pairs(digit):
return 2 in Counter(str(digit)).values()
def is_valid_password(digit):
return check_increasing(digit) and check_adjacent(digit)
def is_valid_password2(digit):
return check_increasing(digit) and check_pairs(digit)
if __name__ == "__main__":
with open('input/day04.txt') as f:
d_min, d_max = f.readline().split("-")
start = timer()
valid_passwords = []
for d in range(int(d_min), int(d_max)+1):
if is_valid_password(d):
valid_passwords.append(d)
print("result day 04 part 1: {} in {}".format(len(valid_passwords), get_time(start)))
start = timer()
valid_passwords = []
for d in range(int(d_min), int(d_max)+1):
if is_valid_password2(d):
valid_passwords.append(d)
print("result day 04 part 2: {} in {}".format(len(valid_passwords), get_time(start)))
|
d1194290ac002ed792fb46dca214449090da1a76 | Aasthaengg/IBMdataset | /Python_codes/p03631/s140947534.py | 48 | 3.59375 | 4 | s=input()
print('Yes' if s[0]==s[-1] else 'No')
|
5a1ff9503d292698f65de8d6071971d2d1f4a992 | bansal6498/ForskTechnologyAssignments | /fizzbuzz.py | 863 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 14 14:45:56 2020
@author: bansa
"""
"""
Code Challenge
Name:
Fizz Buzz
Filename:
fizzbuzz.py
Problem Statement:
Write a Python program which iterates the integers from 1 to 50(included).
For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
User Input not required
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
"""
number = 1
while(number<51):
if number%15 == 0:
print('FizzBuzz')
elif number%5 == 0:
print('Buzz')
elif number%3 == 0:
print("Fizz")
else:
print(number)
number+=1 |
6775fa5fe6219ed370fe6184c812b3329017274c | TT-Bone/guanabara-python | /Exercícios/076.py | 1,863 | 4.09375 | 4 | '''
Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência.
No final, mostre uma listagem de preços organizando os dados em forma tabular.
'''
tupla = ('Panquecas', 5.50, 'Waffles', 4.30, 'Ovos e Bacon', 6.30, 'Linguiça e BatataRosti', 7.40, 'Omelete', 4.40, 'Cheese Burger', 8.80)
# Achando uma forma para diagramar no formato tabulado os nomes.
# nome = 'Thiago'
# print(f'{nome:.<10}{nome:.>30}')
# Ainda estava no pensamento de conseguir entregar o resultado de números pares e ímpares no intervalo de 0 ao len(tupla). Esse teste aqui, era para conseguir entregar a primeira metade dos números.
# for comida in range(0, int(len(tupla)/2)):
# print(comida)
# Essa foi o estudo para conseguir entregar os apenas os índices PARES da contagem. A ideia era de usar dois contadores assim, um para os pares e outro para os ímpares.
# for comida in range(2, int(len(tupla) + 1), 2):
# print(comida)
# Aqui seria a parte dos índices ÍMPARES dessa sequência.
# for comida in range(1, int(len(tupla)), 2):
# print(comida)
# E aqui eu queria entregar as posições, sem ser índice, da primeira metade.
# for volta in range(1, int(len(tupla)/2)+1):
# print(volta)
par = 0
impar = 1
print('=' * 52)
print(f'{"LOJAS BATMAN":^52}')
print('=' * 52)
while True:
print(f'{tupla[par]:.<45}', end ='')
print(f'R$ {tupla[impar]:.2f}')
par += 2
impar += 2
if par == 12:
break
print('=' * 52)
'''
Deixei todos os testes que eu fiz para conseguir achar os valores que eu estava buscando. No final das contas, eu esqueci que poderia usar algumas variáveis para fazer de controle. Porém, foram tentativas bem úteis, no final das contas. Por isso resolvi não deletar.
No final das contas, a resolução ficou super enxuta, e beem diferente do que eu imaginei que seria.
''' |
536dfab0c6aaaa057f98b0b6fd3c4733533e95bc | TemurKhabibullaev/NewRepForCrapsGame | /Craps.py | 1,974 | 4.09375 | 4 | # Temur Khabibullaev
# 10/21/2019
import random
import time
print('ENTER your balance:')
balance = int(input('> '))
print("Good! Let's start! Place how much you bet!")
bet = int(input('> '))
total_amount = balance - bet
def start():
# Balance
print('''
Welcome to Craps Game!
The Dice will be rolled!''')
total_amount = balance - bet
while bet < total_amount:
rollDice()
game()
def finish():
print('Good Job! Game is finished. Here is your balance:\n> ', total_amount)
def rollDice():
points = random.randint(2,12)
return points
def win():
won_money = total_amount + bet * 2
print('Wow! You won! Your win is: ',won_money)
def loosing():
lost_money = total_amount - bet * 2
print('You lose. This is your lose amount:', lost_money)
def game():
roll = rollDice()
print('Your dice: ', roll)
if int(roll) == 7 or int(roll) == 11:
time.sleep(3)
win()
elif int(roll) == 2 or int(roll) == 3 or int(roll) == 12:
time.sleep(3)
loosing()
elif roll == 4 or roll == 5 or roll == 6 or roll == 8 or roll == 9 or roll == 10:
print(f'Your points: {roll}. You will keep rolling until you get same points (Win) or 7 (Lose).')
print('This is your balance now: ',total_amount)
new_roll = random.randint(2,12)
while roll != new_roll and new_roll != 7:
print(f"You have rolled a {new_roll}, we'll keep going.")
time.sleep(2)
new_roll = random.randint(2,12)
if new_roll == roll:
print(f"You got {new_roll}!")
win()
elif new_roll == 7:
print(f"You got {new_roll}")
loosing()
decision = input('Are we playing? Know - wins or loses will be cut from your balance. Enter an INTEGER only:\n1) Yes\n2) No\n> ')
if int(decision) == 1:
start()
elif int(decision) != 1:
print('Good Luck! See you next time.')
finish()
start() |
308a965ff995e99631be35bf3e1ff59a4efbf147 | WasimAlgahlani/Hangman-Game | /main.py | 1,039 | 3.71875 | 4 | import random
from pic import hang
from words import words
lives = 6
chosen_word = random.choice(words)
word_len = len(chosen_word)
display = []
end = False
for _ in range(word_len):
display.append("_")
print(f"{' '.join(display)}")
while not end:
letter = input("Guess a letter: ").lower()
if letter in display:
print("Already chosen.")
else:
c = 0
for pos in range(word_len):
if chosen_word[pos] == letter:
display[pos] = letter
if c == 0:
print(f"Correct, {letter} is in the word.")
c += 1
print(f"{' '.join(display)}")
if letter not in chosen_word:
lives -= 1
print(hang[lives])
print(f"Wrong, down by one live , remains {lives} lives.")
if lives == 0:
print("You loss.")
end = True
if "_" not in display:
end = True
print("You won")
print()
|
376b50fd32555c4aea2d914549c475d58ce15c1b | getState/nklcb_algorithm | /Assignment4/BinaryTree_node.py | 2,811 | 4.03125 | 4 | from queue import Queue
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
class BinaryTree:
def __init__(self, array):
node_list = [Node(value, None, None) for value in array]
for ind, node in enumerate(node_list):
left = 2 * ind + 1
right = 2 * ind + 2
if left < len(node_list):
node.left = node_list[left]
if right < len(node_list):
node.right = node_list[right]
self.root = node_list[0]
def preorder(self):
result = '['
def recursive(node):
nonlocal result
result += str(node.value)
result += ' '
if node.left is not None:
recursive(node.left)
if node.right is not None:
recursive(node.right)
recursive(self.root)
result += ']'
print(result)
def inorder(self):
result = '['
def recursive(node):
nonlocal result
if node.left is not None:
recursive(node.left)
result += str(node.value)
result += ' '
if node.right is not None:
recursive(node.right)
recursive(self.root)
result += ']'
print(result)
def postorder(self):
result = '['
def recursive(node):
nonlocal result
if node.left is not None:
recursive(node.left)
if node.right is not None:
recursive(node.right)
result += str(node.value)
result += ' '
recursive(self.root)
result += ']'
print(result)
def bfs(self, value):
que = Queue()
que.put(self.root)
while not que.empty():
node = que.get()
if node.value == value:
return True
if node.left is not None:
que.put(node.left)
if node.right is not None:
que.put(node.right)
return False
def dfs(self, value):
result = False
def recursive(node):
nonlocal result
if result is True:
return
if node.value == value:
result = True
return
if node.left is not None:
recursive(node.left)
if node.right is not None:
recursive(node.right)
recursive(self.root)
return result
tree = BinaryTree([i for i in range(13)])
tree.preorder()
tree.inorder()
tree.postorder()
print(tree.dfs(15))
print(tree.dfs(11))
print(tree.bfs(6))
print(tree.bfs(17)) |
d859f935df804211b7214923f9eb534187a8918a | beunick13/cars | /main.py | 1,607 | 4 | 4 | # Программа, которая определяет марку автомобиля
q1 = input('Автомобиль из Европы? ')
if q1.lower() == 'да':
q2 = input('Автомобиль из Германии? ')
if q2.lower() == 'да':
q3 = input('У автомобиля цветной логотип? ')
if q3.lower() == 'да':
print('BMW')
else:
q4 = input('Логотип автомобиля состоит из четырех колец? ')
if q4.lower() == 'да':
print('Audi')
else:
print('Mercedes')
else:
q6 = input('На логотипе автомобиля лошадь? ')
if q6.lower() == 'да':
print('Ferrari')
else:
print('Lamborghini')
else:
q2 = input('Автомобиль из Америки? ')
if q2.lower() == 'да':
q5 = input('Логотип этого автомобиля похож на крест? ')
if q5.lower() == 'да':
print('Chevrolet')
else:
print('Ford')
else:
q4 = input('Автомоболь из Японии? ')
if q4.lower() == 'да':
q7 = input('Логотип автомобиля похож на букву "H"? ')
if q7.lower() == 'да':
print('Honda')
else:
print('Toyota')
else:
q9 = input('Автомобиль из Кореи? ')
if q9.lower() == 'да':
print('Hyundai')
|
5722f877782f75048a41796e209cb86c0783805e | Hoan1028/IS340 | /IS340_HW10/IS340_HW10_4.py | 313 | 3.96875 | 4 | #Demonstrate the FillInQuestion class
from questions import FillInQuestion
#create the question and expected answer
q = FillInQuestion()
q.setText("The inventor of Python was _Guido van Rossum_")
#Display the question and obtain user's response
q.display()
response = input("Your answer: ")
print(q.checkAnswer(response))
|
49cbe43bb29116981d7912b86d48923c9c37a32e | timemerry/fifa19PlayerData | /bestplayer.py | 216 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
data = pd.read_csv('data.csv')
print (data.loc[[11200,11201,11206,11226,11239],['Name','Age','Overall','Potential','Value']])
#print (data.loc[11206]) |
1d8525b1c3f22bb2c0bd6b15c7c37f1ada62d28f | Oscar-Oliveira/Python-3 | /11_Iterators/B_Iterator.py | 757 | 3.53125 | 4 | """
Iterator
"""
class RangeAZ:
def __init__(self, max):
if isinstance(max, int) and 0 < max <= 26:
self.current = 65
self.max = self.current + max
else: raise ValueError("max parameter must be in [1..26].")
def __iter__(self):
return self
def __next__(self):
if self.current == self.max:
raise StopIteration
value = chr(self.current)
self.current += 1
return value
def get_next_value(data):
try:
return next(data)
except StopIteration:
return None
iterator = iter(RangeAZ(26))
while True:
a = get_next_value(iterator)
if a:
print(a, end=" ")
continue
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.