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 |
|---|---|---|---|---|---|---|
155cf554e2330f64b7ba41335ae0e90bb454d6a2 | muriloviscondi/curso-em-video-python | /ex067 - Tabuada v3.0.py | 353 | 3.859375 | 4 | while True:
num: int = int(input('Quer ver a tabudada de qual valor? '))
print('-' * 30)
if num < 0:
break
for i in range(1, 11):
print(
'{} x {:2} = {:3}'
.format(
num, i, num * i
)
)
print('-' * 30)
print('PROGRAMA TABUADA ENCERRADO. Volte Sempre!!!')
|
c578cfbe8630e2bfaa6da065efc73fb1d92762c8 | daniel-reich/turbo-robot | /8vBvgJMc2uQJpD6d7_15.py | 588 | 4.1875 | 4 | """
Create a function that returns a list containing the prime factors of whatever
integer is passed to it.
### Examples
prime_factors(20) ➞ [2, 2, 5]
prime_factors(100) ➞ [2, 2, 5, 5]
prime_factors(8912234) ➞ [2, 47, 94811]
### Notes
* Implement your solution using trial division.
* Your solution should not require recursion.
"""
def prime_factors(num):
lst = list()
first_factor = 2
while num > 1:
if num%first_factor == 0:
lst.append(first_factor)
num /= first_factor
else:
first_factor += 1
return lst
|
a383ddf5a5c20f507d58acb8d07a483680466130 | RawitSHIE/Algorithms-Training-Python | /python/cut The webtag r.py | 246 | 3.5625 | 4 | """strip"""
def main():
"""<p>"""
text = input()
if text.startswith("<p>") and text.endswith("</p>"):
pos = len(text)-4
textst = text[3:pos]
print("%100s" %textst)
else:
print("%100s" %text)
main()
|
4c600950b93d582ed3afde905b7fc0eb4f039610 | tsilagava/effective_python | /chapter3_functions/prefer_exceptions_to_None.py | 804 | 3.953125 | 4 | def careful_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
# x, y = 7, 0
# result = careful_divide(x, y)
# if result is None:
# print('Invalid inputs')
x, y = 5, 0
# result = careful_divide(x, y)
# if not result:
# print('Invalid inputs')
# def careful_divide(a, b):
# try:
# return True, a / b
# except ZeroDivisionError:
# return False, None
#
#
# success, result = careful_divide(x, y)
# if not success:
# print('Invalid inputs')
def careful_divide(a: float, b: float) -> float:
"""Divides a by b.
Raises:
ValueError: When the inputs cannot be divided.
"""
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('Invalid inputs')
print(careful_divide(5, 0))
|
b03dec334b95d4c4b77be30dcdd2df713ee1640b | Michaelbvb21/Python_Clases | /Clase 3/pares_impares.py | 451 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 17:06:28 2020
@author: Cristhoffer Carrasco
"""
numero=100
cont=1
suma_par=0
suma_impar=0
pares=[]
impares=[]
while cont<=numero:
if cont % 2 ==0:
pares.append(cont)
suma_par=suma_par+cont
else:
impares.append(cont)
suma_impar+=cont
cont=cont+1
print(pares)
print(f'La suma de los pares es {suma_par}')
print(impares)
print(f'La suma de los impares es {suma_impar}') |
2b092fc444677232107cbafb2e841c5cba05de8b | Zbylson90/creditcalc | /creditcalc.py | 2,784 | 3.609375 | 4 | import math
import argparse
def number_of_payments():
i = (float(args.interest)) / (12 * 100)
n = math.log((int(args.payment) / (int(args.payment) - i * int(args.principal))), 1 + i)
n = math.ceil(n)
n = int(n)
if n < 12:
if n == 1:
print(f"It will take 1 month to repay this loan!")
else:
print(f"It will take {n} months to repay this loan!")
elif n == 12:
print(f"It will take 1 year to repay this loan!")
elif 12 < n < 24:
print(f"It will take 1 year and {n % 12} months to repay this loan!")
else:
if n % 12 == 0:
print(f"It will take {n // 12} years to repay this loan!")
else:
print(f"It will take {n // 12} years and {n % 12} months to repay this loan!")
print(f"Overpayment is {int(args.payment) * n - int(args.principal)}")
def monthly_payment():
i = (float(args.interest)) / (12 * 100)
payment_amount = int(args.principal) * ((i * math.pow((1 + i), int(args.periods))) /
(math.pow(1 + i, int(args.periods)) - 1))
print(f"Your monthly payment = {math.ceil(payment_amount)}!")
print(f"Overpayment = {math.ceil(payment_amount) * int(args.periods) - int(args.principal)}")
def loan_principle():
i = (float(args.interest)) / (12 * 100)
loan = int(args.payment) / ((i * math.pow(1 + i, int(args.periods))) /
(math.pow(1 + i, int(args.periods)) - 1))
print(f"Your loan principal = {round(loan)}!")
print(f"Overpayment = {int(args.payment) * int(args.periods) - loan}")
def differ_payments():
total = 0
i = (float(args.interest)) / (12 * 100)
for x in range(1, int(args.periods) + 1):
monthly_amount = int(args.principal) / int(args.periods) + i * (int(args.principal) - (int(args.principal)
* (x - 1)) / int(args.periods))
monthly_amount = math.ceil(monthly_amount)
total += monthly_amount
print(f"Month {x}: payment is {monthly_amount}")
print(f"Overpayment = {total - int(args.principal)}")
parser = argparse.ArgumentParser()
parser.add_argument("--type")
parser.add_argument("--payment")
parser.add_argument("--principal")
parser.add_argument("--periods")
parser.add_argument("--interest")
args = parser.parse_args()
if args.interest is None:
print("Incorrect parameters")
elif args.type == "diff":
if args.payment is not None:
print("Incorrect parameters")
else:
differ_payments()
elif args.type == "annuity":
if args.payment is None:
monthly_payment()
elif args.periods is None:
number_of_payments()
elif args.principal is None:
loan_principle()
else:
print("Incorrect parameters")
|
0e5f9f2f249185de94384de13b7039d8ccbbda6b | KatarzynaSzlachetka/KakuroHashi | /Hashi/folders_display.py | 368 | 3.71875 | 4 | from tkinter import *
from tkinter import filedialog
def open_common_dialog():
"""
It opens common dialog and user can choose file
:return: file's path
"""
root = Tk()
root.fileName = filedialog.askopenfilename(filetype=(("png", ".png"), ("txt", ".txt"), ("all files", "*.*")))
path = root.fileName
root.destroy()
return path
|
6f658f4d94cb1ac5e4a58ec1e8a89dc8befcf18a | yamadagennji/leetcode | /game of life(uncompleted).py | 712 | 3.703125 | 4 |
def gameOfLife( board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
n=len(board)
m=len(board[0])
if len(board)==0:
return board
aa=[]
bb=[]#zhunbeiji
for a in range(0,len(board[0])):
aa.append(0)
for b in range(0,len(board)):
bb.append(list(aa))
bb[0][0]=board[0][1]+board[1][1]+board[1][0]
bb[n-1][0]=board[n-2][0]+board[n-1][1]+board[n-2][1]
bb[n-1][m-1]=board[n-2][m-1]+board[n-1][m-2]+board[n-2][m-2]
bb[0][m-1]=board[0][m-2]+board[1][m-1]+board[1][m-2]
for c in range(1,n+1):
bb[c][0]=bb[]
print(bb)
abc=gameOfLife([[1,0,1],[1,1,0]])
|
592d38a0b4d6747c1449ca8e9583035220e56017 | lishulongVI/leetcode | /python/268.Missing Number(缺失数字).py | 1,679 | 3.578125 | 4 | """
<p>Given an array containing <i>n</i> distinct numbers taken from <code>0, 1, 2, ..., n</code>, find the one that is missing from the array.</p>
<p><b>Example 1:</b></p>
<pre>
<b>Input:</b> [3,0,1]
<b>Output:</b> 2
</pre>
<p><b>Example 2:</b></p>
<pre>
<b>Input:</b> [9,6,4,2,3,5,7,0,1]
<b>Output:</b> 8
</pre>
<p><b>Note</b>:<br />
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?</p>
<p>给定一个包含 <code>0, 1, 2, ..., n</code> 中 <em>n</em> 个数的序列,找出 0 .. <em>n</em> 中没有出现在序列中的那个数。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [3,0,1]
<strong>输出:</strong> 2
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [9,6,4,2,3,5,7,0,1]
<strong>输出:</strong> 8
</pre>
<p><strong>说明:</strong><br>
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?</p>
<p>给定一个包含 <code>0, 1, 2, ..., n</code> 中 <em>n</em> 个数的序列,找出 0 .. <em>n</em> 中没有出现在序列中的那个数。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [3,0,1]
<strong>输出:</strong> 2
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [9,6,4,2,3,5,7,0,1]
<strong>输出:</strong> 8
</pre>
<p><strong>说明:</strong><br>
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?</p>
"""
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
""" |
8dd6dbdd098f465f103cc65afc4170241ace64d1 | erikkrasner/Project-Euler | /prob4_solution.py | 984 | 3.734375 | 4 | #!/usr/bin/env python
# 906609
# 1.689 s
import sys
import heapq
def descending_products_from(minimum, maximum):
products = [(-(maximum * maximum),maximum)]
small_multiplicand = maximum
while products:
product,multiplicand = heapq.heappop(products)
yield -product
if small_multiplicand > minimum and multiplicand == small_multiplicand:
small_multiplicand -= 1
for big_multiplicand in xrange(maximum,small_multiplicand - 1,-1):
heapq.heappush(products,(-(small_multiplicand * big_multiplicand),small_multiplicand))
def palindromic(n):
if type(n) is not str:
n = str(n)
left,right = 0,len(n)-1
while left < right:
if n[left] != n[right]:
return False
left,right = left+1,right-1
return True
def largest_palindromic_n_digit_product(n):
for product in descending_products_from(10**(n-1),(10**n)-1):
if palindromic(product):
return product
print largest_palindromic_n_digit_product(int(sys.argv[1]) if sys.argv[1:] else 3)
|
0c7fb77e9d4406726c0b4a78686a612a54dae2ee | lics1216/python | /1语法/dictAndSet.py | 1,088 | 4.1875 | 4 | # 使用key-value存储结构的dict在Python中非常有用,选择不可变对象作为key很重要,最常用的key是字符串。
# tuple虽然是不变对象,但试试把(1, 2, 3)和(1, [2, 3])放入dict或set中,并解释结果
# -*- coding: utf-8 -*-
#set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
#要创建一个set,需要提供一个list作为输入集合:
s1 = set([1, 1, 2, 2, 3, 3])
print(s1)
s2 = set([2, 3, 4]) #调用 add 和 remove 方法
print(s1 & s2) # s1 s2 的交集
print(s1 | s2) # s1 s2 的并集
#记住 dict 字典类型使用 {} 表示,,,
d = {
'Michael': 95,
'Bob': 75,
'Tracy': 85
}
print('d[\'Michael\'] =', d['Michael'])
print('d[\'Bob\'] =', d['Bob'])
print('d[\'Tracy\'] =', d['Tracy'])
print('d.get(\'Thomas\', -1) =', d.get('Thomas', -1)) # key没有的,返回None , 或者自己指定的值 -1
# >>> a = 'abc'
# >>> b = a.replace('a', 'A')
# >>> b // b是字符串 不可变对象
# 'Abc'
# >>> a
# 'abc' |
4f61787a92dd683280cccc8cc8ee8370bb8eec12 | Sergey-Kul/pythonProject | /2.1-F(x).py | 187 | 3.515625 | 4 | import math
def f_x(x):
try:
y = 1 / (x+1) + x / (x-3)
except:
y = math.inf
return y
t = float (input('t = '))
y = f_x(t)
print('f(%4.2f) = %6.3f' % (t, y))
|
da1f6e02069a396151b5428f848938b00ea02918 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4058/codes/1668_2972.py | 208 | 3.65625 | 4 | So=int(input("qual sua posicao inicial?"))
v=int(input("qual sua velocidade?"))
t=int(input("qual o seu tempo de deslocamento?"))
S=So+(v*t)
if (S>=1000):
print(S)
print('Sim')
else:
print(S)
print('Nao') |
d9ef4c188c561de3c0cb3aa8d04617ab3a802261 | MalSemik/nauka-5.0 | /Spoj/sort.py | 680 | 3.875 | 4 | def reverse_sort_without_doubles():
tests = int(input())
for i in range(tests):
line = []
item = input()
item = item.split(" ")
for j in range(len(item)):
line.append(int(item[j]))
line.sort(reverse=True)
newlist = [ii for n, ii in enumerate(line) if ii not in line[:n]]
for k in range(len(newlist)):
print(str(newlist[k])+" ", end="")
def rozwiąż_spoj_tablice():
tests = int(input())
for i in range(tests):
items = input()
items = items.split(" ")
result = items[-1:0:-1]
for i in result:
print(i, end=" ")
rozwiąż_spoj_tablice()
|
6d4d5c430301d8eb871c245fcf538bf3b33d59f2 | shelman/algo | /py/strings/permutations.py | 323 | 3.578125 | 4 | def permutations(s):
if len(s) == 1:
return [s]
res = []
for idx, letter in enumerate(s):
res.extend([letter + p for p in permutations(s[:idx] + s[idx+1:])])
return set(res)
def main():
print(permutations('abdia'))
print(permutations('cat'))
if __name__ == '__main__':
main() |
0b011bab56d6584d783c8ad5e0f1bac67a7f52f4 | 1i0n0/Python-Learning | /practices/factorial.py | 611 | 4.4375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Find factorial of number
import sys
import math # another solution using math.factorial
# Find factorial of number using recursion
def my_factorial(num):
if num < 0:
print("It is not a positive integer.")
sys.exit(1)
elif num == 0:
return 1
else:
return num * my_factorial(num - 1)
if __name__ == "__main__":
number = int(input("Enter a positive integer: \n"))
result = my_factorial(number)
assert result == math.factorial(number)
if result:
print(f"The factorial of {number} is {result}.")
|
ae0f418828815207d54ee3f0eec97fda3adba695 | dertajora/learn_python | /looping.py | 718 | 3.96875 | 4 | numbers = [1,2,3,4,5,6,7]
for number in numbers:
if number % 2 == 0:
print(number)
# x = 0 - 4
for x in range(5):
print(x)
# x = 3 - 5
for x in range(3,6):
print(x)
# x = 3,5,7 karena intervalnya = 2 , batas awal = 3, batas akhir = 8
for x in range(3,8,2):
print(x)
#while
count = 0
while count < 5:
print(count)
count += 1
#use continue when condition meet, skip 1 loop saja
for x in range(1,10):
if x % 2 == 0:
continue
print(x)
#use break when condition meet, stop the loop
for x in range(1,10):
if x >= 5:
break
print(x)
# else condition in loop
count = 0
while(count<5):
print(count)
count += 1
else:
print("Value count reached 5")
# credit : https://www.learnpython.org/en/Loops |
1cfac565786a763d8b033d6e77465b1b0a19b3ac | melaniesifen/Elements-of-Software-Design | /basic-alg/Work.py | 1,931 | 4.0625 | 4 | # Background: Vyasa has to complete a programming assignment overnight.
# This is how he plans to write the program. He will write the first v lines of code, then drink his first cup of coffee. Since his productivity has gone down by a factor of k he will write v // k lines of code. He will have another cup of coffee and then write v // k**2 lines of code. He will have another cup of coffee and write v // k**3 lines of code and so on. He will collapse and fall asleep when v // k ** p becomes 0.
# Now Vyasa does want to complete his assignment and maximize on his sleep. So he wants to figure out the minimum allowable value of v for a given productivity factor that will allow him to write at least n lines of code before he falls asleep.
# see input file work.txt
# binary search for min v value
def binary_search(n, k):
lo = 1
hi = n
while lo <= hi:
mid = (lo + hi) // 2
v = formula(mid, k) # mid is the v value we're testing
if hi == lo:
if v < n:
return mid + 1 # need v to be AT LEAST n
else:
return mid
elif v < n: # not enough lines of code
lo = mid + 1
elif v > n: # working too hard/not enough sleep
hi = mid - 1
else:
return mid
# applies formula for mid value
def formula(v, k):
# keep going until v // k ** p == 0
p = 0
lines = 0
while (v // k ** p) > 0:
lines += (v // k ** p)
p += 1
return lines
# reads file and calls binary search function
def main():
inf = open("work.txt", "r")
firstline = int(inf.readline())
for i in range(firstline): # num of test cases
line = inf.readline()
line = line.strip()
line = line.split()
n = int(line[0])
k = int(line[1])
print(binary_search(n, k))
main()
|
0905588dc5c507a73972c41b7bb31c55e184b9c3 | mingziV5/python_script | /pattern/factory.py | 2,120 | 4.21875 | 4 | #!/usr/bin/python
#设计模式 工厂模式
class Burger():
name = ''
price = 0.0
def getPrice(self):
return self.price
def setPrice(self, price):
self.price = price
def getName(self):
return self.name
class cheeseBurger(Burger):
def __init__(self):
self.name = 'cheese burger'
self.price = 10.0
class spicyChickenBurger(Burger):
def __init__(self):
self.name = 'spicy chicken burger'
self.price = 15.0
class Snack():
name = ''
price = 0.0
type = 'SNACK'
def getPrice(self):
return self.price
def setPrice(self, price):
self.price = price
def getName(self):
return self.name
class chips(Snack):
def __init__(self):
self.name = 'chips'
self.price = 6.0
class chickenWings(Snack):
def __init__(self):
self.name = 'chicken wings'
self.price = 12.0
class Beverage():
name = ''
price = 0.0
type = 'BEVERAGE'
def getPrice(self):
return self.price
def setPrice(self, price):
self.price = price
def getName(self):
return self.name
class coke(Beverage):
def __init__(self):
self.name = 'milk'
self.price = 5.0
#工厂类
class foodFactory():
type = ""
def createFood(self, foodClass):
print(self.type + ' factory produce a instance.')
foodIns = foodClass()
return foodIns
class burgerFactory(foodFactory):
def __init__(self):
self.type="BURGER"
class snackFactory(foodFactory):
def __init__(self):
self.type="SNACK"
class beverageFactory(foodFactory):
def __init__(self):
self.type="BEVERAGE"
if __name__ == "__main__":
burger_factory = burgerFactory()
snack_factory = snackFactory()
beverage_factory = beverageFactory()
cheese_burger = burger_factory.createFood(cheeseBurger)
print(cheese_burger.getName())
chicken_wings = snack_factory.createFood(chickenWings)
print(chicken_wings.getName())
coke_drink = beverage_factory.createFood(coke)
print(coke_drink.getName())
|
c014b749926bfcc94a895ef2c849d019acff3b6e | Aakanshakowerjani/Linked_List-Codes | /Reversing-Singly-LinkedList.py | 993 | 4.03125 | 4 | class SinglyLinkedlist:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def addNode(self, data):
if self.next_node != None:
self.next_node.addNode(data)
else:
self.next_node = SinglyLinkedlist(data)
def printLinkedList(self):
print("->", self.data, end=" ")
if self.next_node != None:
self.next_node.printLinkedList()
def printReverse(self):
if self.next_node != None:
self.next_node.printReverse()
print("->", self.data, end=" ")
def main():
root = SinglyLinkedlist(input("enter root node \n"))
nodes = list(map(str, input("\nenter nodes separated by space\n").split()))
for node in nodes:
root.addNode(node)
print("\nLinked List\n")
root.printLinkedList()
print("\nReverse Linked List\n")
root.printReverse()
if __name__ == "__main__":
main()
|
0a9cf8746cddf6075a90c1cd7adbb9a99a97cdd1 | Kyetuur/PythonProject | /IntervalGenerator.py | 1,267 | 3.546875 | 4 | import random
import Interval as Interval
import logging
logger = logging.getLogger(name="IntervalGenerator")
def get_random_root():
root = random.choice(Interval.notes)
logger.debug(f"Get random root returned {root}")
return root
def get_random_interval_from_root(root):
second_note = random.choice(Interval.notes)
interval = Interval.Interval(root, second_note)
logger.debug(f"Get random interval from root returned {interval}")
return interval
def get_random_interval():
random_interval = get_random_interval_from_root(get_random_root())
logger.debug(f"Get random interval {random_interval}")
return random_interval
def get_random_increasing_interval():
interval = get_random_interval()
while not interval.check_if_increasing():
logger.debug(f"Rerolling interval, current {interval}")
interval = get_random_interval()
logger.debug(f"Get random increasing returned {interval}")
return interval
def get_random_not_egdy_number():
interval = get_random_increasing_interval()
while interval.get_interval_number() == 0 or interval.secondNote == 'B':
interval = get_random_increasing_interval()
logger.debug(f"Get random not edgy {interval}")
return interval
|
f697623eb6a1e5dc552ce2e29017de2bb28f61f4 | jamie0725/LeetCode-Solutions | /461HammingDistance.py | 730 | 4.40625 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
"""
#solution 1:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
#solution 2:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
result = []
bit = str(bin(x ^ y))
for i in range(len(bit)):
result.append(bit[i])
return result.count('1')
|
e5d0378872feb218e994f6aa279f031003f089d6 | RealNerdEthan/Django-Python-Tutorial | /python_intro_2.py | 415 | 3.765625 | 4 | # This is my first Python function!
# def hi():
# print('Hi there!')
# print('How are you?')
# hi()
# My second Python function!
# def hi(name):
# if name == 'Doug':
# print('Hi Doug!')
# elif name == 'Ethan':
# print('Hi Ethan!')
# else:
# print('Hi stranger!')
# hi('Ethan')
# My third Python function!
def hi(name):
print('Hi ' + name + '!')
hi('Ethan')
|
9f87cb1a289e23571f1956fa22228fca93b72ee4 | loukey/pythonDemo | /chap4/exp4.21.py | 148 | 3.5 | 4 | # -*- coding: utf-8 -*-
#例4.21小心谨慎地使用测试条件:豆子数不够
beans = 4
count = 1
while count<beans:
print 'bean'
count += 1 |
25550e5b654c0a196c16f3d259acc5014e48e1b3 | bensonnd/NeilDBenson | /pivotFunction.py | 842 | 4.09375 | 4 | def listsPivot(pivotInput):
"""This function takes a list of lists, and rotates the 'grid' 90
degrees clockwise. ex. listToInvert[8,0] becomes listToInvert[0,0],
listToInvert[0,0] becomes listToInvert[0,5] in 5x9 'grid'."""
masterList = []
for i in range(len(grid[0])): #012 - indeces of the first row
listHolder = []
for j in range(len(grid)): #012345 - indeces of the first column
tempVar = grid[j][i] #invert the indeces
listHolder.append(tempVar) #updates the list with the inverted value. Creates a list for each row.
masterList.append(listHolder) #adds each new inverted row to the masterList
return masterList
grid = [['1', '2', 'A', '4', '5', '6'],
['1', '2', '3', 'F', '5', '6'],
['1', '43', '3', '4', '5', '6']]
print(listsPivot(grid))
|
e01a6457d6e5bbee4324af9061051b0e268d32d9 | 2B-people/2B-repositery | /leetcode/48_rotate.py | 2,395 | 3.84375 | 4 | '''
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
'''
# TODO 翻转矩阵解决方案
from coding_analyze import Timer
class Solution:
# 72ms,mine
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
# 根据对角线,找对应位置,互换两个数字的值。
for i in range(n):
for j in range(i+1,n):
matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]
# 对每一行数字,根据中线左右翻转。
for i in range(n):
for j in range(n//2):
matrix[i][j],matrix[i][n-j-1] = matrix[i][n-j-1],matrix[i][j]
# or
# for i in range(length):
# matrix[i] = matrix[i][::-1]
#40ms
def rotate2(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if matrix == None or len(matrix) <= 1:
return
def swap(i, j, x, y):
temp = matrix[i][j]
matrix[i][j] = matrix[x][y]
matrix[x][y] = temp
n = len(matrix)
for i in range(0, n):
for j in range(i, n-i-1):
swap(i,j, n-j-1, i)
swap(n-j-1, i, j, n-i-1)
swap(n-j-1, i, n-i-1, n-j-1)
if __name__== '__main__':
with Timer() as t:
sol = Solution()
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
for i in range(len(matrix)):
print(matrix[i])
print('than:')
sol.rotate(matrix)
for i in range(len(matrix)):
print(matrix[i])
|
4e6d62f672f1a90d7aaccc8595a16a5203cfdeff | Bit4z/python | /python_special/num2.py | 883 | 3.796875 | 4 | import numpy as np
arr=np.array([1,2,3,4],ndmin=7)
print("Number of diamensions:",arr)
print("<----------------------------------------------------------------------------->")
print(" Array accessing elements")
arr=np.arange(10)
for i in range(10):
print(arr[i])
print("sum=",arr[i]+arr[i])
print(" Access 2D array")
arr2=np.array([[1,2,3,4],[7,8,9,10]])
print(len(arr2))
print("2d array elements:")
for i in range(len(arr2)):
for j in range(len(arr2[i])):
print(arr2[i][j])
print("<------------------------------------------------------------------------------->")
print(" Access 3D array elements")
arr3=np.array([[[12,13,14,17],[18,19,20,21]],[[22,23,24,27],[28,29,30,31]]])
print(arr3)
print(arr3[0,1,2])
print(arr3[0,2,1])
|
aafc9bcc803c65f10004c6228e78b92a9ea24d05 | santhosh0204/code-kata | /oddnumbersbwintervals.py | 101 | 3.5 | 4 | s,a=raw_input().split()
s=int(s)
a=int(a)
for i in range(s+1,a+1):
if(i%2!=0):
print(i),
|
6b21544f8a4d20e18277dead7a453ae15160532f | arnabs542/achked | /python3/sorting/heapsort.py | 937 | 3.96875 | 4 | #!/usr/bin/env python3
def swap(a, i, j):
temp = a[i]
a[i] = a[j]
a[j] = temp
def max_heapify(a, i, sz):
left = 2 * i
right = 2 * i + 1
if left < sz and a[i] < a[left]:
largest = left
else:
largest = i
if right < sz and a[right] > a[largest]:
largest = right
if i != largest:
swap(a, i, largest)
max_heapify(a, largest, sz)
def heapsort(a):
sz = len(a)
# we can go from sz//2 to 0 or sz to 0, it doesn't matter since
# the guard conditions are protecting the largest check.
for i in range(sz//2, -1, -1):
max_heapify(a, i, sz)
for sz in range(len(a) - 1, -1, -1):
# following is an optimization
#if a[0] > a[sz]:
swap(a, 0, sz)
max_heapify(a, 0, sz - 1)
def main():
l = [4, 3, 45, 2, 22, 15, 6, 22, 19, 18, 27]
heapsort(l)
print(l)
if __name__ == '__main__':
main()
|
ae2618e18d4506d7549a049fca3e28637c9c0062 | michaelChen07/studyPython | /cn/wensi/practice/factorial.py | 452 | 3.84375 | 4 | #encoding=utf-8
#求一个正整数的阶乘
#方法一:
def factorial(n):
if n == 0 or n == 1:
return 1
number = 1
for i in range(2,n+1):
number *= i
return number
print factorial(4)
#方法二:递归
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
print factorial(4)
#方法三:reduce()函数
n=input('input your number: ')
print reduce(lambda x,y:x*y,range(1,n+1)) |
0b79be6fa993d0e21175731acef42cc2474b1586 | BigDataRoad/Algorithm | /src/main/com/libin/yfl/13.py | 1,539 | 3.828125 | 4 | '''
2. 两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
list1 = []
list2 = []
l1_ = l1
l2_ = l2
while l1_:
list1.append(l1_.val)
l1_ = l1_.next
while l2_:
list2.append(l2_.val)
l2_ = l2_.next
int1 = 0
for i in range(len(list1)-1,-1,-1):
int1 += list1[i] *10**i
int2 = 0
for i in range(len(list2)-1,-1,-1):
int2 += list2[i] *10**i
c = int1 + int2
c_list = list(str(c))
cur_ = ListNode(0)
cur = cur_
for i in range(len(c_list) - 1, -1, -1):
linshi = ListNode(0)
linshi.val = int(c_list[i])
cur.next = linshi
cur = cur.next
return cur_.next |
db7e9512f357f322fb43ee5fc4193c7bf560cbbb | avnkailash/blog_api | /api/core/tests/test_models.py | 2,441 | 3.5 | 4 | from django.test import TestCase
from django.contrib.auth import get_user_model
def sample_user(email='user@test.com', password='Test123'):
"""
Helper method to create a sample user for our test cases!
:param email: Email address of the sample user
:param password: A password for account creation.
This can be a weak password as well since this is restricted
to our testing environment.
:return: Returns the created user object
"""
# We will be relying on the get_user_model() from
# the auth module to ensure that the user model
# can be switched in future without any new bugs getting introduced.
return get_user_model().objects.create_user(email, password)
class ModelTestScenarios(TestCase):
"""A testing class that holds all the test cases specific to models."""
def test_create_user_with_email_successful(self):
"""
A test case to check the creation of a user account
with valid details provided.
:return: None
"""
email = 'testUser@test.com'
password = 'Test123'
user = sample_user(email=email, password=password)
# Assertions to check if the results are as expected.
self.assertEqual(user.email, email)
# We cannot check the password just like an email field.
# We have to rely on the check_password helper method of
# the user object
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
"""
A test to validate if the email string is normalized for a new user
:return: None
"""
email = 'user@TEST.COM'
user = sample_user(email=email)
# Checking if the email in the user object is normalized
self.assertEqual(user.email, email.lower())
def test_new_user_invalid_email(self):
"""
A test to create uesr with invalid email.
We should see a ValueError in such cases.
:return: None
"""
with self.assertRaises(ValueError):
sample_user(email=None)
def test_create_new_super_user(self):
"""
A test to check if super user creation is working as expected
:return: None
"""
user = get_user_model().objects.create_superuser(
'moderator@test.com',
'Moderator123'
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
|
155d599f4dbdcf967aed3f0d11565f5e93dc6588 | CriMilanese/bench | /utils/class_edge.py | 1,531 | 3.828125 | 4 | """
the class describing a single directed connection between two hosts
"""
from tkinter import FIRST, Label, StringVar
from globals import WHITE, LIGHT_BLUE, root
from math import floor
class Edge():
def __init__(self, source, target, lf):
self.source = source
self.dest = target
self.lifetime = lf
self.string_result = ''
def show(self, anchor, a, b):
"""
pass two instances of node to draw a line in between
this is for the gui to be able to change the connection label on the fly
as each client returns the results
"""
self.body = anchor.create_line(a.x, a.y, b.x, b.y, arrow=FIRST)
self.result = StringVar()
self.label = Label(anchor, textvariable=self.result, fg=WHITE, bg=LIGHT_BLUE)
middle = ((a.x+b.x)/2, (a.y+b.y)/2)
self.label.place(x=middle[0], y=middle[1])
def outcome(self, caller):
"""
modify the value of this instance variable will cause the label of
the edge on the GUI to update with the reported bandwidth for that
connection
"""
tmp = caller.result()
self.result.set(str(floor(tmp.bandwidth))+" B/s")
self.string_result = str(floor(tmp.bandwidth))+" B/s"
print(self.string_result)
def create_hash(a, b):
"""
concatenate the strings allows for unique connections given
the direction of the communication.
"""
return hash(str(hash(a)).join(str(hash(b))))
|
00e0046c186cef5f6855be648ff60274195fa669 | SiddharthaPramanik/Assessment-VisualBI | /music_app/artists/models.py | 754 | 3.5 | 4 | from music_app import db
from music_app.albums.models import Albums
class Artists(db.Model):
"""
A class to map the artists table using SQLAlchemy
...
Attributes
-------
artist_id : Integer database column
Holds the id of the artist
artist : String databse column
Holds the artist's name
albums : Relationship
A relationship to albums table
Methods
-------
__repr__()
Method to represent the class object
"""
artist_id = db.Column(db.Integer, primary_key=True)
artist = db.Column(db.String(30), nullable=False)
albums = db.relationship('Albums', backref='albums', lazy=True)
def __repr__(self):
return f"Artists('{self.artist}')" |
736df9b2db251bdbaa15fe2519af198c4f4ee5ee | Anil2144/python-basics | /mycode.py | 88 | 3.75 | 4 | i=1
j=int(input("enter a number"))
f=1
while i<=j :
f=f*i
i=i+1
print(f)
|
512be48f3f46f0e72dc69b4e9dac75bd41aa3a00 | lmdpadm/Python | /desafio40.py | 668 | 3.859375 | 4 | import time
print('Me diga suas notas, que lhe direi se foi aprovado:')
time.sleep(1)
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
média = (n1 + n2) / 2
if média < 5:
print('A sua média foi de {:.2f}, abaixo do mínimo de 5.00, então está R E P R O V A D O!'.format(média))
elif média >= 5 and média <= 6.9:
print('A sua média foi de {:.2f}, não atingiu o mínimo de 7.00, então fará recuperação.'.format(média))
elif média >= 7:
print('Parabéns, a sua média foi {:.2f}, maior do que 7.00, você está aprovado!'.format(média))
else:
print('Algo está errado em suas notas, tente novamente!') |
56b2fbdbef3b21df51ddb8d2d179c079e37849c8 | ErenBtrk/PythonNumpyExercises | /Exercise53.py | 452 | 4.40625 | 4 | '''
53. Write a NumPy program to extract all numbers from a given
array which are less and greater than a specified number.
'''
import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 4.38, 6.99],
[1.54, 2.39, 9.29]])
print("Original array:")
print(nums)
n = 5
print("\nElements of the said array greater than",n)
print(nums[nums > n])
n = 6
print("\nElements of the said array less than",n)
print(nums[nums < n]) |
c43748ec01f3051c0bea61045319a3260781c91d | pbjsowon408/pyGame | /4_keyboard_event.py | 2,511 | 3.671875 | 4 | import pygame
pygame.init() # initiation
# Setting Screen size
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
# Screen Title Setting
pygame.display.set_caption("Python Game") # Game title
# get background img
background = pygame.image.load("C:/Programmings/pyGame/background.png")
# get character img
character = pygame.image.load("C:/Programmings/pyGame/character.png")
character_size = character.get_rect().size # get image size
character_width = character_size[0] # character width size
character_height = character_size[1] # character height size
# set character width location in the middle of the screen
character_x_pos = (screen_width / 2) - (character_width / 2)
# set character height location in the botton of the screen
character_y_pos = screen_height - character_height
# coordinates to move
to_x = 0
to_y = 0
# event Loop
running = True # Check if the game is running
while running:
for event in pygame.event.get(): # Which event has been occured
if event.type == pygame.QUIT: # Close Screen event is occured
running = False # Game not running
if event.type == pygame.KEYDOWN: # check if the key is pushed
if event.key == pygame.K_LEFT: # move character left
to_x -= 5
elif event.key == pygame.K_RIGHT: # move character right
to_x += 5
elif event.key == pygame.K_UP: # move character up
to_y -= 5
elif event.key == pygame.K_DOWN: # move character down
to_y += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
character_x_pos += to_x
character_y_pos += to_y
# weight limit
if character_x_pos > 0:
character_x_pos = 0
elif character_x_pos > screen_width - character_width:
character_x_pos = screen_width - character_width
# height limit
if character_y_pos > 0:
character_y_pos = 0
elif character_y_pos > screen_height - character_height:
character_y_pos = screen_height - character_height
screen.blit(background, (0, 0)) # paint background
# create character
screen.blit(character, (character_x_pos, character_y_pos))
pygame.display.update() # game background paint again
# pygame quit
pygame.quit()
|
1d999ce7d6de1237b249dbccc9497f3735bd21e3 | Hidenver2016/Leetcode | /Python3.6/448-Py3-find-all-numbers-disappeared-in-an-array.py | 920 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 17:06:57 2018
@author: hjiang
"""
#Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
#
#Find all the elements of [1, n] inclusive that do not appear in this array.
#
#Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
#
#Example:
#
#Input:
#[4,3,2,7,8,2,3,1]
#
#Output:
#[5,6]
import numpy as np
def find_number(list1):
max_number = max(list1)
temp_list = list(np.arange(1,max_number+1))
set_temp_list = set(temp_list)
set_list = set(list1)
missing_number = set_temp_list - set_list
return list(missing_number)
def find_number1(nums):
return list(set(range(1, len(nums) + 1)) - set(nums))
if __name__ == "__main__":
print (find_number1([4,3,2,7,8,2,3,1])) |
07b1e0f6714ae645218722d1759b6d0dfadea6b9 | aburan28/python-datastructures | /random/karatsubaMultiplication.py | 505 | 3.703125 | 4 |
def multiply(x,y):
"""
"""
if x.bit_length() <= 2000 or y.bit_length() <= 2000:
return x * y
else:
n = max(x.bit_length(),y.bit_length())
mid = (n + 32) // 64 * 32
nmask = (1 << half) - 1
xlow = x & nmask
ylow = y & nmask
xhigh = x >> mid
yhigh = y >> mid
a = multiply(xhigh,yhigh)
b = multiply(xlow + xhigh, ylow + yhigh)
c = multiply(xlow,ylow)
d = b - a - c
return (((a << half) + d) << half) + c
if __name__ == '__main__':
import unittest
|
e5a66af8154f0f98bcac963be707dcffc39e3fad | nanisaladi24/Leetcode_py_codes | /Easy/valid_parenthesis.py | 770 | 3.625 | 4 | def soln(myStr):
lookup1="[{("
lookup2="]})"
if myStr=="":
return True
myStack=list()
# myStack.append(1)
# myStack.pop()
#print (myStack)
if myStr[0] in lookup2:
return False
temp=""
for i in myStr:
if i in lookup1:
myStack.append(i)
temp=i
if i in lookup2:
if i==lookup2[lookup1.index(temp)]:
myStack.pop()
if len(myStack)>0:
temp=myStack[-1]
else:
return False
if myStack==[]:
return True
else:
return False
myStr="[]{}()"
print(soln(myStr))
myStr="[]{[]}]()"
print(soln(myStr))
myStr="[]{}([])"
print(soln(myStr))
myStr="[]{{{}}([])}"
print(soln(myStr)) |
cc93c06d201c6dbd3528220237d81c8ec6ebefee | carlosalvarezdeloscobos/1.Bootcamp | /2. Python challenge- Py me up charlie/Pybank2.py | 2,500 | 3.625 | 4 | import os
import csv
months= []
profit=[]
changes=[]
#/Users/carlosalvarez/Desktop/Boot/3 Python Intro/Python Intro Hmwk
#pybank_csv = os.path("Users/carlosalvarez/Desktop/Boot/3 Python Intro/Python Intro Hmwk")
pybank_csv = os.path.join("..","Python Intro Hmwk", "budget_data.csv")
#open de file and use de csv module to read it
with open(pybank_csv, newline='') as csvfile_pybank:
csvreader_pybank = csv.reader(csvfile_pybank, delimiter=",")
# extract the information to the months and profits list
for row in csvreader_pybank:
months.append(row[0])
profit.append(row[1])
#remove information to start the operations
months.remove('Date')
profit.remove('Profit/Losses')
# Format profit to integeres
profit_integer= [int(x) for x in profit]
for i in range(0,len(profit_integer)):
changes.append(profit_integer[i] - profit_integer[i-1])
changes_integer= [int(x) for x in changes]
changes_integer.remove(changes_integer[0])
addchanges=0
for x in range(1,len(changes_integer)):
addchanges= addchanges + changes_integer[x]
# total months, total profit, ave change, greatest & lowest profit (with dates)
total_months= len(months)
total_profit= sum(profit_integer)
avechange= addchanges/(len(changes_integer))
greatest_profit= max(profit_integer)
minimum_profit= min(profit_integer)
#Use the following to identify wich months were the greatest and minimum profit
#zip_pybank_data= zip(months,profit)
#for months,profit in zip_pybank_data:
# print(months,profit)
#print results
print('TOTAL MONTHS: ' + str(total_months))
print('TOTAL PROFIT: ' + str(total_profit))
print('AVERAGE CHANGE: ' + str(avechange))
print('GREATEST INCREASE profit: ' + str(greatest_profit)+ ' month: ' + str(months[25]))
print('GREATEST DECREASE profit: ' + str(minimum_profit) + ' month: '+ str(months[44]))
# Export results to a new csv file
output_path = os.path.join("..","Python Intro Hmwk", "new_PYBANK.csv")
# Open the file using "write" mode. Specify the variable to hold the contents
with open(output_path, 'w', newline='') as new_pybank:
# Initialize csv.writer
csvwriter = csv.writer(new_pybank, delimiter=',')
# Write the first row (column headers)
csvwriter.writerow(['Total Months: ', total_months])
csvwriter.writerow(['Total Profit: ', total_profit] )
csvwriter.writerow(['GREATEST INCREASE profit: ', greatest_profit,' month: ', months[25]])
csvwriter.writerow(['GREATEST DECREASE profit: ', minimum_profit ,' month: ', months[44]]) |
c794afe934d5efa150c107b61c2882fd53009415 | 15988108363/Github | /2020.07.26-mysql增删改查.py | 1,511 | 3.828125 | 4 | """pymysql增删改查"""
import pymysql
#连接数据库
db = pymysql.connect(host="localhost",port=3306,user= "root",
password="Q13470819781q",database="exercise",
charset= "utf8mb4")
#获取游标
cur = db.cursor()
name =input("name:")
age= input("age:")
sex = input("sex:")
score= input("score:")
# sql ="""insert into class_1 (name,age,sex,score) \
# values (%s,%d,%s,%f);"""%(name,age,sex,score)
# try:
# cur.execute(sql)
# db.commit()
# except Exception as e:
# print(e)
# db.rollback()#回滚到操作之前的状态
sql ="insert into class_1 (name,age,sex,score) \
values (%s,%s,%s,%s);"#不需要强转格式
try:
cur.execute(sql,[name,age,sex,score])#自动识别参数类别
db.commit()
except Exception as e:
print(e)
db.rollback()#回滚到操作之前的状态
#写操作
try:
sql ="""insert into interest values \
(8,"Bob","draw,sing","A","7777","凑合");"""#写入操作
cur.execute(sql)
sql = """update interest set price=6666 \
where name="Abby";"""#更新操作
cur.execute(sql)
sql = """delete from class_1 where score<88;""" # 删除操作
cur.execute(sql)
db.commit()
except Exception as e:
db.rollback()
print("出现异常为",e)
#读操作
sql = "select * from class_1 where age=13;"
#执行语句
cur.execute(sql)
one_row = cur.fetchone()
print(one_row)
maney_row = cur.fetchone(2)
print(maney_row)
all_row = cur.fetchall()
print(all_row)
cur.close()
db.close() |
502cc8403fc098ea34efb81916eb84b7efa53152 | DarkMatter188/factorial_generator | /challenge3.py | 202 | 4.0625 | 4 | # Factorial of a number using generator
def factorial(n):
a=1
fact=1
while(a<=n):
yield fact
fact=fact*a
a+=1
f=factorial(10)
for i in f:
print(i) |
4b2477eafcdf946864885c719e80c8589359015c | EpsilonHF/Leetcode | /Python/367.py | 367 | 3.921875 | 4 | """
Given a positive integer num, write a function which returns
True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
"""
class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while i * i < num:
i = 1
return i * i == num
|
a72ca72399928adaf18620e492c4f03ca10c99b4 | shrey920/IT200-DSA | /lab1/p2.py | 485 | 3.859375 | 4 | def fib(n):
if n==1:
print (0)
return
elif n==2:
print (0,",",1)
return
elif n>2:
f1=0
f2=1
print (f1,",",f2, end=", ")
for i in range(2,n):
f=f1+f2
print (f, end=", ")
f1=f2
f2=f
def fibr(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibr(n-1)+fibr(n-2)
n=int(input("Enter limit: "))
print ("Fibonacci series by iteration: ")
fib(n)
print ("\nFibonacci series by recursion: ")
for i in range(0,n):
print (fibr(i),end=", ")
print () |
b8d9099c88384a6b61062678d3e73b30658fa09b | gusenov/test-tech-mail-ru-python2 | /question17.py | 287 | 3.53125 | 4 | s = 'Hello, World!'
print len(s) # 13
print unicode(s) # Hello, World!
print id(s) # 140369511854520
# print length(s) # NameError: name 'length' is not defined
# print find(s) # NameError: name 'find' is not defined
# print indexOf(s) # NameError: name 'indexOf' is not defined
|
6978a02380fdbdcebfe5b08e24c5dedce51313bd | naimishbhagat/python3 | /data_structure/lists.py | 3,949 | 4 | 4 | from collections import deque
letters = ["a", "b", "c"]
# list of lists
matrix = [[0, 1], [2, 3]]
# lists of 100 0's
zeros = [0] * 100
zeros = [0] * 5
combined = zeros + letters
# merge two lists with +
print(zeros, combined)
# loop 0...20
numbers = list(range(20))
print(numbers)
# loop through string characters
strings = list("Hello world")
print(strings)
print(len(strings))
letters = ["a", "b", "c", "d"]
print(letters[0]) # first item
print(letters[-1]) # last item
# change item
letters[0] = 'e'
print(letters)
# return items between index first 2 items
print(letters[0:2])
# if not specified then it will start from 0 same if end index not specified then it will take total length
print(letters[:2])
print(letters[2:])
print(letters[:]) # will take full list
print(letters[::2]) # will return every 2nd element => result: ['e', 'c']
numbers = list(range(20))
# skip every second element = result [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print(numbers[::2])
# unpacking list
numbers = [1, 2, 3]
first, second, third = [1, 2, 3]
print(first, third)
numbers = [1, 2, 3, 4, 4, 5]
first, second, *other = numbers # other is remaining items
print(first, other)
first, *other, last = numbers # other is middle items
print(first, other)
def multiply(*numbers):
total = 1
for number in numbers:
total *= number
return total
print(multiply(1, 2, 3, 4, 5))
letters = ["a", "b", "c"]
for letter in enumerate(letters):
print(letter[0], letter[1])
# list unpacking
for key, value in enumerate(letters):
print(key, value)
# add item
letters = ["a", "b", "c"]
letters.append("d")
print(letters)
# add item to specific index
letters.insert(0, "-")
print(letters)
# remove item
letters.pop() # last element
print(letters)
letters.pop(0) # first element
del letters[0:1]
print(letters)
letters.remove("b") # first "b" element
print(letters)
letters.clear() # remove whole
print(letters)
# find item
letters = ["a", "b", "c"]
index = letters.index("c")
print(index)
if "d" in letters:
print(letters.index("d"))
print(letters.count("d")) # find number of occurances in given list
# sorting list
numbers = [3, 51, 2, 8, 6]
numbers.sort()
print(numbers)
# sort in reverse order
numbers.sort(reverse=True)
print(numbers)
print(sorted(numbers)) # duplicate and create the new list with sorted order
items = [
("Product1", 10),
("Product2", 9),
("Product3", 10)
]
items.sort()
print(items)
# sort function
def sort_items(item):
return item[1]
items.sort(key=sort_items)
print(items)
# lambda function
#lambda item:expression
items.sort(key=lambda item: item[1])
print(items)
# map functions
prices = []
for item in items:
prices.append(item[1])
print(prices)
prices = list(map(lambda item: item[1], items))
print(prices)
# filter function
prices = list(filter(lambda item: item[1] >= 10, items))
print(prices)
# list comprehensions
numbers = [item[1] for item in items]
print(numbers)
# filtered list comprehensions
numbers = [item for item in items if item[1] >= 10]
print(numbers)
# zip function
list1 = [1, 2, 3]
list2 = [10, 20, 30]
#[(1, 10), (2, 20), (3, 30)]
combined = zip(list1, list2)
print(list(zip(list1, list2)))
# stacks
# LIFO,FIFO
browsing_session = [1, 2, 3]
browsing_session.append(4)
browsing_session.pop()
if not browsing_session:
print("Empty")
# Queues
queue = deque([])
queue.append(1)
queue.append(2)
queue.append(3)
queue.popleft()
print(queue)
if not queue:
print("Empty")
# Tuple - read only list
point = 1, 2
print(type(point)) # <class 'tuple'>
# concat tuple
point = (1, 2)+(3, 4)
print(point) # (1, 2, 3, 4)
# repeat a tuple
point = (1, 2) * 3
print(point) # (1, 2, 1, 2, 1, 2)
# list a tuple
point = tuple([1, 2])
print(point) # (1, 2)
# access tuple with index
point = (1, 2, 3)
print(point[0:2]) # (1, 2)
# unpack touple
x, y, z = (1, 2, 3)
print(x, y) # 1, 2
# swapping variable
x = 9
y = 10
x, y = y, x
print(x, y)
|
fb43b7b8876039fc5bfbcb44d660b6ce770dab96 | predalis/piwetter | /fileManipulator.py | 1,855 | 3.578125 | 4 | #!/usr/bin/env python
# Filename: fileManipulation.py
# returns the content of the file
def getFileContent(filename):
myFile = open (filename, 'r')
current = myFile.readlines()
# print('file content:', current)
myFile.close()
return current
#adds at the beginning of a file
def addToFileBeginning(toAdd, filename):
current = getFileContent(filename)
current.insert(0, toAdd)
myFile = open(filename, 'w')
current = "".join(current) #copy the list content into a string object
myFile.write(current)
myFile.close()
def removeLastComma(listOfStrings):
str = listOfStrings[-1]
str = str.replace(',', '')
listOfStrings[-1] = str
return listOfStrings
def addToFileEnd(toAdd, filename):
current = getFileContent(filename)
current = removeLastComma(current)
print (current[-1])
current.insert(len(current), toAdd)
myFile = open(filename, 'w')
current = "".join(current) #copy the list content into a string object
myFile.write(current)
myFile.close()
def convertToJsonArray(filename):
addToFileBeginning('[', filename)
addToFileEnd(']', filename)
def copyIntoWebServer(varname, filename, newFilename):
newVarname = "var "+varname+"= "
current = getFileContent(filename)
current.insert(0, newVarname)
myFile = open('/var/www/files/'+newFilename, 'w')
current = "".join(current) #copy the list content into a string object
myFile.write(current)
myFile.close()
def getFileInfos(filename):
myFile=open(filename, 'r+')
print ('filename:', myFile.name)
print ('this is my Filemode:', myFile.mode)
print ('current position:', myFile.tell())
if myFile.tell()>1:
print('going back to beginning')
myFile.seek(0,0)
myFile.write("hello Python")
print ('first in the file:', myFile.read(1), '\ncurrent position:', myFile.tell(), '\nfileno:', myFile.fileno())
myFile.close()
print ('is the file closed?: ',myFile.closed)
|
b93a3198d2a669eb993d6549518ad60d76a29847 | Ajordat/dice_rolling | /dice_rolling/models/die.py | 747 | 4.03125 | 4 | from random import Random
from typing import Any
class Die:
"""Class to represent a single die.
All dice have the same random source in order to set a seed globally among them to
later reproduce a throw.
"""
rand = Random()
def __init__(self, sides: int = 6):
"""Constructor of Die.
:param int sides: Number of sides of the die. Defaults to 6.
"""
self.sides = sides
def roll(self) -> int:
"""Method to roll the die.
:returns: The roll's result.
"""
return self.rand.randint(1, self.sides)
@classmethod
def set_seed(cls, seed: Any) -> None:
"""Method to set a global seed for every die.
"""
cls.rand = Random(seed)
|
416cb8bdd73e8ffa28de852ad3b8b3fdc0a73359 | rafaelperazzo/programacao-web | /moodledata/vpl_data/306/usersdata/284/69433/submittedfiles/poligono.py | 57 | 3.5 | 4 |
n=('digite o numero de lados: ')
nd=(n*(n-3))
print(nd)
|
dd581e56aaf775ac62af7702763baab1e108cda0 | ZenDevelopmentSystems/python-alexa-voice-service | /main.py | 1,559 | 3.671875 | 4 |
import helper
import authorization
import alexa_device
__author__ = "NJC"
__license__ = "MIT"
__version__ = "0.2"
def user_input_loop(alexa_device):
""" This thread initializes a voice recognition event based on user input. This function uses command line
input for interacting with the user. The user can start a recording, or quit if desired.
This is currently the "main" thread for the device.
"""
# While the stop event is not set
while True:
# Prompt user to press enter to start a recording, or q to quit
text = input("Press enter anytime to start recording (or 'q' to quit).")
# If 'q' is pressed
if text == 'q':
# Set stop event and break out of loop
alexa_device.close()
break
# If enter was pressed (and q was not)
# Get raw audio from the microphone
alexa_device.user_initiate_audio()
if __name__ == "__main__":
# Load configuration file (contains the authorization for the user and device information)
config = helper.read_dict('config.dict')
# Check for authorization, if none, initialize and ask user to go to a website for authorization.
if 'refresh_token' not in config:
print("Please go to http://localhost:5000")
authorization.get_authorization()
config = helper.read_dict('config.dict')
# Create alexa device
alexa_device = alexa_device.AlexaDevice(config)
user_input_loop(alexa_device)
print("Done")
|
feef43ee3dc280d717f10f057e06554108455618 | tackme/exercism | /python/pythagorean-triplet/pythagorean_triplet.py | 758 | 3.578125 | 4 | from math import gcd
def triplets_with_sum(number):
primitive_pythagoras = []
m = 1
while m ** 2 <= number:
for n in range(1, m):
if 2 * m * (m + n) > number:
break
if (m - n) % 2 != 0 and gcd(m, n) == 1:
a = m ** 2 - n ** 2
b = 2 * m * n
c = m ** 2 + n ** 2
if a < b:
primitive_pythagoras.append([a, b, c])
else:
primitive_pythagoras.append([b, a, c])
m += 1
triplet = []
for a, b, c in primitive_pythagoras:
if number % (a + b + c) == 0:
q = number // (a + b + c)
triplet.append([q * a, q * b, q * c])
return triplet
|
33136614c8dddc6ba2e4feb0a7cb1659c4e8393b | sraywall/GitTutorial | /automateboring/capitalsquizzes/randomQuizGenerator.py | 3,337 | 3.5625 | 4 | #!/usr/bin/python3
#randomQuizGenerator.py - Creates quizzes with questions and answers in
#random order, along with the answer key.
import random
#The quiz data. Keys are states and values are their capitals.
capitals = {
"Alabama":"Montgomery",
"Alaska":"Juneau",
"Arizona":"Phoenix",
"Arkansas":"Little Rock",
"California":"Sacramento",
"Colorado":"Denver",
"Connecticut":"Hartford",
"Delaware":"Dover",
"Florida":"Tallahassee",
"Georgia":"Atlanta",
"Hawaii":"Honolulu",
"Idaho":"Boise",
"Illinois":"Springfield",
"Indiana":"Indianapolis",
"Iowa":"Des Moines",
"Kansas":"Topeka",
"Kentucky":"Frankfort",
"Louisiana":"Baton Rouge",
"Maine": "Augusta",
"Maryland":"Annapolis",
"Massachusetts": "Boston",
"Michigan":"Lansing",
"Minnesota":"Saint Paul",
"Mississippi":"Jackson",
"Missouri":"Jefferson City",
"Montana":"Helena",
"Nebraska":"Lincoln",
"Nevada":"Carson City",
"New Hampshire":"Concord",
"New Jersey":"Trenton",
"New Mexico":"Santa Fe",
"New York":"Albany",
"North Carolina":"Raleigh",
"North Dakota":"Bismark",
"Ohio":"Columbus",
"Oklahoma":"Oklahoma City",
"Oregon":"Salem",
"Pennsylvania":"Harrisbrg",
"Rhode Island":"Providence",
"South Carolina":"Columbia",
"South Dakota":"Pierre",
"Tennesse":"Nashville",
"Texas":"Austin",
"Utah":"Salt Lake City",
"Vermont":"Montpelier",
"Virginia":"Richmond",
"Washington":"Olympia",
"West Virginia":"Charleston",
"Wisconson":"Madison",
"Wyoming":"Cheyenne"
}
#Generate 35 quiz files.
for quizNum in range(35):
# Create the quiz and answer key files.
quizFile = open("capitalsquiz{}.txt".format(quizNum + 1), 'w')
answerKeyFile = open("capitalsquiz_answers{}.txt".format(quizNum + 1), 'w')
# Write out the header for the quiz.
quizFile.write("Name:\n\nDate:\n\nPeriod:\n\n")
quizFile.write((" " * 20) + "State Capitals Quiz (Form {})".format(quizNum + 1))
quizFile.write("\n\n")
#Shuffle the order of the states.
states = list(capitals.keys())
random.shuffle(states)
# Loop through all 50 states, making a question for each.
for questionNum in range(50):
# Get right and wrong answers.
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
# Write the question and answer options to the quiz file.
quizFile.write("{}. What is the capital of {}?\n".format(questionNum + 1, states[questionNum]))
for i in range(4):
quizFile.write(" {}. {}\n".format("ABCD"[i], answerOptions[i]))
quizFile.write("\n")
# Write the answer key to a file.
answerKeyFile.write("{}. {}\n".format(questionNum + 1, "ABCD"[
answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
|
fcae2ca8a6365874a2655be3bc4a888e686c4fe7 | kolesov93/shad-2015-seminars | /homeworks/05_metrics/practice/chingis_task/tests/gen.py | 698 | 3.640625 | 4 | #!/usr/bin/env python
import random
import sys
import os
from math import sqrt
def rnd1(n):
return random.randint(0, n - 1)
def clamp(x, n):
if x < 0:
return 0
if x >= n:
return n - 1
return int(x)
def rnd2(n):
return clamp(abs(random.normalvariate(float(n) / 2, float(n)**(1./3))), n)
lima = 50000
limb = 100000
n = random.randint(lima, limb)
limc = 1000000 - n
first = [[i] for i in xrange(n)]
random.shuffle(first)
c = random.randint(0, limc)
for _ in xrange(c):
girl = rnd1(n)
boy = rnd2(n)
if girl not in first[boy]:
first[boy].append(girl)
print n
for girls in first:
print len(girls), ' '.join(str(x + 1) for x in girls)
|
4940922ad8f1c667b7aaf4a9a796cf76d748b8bd | ravite9/Weather-GUI-using-Python | /GUI_Weather_NOAA_USA.py | 8,038 | 3.578125 | 4 |
#======================
# imports
#======================
import tkinter as tk
from tkinter import Menu
from tkinter import ttk
#======================
# functions
#======================
# Exit GUI cleanly
def _quit():
win.quit() # win will exist when this function is called
win.destroy()
exit()
#======================
# procedural code
#======================
# Create instance
win = tk.Tk()
# Add a title
win.title("Python Projects")
# ---------------------------------------------------------------
# Creating a Menu Bar
menuBar = Menu()
win.config(menu=menuBar)
# Add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=_quit) # command callback
menuBar.add_cascade(label="File", menu=fileMenu)
# Add another Menu to the Menu Bar and an item
helpMenu = Menu(menuBar, tearoff=0)
helpMenu.add_command(label="About")
menuBar.add_cascade(label="Help", menu=helpMenu)
# ---------------------------------------------------------------
# Tab Control / Notebook introduced here ------------------------
tabControl = ttk.Notebook(win) # Create Tab Control
tab1 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab1, text='Tab 1') # Add the tab
tab2 = ttk.Frame(tabControl) # Add a second tab
tabControl.add(tab2, text='Tab 2') # Make second tab visible
tabControl.pack(expand=1, fill="both") # Pack to make visible
# ---------------------------------------------------------------
# We are creating a container frame to hold all other widgets
weather_conditions_frame = ttk.LabelFrame(tab1, text=' Current Weather Conditions ')
# using the tkinter grid layout manager
weather_conditions_frame.grid(column=0, row=0, padx=8, pady=4)
# ---------------------------------------------------------------
# but frame won't be visible until we add widgets to it...
# Adding a Label
## START REFACTORING ---
## COMMENTED OUT AS WE MOVED LABEL TO DIFFERENT PARENT FRAME
# ttk.Label(weather_conditions_frame, text="Location:").grid(column=0, row=0, sticky='W')
# # ---------------------------------------------------------------
# city = tk.StringVar()
# citySelected = ttk.Combobox(weather_conditions_frame, width=12, textvariable=city)
# citySelected['values'] = ('Los Angeles', 'London', 'Rio de Janeiro, Brazil')
# citySelected.grid(column=1, row=0)
# citySelected.current(0) # highlight first city
# # ---------------------------------------------------------------
# # increase combobox width to longest city
# max_width = max([len(x)for x in citySelected['values']])
# new_width = max_width
# # new_width = max_width - 4 # adjust per taste of extra spacing
# citySelected.config(width=new_width)
# ---------------------------------------------------------------
#==========================
# ENTRY_WIDTH = max_width + 3 # adjust per taste of alignment
ENTRY_WIDTH = 22
#==========================
## END REFACTORING ---
# Adding Label & Textbox Entry widgets
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Last Updated:").grid(column=0, row=1, sticky='E') # <== right-align
updated = tk.StringVar()
updatedEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=updated, state='readonly')
updatedEntry.grid(column=1, row=1, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Weather").grid(column=0, row=2, sticky='E') # <== increment row for each
weather = tk.StringVar()
weatherEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=weather, state='readonly')
weatherEntry.grid(column=1, row=2, sticky='W') # <== increment row for each
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Temperature:").grid(column=0, row=3, sticky='E')
temp = tk.StringVar()
tempEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=temp, state='readonly')
tempEntry.grid(column=1, row=3, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Dewpoint:").grid(column=0, row=4, sticky='E')
dew = tk.StringVar()
dewEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=dew, state='readonly')
dewEntry.grid(column=1, row=4, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Relative Humidity:").grid(column=0, row=5, sticky='E')
rel_humi = tk.StringVar()
rel_humiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=rel_humi, state='readonly')
rel_humiEntry.grid(column=1, row=5, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Wind:").grid(column=0, row=6, sticky='E')
wind = tk.StringVar()
windEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=wind, state='readonly')
windEntry.grid(column=1, row=6, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Visibility:").grid(column=0, row=7, sticky='E')
visi = tk.StringVar()
visiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=visi, state='readonly')
visiEntry.grid(column=1, row=7, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="MSL Pressure:").grid(column=0, row=8, sticky='E')
msl = tk.StringVar()
mslEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=msl, state='readonly')
mslEntry.grid(column=1, row=8, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Altimeter:").grid(column=0, row=9, sticky='E')
alti = tk.StringVar()
altiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=alti, state='readonly')
altiEntry.grid(column=1, row=9, sticky='E')
#---------------------------------------------
# ****************************************************************
# NOTE: WE REFACTORED THE LABELFRAME VARIABLE TO USE A BETTER NAME
# ****************************************************************
# Add some space around each label
for child in weather_conditions_frame.winfo_children():
child.grid_configure(padx=4, pady=2)
#########################################################################################
# NOAA (National Oceanic and Atmospheric Administration) section starts here
# we have to reposition the weather_conditions_frame to the next row below
weather_conditions_frame.grid_configure(column=0, row=1, padx=8, pady=4)
# create new labelframe
weather_cities_frame = ttk.LabelFrame(tab1, text=' Latest Observation for ')
weather_cities_frame.grid(column=0, row=0, padx=8, pady=4)
# ---------------------------------------------------------------
# place label and combobox into new frame
ttk.Label(weather_cities_frame, text="Location: ").grid(column=0, row=0) # empty space for alignment
# ---------------------------------------------------------------
city = tk.StringVar()
# citySelected = ttk.Combobox(weather_conditions_frame, width=12, textvariable=city) # before
citySelected = ttk.Combobox(weather_cities_frame, width=24, textvariable=city) # assign different parent frame
citySelected['values'] = ('Los Angeles', 'London', 'Rio de Janeiro, Brazil')
citySelected.grid(column=1, row=0)
citySelected.current(0) # highlight first city
# ---------------------------------------------------------------
for child in weather_cities_frame.winfo_children():
child.grid_configure(padx=6, pady=6)
#======================
# Start GUI
#======================
win.mainloop()
|
f0ad7f60c7700cd9861ed6586adc4370a0c2d860 | sofiane-lablack/Stage_M2_GitHub_test | /Wmass_direct_measurement_240GeV/analysis_tools/correlation_coefficients.py | 1,375 | 3.5625 | 4 | '''The aim of this file is to get a correlation coefficients form a TH2 histograms'''
from ROOT import TFile, gDirectory
def correlation_coefficient(input, output, ecm):
'''Function to get the correlation coefficients from a TH2'''
file_ = TFile(input,"r")
file_.cd()
for obj in file_.GetListOfKeys():
if "h_corr_" in obj.GetName():
histo = gDirectory.Get(obj.GetName())
output.write("{} \t {}\n".format(obj.GetName(), histo.GetCorrelationFactor()))
def main():
'''Main function to select the study. The user can change the parameters to put the correct
input file or gives directly the name of his file. The coefficents are written in an output txt
file.'''
# parameters to choose the study
ecm = 365 #GeV
m_w = 80.385 #GeV
nevt = 50 #K
channel = 'semi-leptonic'
###### Input
if channel == 'hadronic':
decay = 'qqqq'
else:
decay = 'qqll'
infile = "../output/plots/uncertainties_study/{}/corre_matrix_{}_{}K_M{}.root".format(channel, ecm, nevt, str(m_w)[:2])
###### Output
outdir = "../output/data/{}".format(channel)
outfile = open('{}/correlation_coefficients_{}_{}K_M{}.txt'.format(outdir, ecm, nevt, str(m_w)[:2]), 'w')
# Run function
correlation_coefficient(infile, outfile, ecm)
if __name__ == '__main__':
main()
|
02e2431aee9cded88f293b87108cb7a090698919 | felipetoro04/Logica-computacional | /Clase 4 ejercicio 3(Listas pares e impares).py | 301 | 3.515625 | 4 |
lista_pares = []
lista_impares = []
contador = 0
for i in range(1,11):
if (i % 2 == 0):
lista_pares.append(i)
contador = contador + 1
else:
lista_impares.append(i)
print("Numero pares: ",lista_pares)
print("Numero impares: ",lista_impares)
|
3368538b7b82caf0c3e409375f25328467eb1e16 | enrro/TC1014-Files-done-in-class | /7.-Proyectos py 3er/exercise3.py | 200 | 3.625 | 4 | '''
Created on 05/11/2014
exercise3
Proven and tested on python 3.3.3
@author: A01221672
'''
foo = [1,2,3,4,5]
bar = []
x = 0
for i in range(len(foo)):
x = foo[i] + x
bar.append(x)
print(bar) |
af98881c952f36f9d1408db5a17a6335df592aed | jassim-jasmin/ai | /data/preprocessing/text/vectorization/binary_term_frequency/visualize.py | 1,278 | 3.5 | 4 | from matplotlib import pyplot as plt
from pandas import DataFrame
from pandas.plotting import scatter_matrix
import numpy as np
from data.preprocessing.text.vectorization.binary_term_frequency.binary_term_frequency import BinaryTermFrequency
class Visualize:
@staticmethod
def apply(data: list):
vectorizer = BinaryTermFrequency.get()
vectorised_fit_data = vectorizer.fit_transform(data)
df = DataFrame(vectorised_fit_data.toarray(), columns=vectorizer.get_feature_names())
axarr = df.hist(bins=2)
for ax in axarr.flatten():
ax.set_xlabel("Feature presence")
ax.set_ylabel("Presence count")
plt.show()
return plt
if __name__ == "__main__":
corpus = ["This is a brown house. This house is big. The street number is 1.",
"This is a small house. This house has 1 bedroom. The street number is 12.",
"This dog is brown. This dog likes to play.",
"The dog is in the bedroom.",
"this is another string by house",
"My dog ran away",
"My house was empty",
"I'm jassim jasmin",
"My brother is jishal",
"india", "japan", "arabia", "kerala", "nothing"]
Visualize.apply(corpus)
|
3d3f2c76eabb32ba119866d204256c8e1d275df9 | rakeshksaraf/python-oop | /PetOop.py | 598 | 3.78125 | 4 |
class Pet:
def __init__(self,name,age):
self.name = name
self.age=age
def show(self):
print(f"I am {self.name},I am {self.age}")
def speak(self):
print("Shall I just say ")
class Cat(Pet):
def __init__(self,name,age,color):
super().__init__(name,age)
self.color=color
def speak(self):
print("Meow!")
class Dog(Pet):
def speak(self):
print("Bark!")
class Fish(Pet):
pass
p1= Pet("Tim",19)
p1.show()
c1=Cat("Bill",34)
c1.show()
c1.speak()
f1=Fish("Bub",2)
f1.speak() |
98cb2a49ce14fae8153b33479c249ce7f671856a | worker2396/hackerrank | /hackerrank/David's algorithm.py | 2,298 | 3.59375 | 4 | import collections as cl
import numpy as np
#
# Complete the 'organizingContainers' function below.
#
# The function is expected to return a STRING.
# The function accepts 2D_INTEGER_ARRAY container as parameter.
# 0 2 1
# 1 1 1
# 2 0 0
# if a list
def compare(s, t):
return cl.Counter(s) == cl.Counter(t)
def sum_row(container, it, size):
total = 0
for i in range(size):
total += container[it][i]
return total
def sum_col(container, it, index_start, size):
total = 0
for i in range(index_start, index_start + size):
total += container[i][it]
return total
def sum_check(container, index_start, size):
row_list = []
col_list = []
for i in range(index_start, index_start + size):
row_list.append(sum_row(container, i, size))
for j in range(size):
col_list.append(sum_col(container, j, index_start, size))
return compare(row_list, col_list)
def organizingContainers(container):
# Write your code here
queries = container[0][0]
count = 0
length = len(container)
size = container[1][0]
index_start = 2
head_index = 1
while count < queries:
if sum_check(container, index_start, size):
print('Possible')
else:
print('Impossible')
head_index += size + 1
count += 1
if head_index < length:
size = container[head_index][0]
index_start = head_index + 1
# sample inputs
two_d_array = [[2], # 0
[3], # 1
[1, 3, 1], # 2
[2, 1, 2], # 3
[3, 3, 3], # 4
[3], # 5
[0, 2, 1], # 6
[1, 1, 1], # 7
[2, 0, 0]] # 8
two_d_array_2 = [[2],
[3],
[1, 3, 1],
[2, 1, 2],
[3, 3, 3],
[4],
[2, 4, 1, 0],
[0, 2, 3, 0],
[0, 3, 2, 0],
[0, 0, 0, 2]]
big_2d_array = np.ones((1002, 1000), int)
big_2d_array[0] = [1]
big_2d_array[1] = [1000]
organizingContainers(two_d_array)
organizingContainers(two_d_array_2)
organizingContainers(big_2d_array)
|
99a0a7a3b08b4146fc2b073eb83b4dd27e9da199 | varshajoshi36/practice | /leetcode/python/easy/constructRectangle.py | 221 | 3.703125 | 4 | import math
def constructRectangle(area):
pivote = math.sqrt(area)
for i in range(int(pivote), 0, -1):
if area % i == 0:
return [area/i, i]
area = 9
print area
print constructRectangle(area)
|
07fc52f578adb9ee62c5424e4920ec5f7ff45a06 | MeetLuck/works | /thinkpython/chapter17/classmethod.py | 2,392 | 4.03125 | 4 | ''' chapter 17: Classes and methods '''
#------------ 17.1 Object-oriented features -------------
#------------ 17.2 Printing objects ---------------------
class Time(object):
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(time):
print '%.2d:%.2d:%.2d' %(time.hour, time.minute, time.second)
def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
def increment(self,seconds):
seconds += seconds
return int_to_time(seconds)
#--------- self is more recent than other -----------
def is_after(self, other):
return self.time_to_int() > other.time_to_int()
def __str__(self):
return '%.2d:%.2d:%.2d' %(self.hour, self.minute,self.second)
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def add_time(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
def __radd__(self,other):
return self.__add__(other)
def int_to_time(seconds):
minutes,second = divmod(seconds,60)
hour,minute = divmod(minutes,60)
return Time(hour, minute, second)
start = Time()
start.hour = 9
start.minute = 45
start.second = 00
Time.print_time(start)
start.print_time()
#------------ 17.3 Another example ---------------------
#------------ 17.4 A more complicated example ---------------------
#------------ 17.5 The init method ---------------------
#------------ 17.6 The __str__ method ---------------------
#------------ 17.7 Operator overloading ---------------------
start = Time(9,45)
duration = Time(1,35)
print start + duration
#------------ 17.8 Type-based dispatch ---------------------
print start + 1337
print 1337 + start
#------------ 17.9 Polymorphism ---------------------
# sum(iterable [,start] )
t1,t2,t3 = Time(7,43), Time(7,41), Time(7,37)
total = sum( [t1,t2,t3] )
print type(total), total
#------------ 17.10 Debugging ----------------------------------
def print_attributes(obj):
for attr in obj.__dict__:
print attr, getattr(obj,attr)
print_attributes(start)
#------------ 17.11 Interface and implementation ---------------
|
bcffcd1e99e9155e8b26ea90b5b686f89b78ed6b | NadiyaKh/Python | /codding text.py | 1,049 | 3.78125 | 4 | x=int(input("enter count:"))
def encode(s, x):
"""Encodes a string (s) using ROT (ROT_number) encoding."""
ROT_number %= x # To avoid IndexErrors
alpha = "abcdefghijklmnopqrstuvwxyz" * 2
alpha += alpha.upper()
def get_i():
for i in range(x):
yield i # indexes of the lowercase letters
for i in range(53, 78):
yield i # indexes of the uppercase letters
ROT = {alpha[i]: alpha[i + ROT_number] for i in get_i()}
return "".join(ROT.get(i, i) for i in s)
def decode(s, x):
"""Decodes a string (s) using ROT (ROT_number) encoding."""
return encrypt(s, abs(ROT_number % x - x))
#####################################
from string import ascii_lowercase
a = ascii_lowercase
x=4
b = a[-x:] + a[:-x]
d=dict(zip(a,b))
s="testeee"
encoded = ""
for letter in s:
if letter in d:
encoded+=d[letter]
else encoded+=letter
print (encoded)
####
for letter in s:
encoded+=d.get(letter, letter)
print (encoded)
|
e79aec0071a9ecdba6e773cd8f21a392693f70d2 | akushnirubc/pyneta | /Exercises/week_7_xml_nx-api/exercise1d.py | 627 | 3.515625 | 4 | # Using both direct indices and the getchildren() method,
# obtain the first child element and print its tag name.
from __future__ import unicode_literals, print_function
from lxml import etree
# Using a context manager read in the XML file
with open("show_security_zones.xml") as infile:
# parse string using etree.fromstring
show_security_zones = etree.fromstring(infile.read())
print("\n\n")
print("Print the child tag using list indices")
print("-" * 20)
print(show_security_zones[0].tag)
print()
print("Print the child tag using getchildren()")
print("-" * 20)
print(show_security_zones.getchildren()[0].tag) |
a83f8988dafbe9a45afcb3c7579e69cb0e150cf9 | hendrykosasih/CP2410-Practicals | /Week2/Question1.py | 222 | 3.90625 | 4 |
a = int(input("Higher number? >>> "))
b = int(input("Lower number? >>> "))
if a%b == 0:
print (("True! {1} is the factor of {0}.").format(a,b))
else:
print((("Oops! {1} is not the factor of {0}.").format(a,b)))
|
1669a07424139fad9c77831aa51d1f146a8c0e4d | JavierSLX/Hacking-Python | /Seccion_7/decoradores.py | 898 | 3.875 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
# classmethod
# staticmethod
# property
class Prueba(object):
def __init__(self, radio):
self.radio = radio
# Decorador que permite llamar el método sin que la clase sea instanciada (Igual a static en Java)
@classmethod
def saludo(cls, nombre):
print("Hola {}".format(nombre))
# Permite usar el metodo sin necesidad de argumentos (sin poner self)
@staticmethod
def saludo_static():
print("Bienvenido")
# Decorador que permite trabajar con metodos como si fueran variables
@property
def area_circulo(self):
return 3.141592 * (self.radio ** 2)
def main():
Prueba.saludo("Javier")
prueba = Prueba(5)
prueba.saludo_static()
# Se usa como si fuera una variable sin parentesis
area = prueba.area_circulo
print(area)
if __name__ == '__main__':
main() |
9ab25ddd4309b8338178affb804ea65c78ee45be | PbernsY/PythonPam | /code/crypto/prime_utils.py | 1,978 | 3.8125 | 4 | from random import randrange, getrandbits
def miller_rabin_test(prime_candidate, repetitions = 128):
# miller rabin works by combining fermat primality test AND Solovay-Strassen primality test
# below tests are to prevent errors)
if prime_candidate == 2 or prime_candidate == 3:
return True
if prime_candidate <= 1 or prime_candidate % 2 == 0:
return False
# pick miller-rabin #'s r and s so (primecand - 1) = r*(2 * s)
# and r is odd
# a is also used such that a in range [2, primecand - 1]
s = 0
r = (prime_candidate - 1)
while r & 1 == 0:
s += 1
r //= 2
# here we repeat so we know its accurate, as miller rabin is probablistic
for iter in range(repetitions):
# [2, primecand - 1]
fermat_witness = randrange(2, prime_candidate - 1)
# modular exponentiation
y = pow(fermat_witness, r, prime_candidate)
# above is the same as fermat_witness ** r mod prime_cand
if y != 1 and y != (prime_candidate - 1):
i = 1
while i < s and y != (prime_candidate - 1):
y = pow(y, 2, prime_candidate)
if y == 1:
return False
i += 1
if y != (prime_candidate - 1):
return False
return True
# we need to generate random big primes, we use a method called a mersenne twister (pseudo random number generator)
def generate_big_prime(bits = 128):
# we need to generate a 1024 bit random integer
# if we set the msb to 1 , it will hold on 1024 bits ie it will always be 1024 bits
# if we set the lsb to 1, itll be odd , the standard for RSA is generating a pseudo random odd integer of specified length (bits) and testing for primality
candidate = getrandbits(bits)
candidate |= (1 << bits - 1) | 1
return candidate
def obtain_both(bits = 128):
start = 4
# start at a NON prime number (so we know the miller rabin is working correctly)
while miller_rabin_test(start, 128) != True:
# while the chosen number (start) isnt prime, keep going until we hit a prime
start = generate_big_prime(bits)
return start
|
e5e207c20262e91123dbbd9e5a5a59173631d3b6 | frankobe/lintcode | /138_subarray-sum/subarray-sum.py | 903 | 3.671875 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: frankobe
@Problem: http://www.lintcode.com/problem/subarray-sum
@Language: Python
@Datetime: 16-02-16 19:55
'''
class Solution:
"""
@param nums: A list of integers
@return: A list of integers includes the index of the first number
and the index of the last number
"""
def subarraySum(self, nums):
# write your code here
if nums is None or len(nums) == 0:
return None
if len(nums) == 1 and nums[0] == 0:
return [0, 0]
dic = {}
sum = 0
for i in xrange(len(nums)):
sum = sum + nums[i]
if sum == 0:
return [0, i]
if sum in dic:
return [dic[sum]+1, i]
else:
dic[sum] = i
return None |
ac0dae58423bc2f80c306861f48792605a565917 | FeixLiu/graduation_project | /ptr_with_no_coverage/load_dict.py | 1,296 | 3.53125 | 4 | import sys
class load_dict():
"""
self._path (string): the path of the words set
self.vocab2index (dictionary): the vocab to index dictionary
self.index2vocab (dictionary): the index to vocab dictionary
self.embd (list): the embeddings of the words
"""
def __init__(self, path, embedding_size):
"""
function: initialize the class
:param path (string): the path of the words set
:param embedding_size (int): the embedding size
"""
self._path = path
self._embedding_size = embedding_size
self._load_dict()
def _load_dict(self):
"""
function: load the word index dictionary
"""
index = 0
self.vocab2index = {}
self.index2vocab = {}
self.embd = []
self.vocab2index['unk'] = 0
self.index2vocab[0] = 'unk'
self.embd.append([0. for _ in range(self._embedding_size)])
with open(self._path, 'r') as file:
for line in file:
row = line.strip().split(' ')
index += 1
self.vocab2index[row[0]] = index
self.index2vocab[index] = row[0]
self.embd.append(row[1:])
print('Loaded vocabulary from:', self._path, file=sys.stderr)
|
712a12721c4d451c167bfd89526d402cc7a9e204 | shellfly/algs4-py | /algs4/heap.py | 1,375 | 3.984375 | 4 | """
Sorts a sequence of strings from standard input using heap sort.
% more tiny.txt
S O R T E X A M P L E
% python heap.py < tiny.txt
A E E L M O P R S T X [ one string per line ]
% more words3.txt
bed bug dad yes zoo ... all bad yet
% python heap.py < words3.txt
all bad bed bug dad ... yes yet zoo [ one string per line ]
"""
class Heap:
@classmethod
def sink(cls, a, i, length):
while (2 * i + 1 <= length):
j = 2 * i + 1
if (j < length and a[j] < a[j + 1]):
j += 1
if a[i] > a[j]:
break
a[i], a[j] = a[j], a[i]
i = j
@classmethod
def sort(cls, arr):
N = len(arr)
k = N // 2
while k >= 0:
cls.sink(arr, k, N - 1)
k -= 1
while N > 0:
arr[0], arr[N - 1] = arr[N - 1], arr[0]
N -= 1
cls.sink(arr, 0, N - 1)
return arr
@classmethod
def is_sorted(cls, arr):
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
if __name__ == '__main__':
import sys
items = []
for line in sys.stdin:
items.extend(line.split())
print(' items: ', items)
print('sort items: ', Heap.sort(items))
assert Heap.is_sorted(items)
|
c037635a2a56e6db15545404a725a925b44130c8 | wbshobhit1/Python3.7 | /slice.py | 565 | 4.1875 | 4 | mystr = "aur Bhaiya Kaise Ho Sab Bhadihya"
"""""
print(mystr[:32])
print(len(mystr))
print(mystr[::2])
print(mystr[::])
print(mystr[:7:2])
print(mystr[4::2])
print(mystr[-8:-5])
print(mystr[::-1])
"""
# functions in strings
print(mystr.isalpha())
print(mystr.isalnum())
print(mystr.islower())
print(mystr.istitle())
print(mystr.endswith("bhadhiya"))
print(mystr.endswith("Bhadihya"))
print(mystr.count("a"))
farzi = mystr.capitalize()
print(farzi)
print(mystr.find("Sab"))
print(mystr.upper())
print(mystr.lower())
print(mystr.replace("Bhadihya" , "changa"))
print(mystr.format("Sab"))
|
28d874c54f1853e2e42b8e0c8615e639fdf1134a | bitty7/stock_market_prediction | /libs/get_data.py | 6,962 | 3.921875 | 4 | """ The get_data module is to scrape the information from the internet
Overview
----------
This module is responsible to supply the program with the data it needs which are
the companies prices in the stock market and their news.
Functions
----------
get_news: sequence of ints
The list of integers to sum up.
R
-------
See also
--------
"""
from bs4 import BeautifulSoup
import requests
import time
from datetime import datetime
import pandas as pd
from pandas_datareader import data as pd_dr
class Ticker:
"""
this class
[extended_summary]
"""
_URLs_news = {
"yahoo": "https://finance.yahoo.com/quote/{}?p={}",
"reuters": "https://www.reuters.com/companies/{}.{}",
}
_URLs_stock_prices = {
"yahoo": "https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval=1d&events=history&includeAdjustedClose=true",
}
def __init__(self, ticker) -> None:
"""
__init__ class constructor
[extended_summary]
:param ticker: the symbol of a company's name in the stock market
:type ticker: str
"""
self.ticker = ticker
response = requests.get(self._URLs_news["yahoo"].format(ticker, ticker))
soup = BeautifulSoup(response.content, "lxml")
# print(soup)
self.price = float(
soup.find("span", "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").text
)
self.name = soup.find("h1", "D(ib) Fz(18px)").text.split("(")[0].strip()
def _update_news_file(self, source="yahoo"):
"""
[summary]
[extended_summary]
:param source: [description], defaults to 'yahoo'
:type source: str, optional
:returns: list of all
:rtype: str
:raises ValueError: when source is not valid
:Example:
>>>
"""
results = []
if source == "yahoo":
# TODO: add news crawling from yahoo
pass
elif source == "reuters":
# NOTE: there are two options for the markets in the reuters website which are:
# OQ -> represent NASDAQ
# N -> represent the NYSE (New York Stock Exchange)
# this code will check both markets to find which market the ticker is in
markets = ["N", "OQ"]
for market in markets:
url = self._URLs_news["reuters"].format(self.ticker, market)
else:
raise ValueError("the source " + source + "is not recognized")
def _scrapping_reuters_news(self, market):
"""
a function that scrape the news from reuters
the news in reuters is in a list and once the user reach the end of the page,
the page will load more content if it has until all the news in its database is shown.
in order to get all the news, this function will try to mimic the behavior of the user
(using Selenium) and scroll until the there is no more news, then use parsing library
like: Beatifulsoup to get all the news
"""
pass
def _scraping_yahoo_news(self):
pass
def get_recent_news(self, source="yahoo"):
"""
a function to get the recent news of a company.
[extended_summary]
:param source: the source (website) to get the news from. defaults to 'yahoo'
:options:
- 'yahoo'
- 'reuters'
:type source: str, optional
:raises ValueError: if the source option is not recognized
:return: [description]
:rtype: list
:example:
.. highlight:: python
.. code-block:: python
Ticker('AAPL').get_recent_news(source='reuters')[0]
>>> {'description': 'Apple Inc said on Monday it has hired former distinguished '
'Google scientist Samy Bengio, who left the search giant amid '
'turmoil in its artificial intelligence research department.',
'link': 'https://www.reuters.com/article/us-apple-research/apple-hires-ex-google-ai-scientist-who-resigned-after-colleagues-firings-idUSKBN2CK1MN',
'title': "Apple hires ex-Google AI scientist who resigned after colleagues' "'firings'}
"""
url = ""
if source == "yahoo":
# TODO: write a code to get the recent news from yahoo
pass
elif source == "reuters":
for market in ["OQ", "N"]:
url = self._URLs_news["reuters"].format(self.ticker, market)
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
news_list = soup.find_all("div", {"class": "item"})
news_urls = []
for news in news_list:
news_urls.append(
{
"title": news.div.a.text,
"description": news.div.p.text,
"link": news.div.a["href"],
}
)
if len(news_urls) > 2:
return news_urls
return []
else:
raise ValueError("the source" + source + "is not recognized")
def __str__(self):
"""
a function that returns the name of the ticker's company
"""
def _historical_data(self, t1, t2, method="scraping"):
"""
[summary]
:param t1: the starting date in seconds
:type t1: int
:param t2: the ending date in seconds
:type t2: int
:param options: [description], defaults to 'show'
:type options: str, optional
"""
# tickers (list) -> a list of the tickers needed to be downloaded
# t1 (int) -> the starting date in seconds
# t2 (int) -> the ending date in seconds
if method == "scraping":
# convert the dates to seconds
t1 = time.mktime(t1.timetuple())
t2 = time.mktime(t2.timetuple())
# setup the url
url = self._URLs_stock_prices["yahoo"].format(self.ticker, int(t1), int(t2))
# read the data into a pandas.dataframe
pd.options.display.max_rows = None
pd.options.display.max_columns = None
df = pd.read_csv(url)
df.to_csv("example.txt", index=False)
return df
elif method == "pandas":
return pd_dr.DataReader(self.ticker, data_source="yahoo", start=t1, end=t2)
def get_price(self):
return self.price
if __name__ == "__main__":
# time_1 = datetime(2019, 1,1)
# time_2 = datetime(2020, 1,1)
# print(
# Ticker("AAPL")._historical_data(
# datetime(2019, 1, 1),
# datetime(2020, 1, 1),
# method="scraping",
# )
# )
a = Ticker("AAPL")
print(a.get_price())
|
0074a2240674cd42ace7efff3bc6dd99534819aa | faeze-mobasheri/CalculatorPro | /calculatorFunctions/TenToPowerX/10toPowerx.py | 1,398 | 3.5 | 4 | __author__ = "The CalculatorPro Inc."
__copyright__ = "Copyright 2018, CalculatorPro"
__credits__ = ["Team A"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Faezeh Mobasheri"
__email__ = "f_mobas@encs.concordia.ca"
__status__ = "Release v1.0"
import math
value = 1
ln10 = math.log(10)
#Define precision decimal
error=0.000000000001
error_decimals=10
#Calculation of power function
def power(base,exp):
if (exp==0):
return 1
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
#calculation of factorial function
def factorial(n):
if n == 1:
return n
if n==0:
return 1
else:
return n * factorial(n - 1)
#if the value of X is an integer use power function, if it is floating number taylor series formula
def tentopower(x):
val=x
if type(val)==int:
if val >= 0 :
print(power(10, val))
if val < 0 :
val *= -1
print(1/power(10, val))
elif type(val)==float:
value = 0.0000000000000000000001
for n in range(150):
calculate = ((power(ln10, n)) * (power(val + 22, n)) * 0.0000000000000000000001) / factorial(n)
if calculate > error:
value += calculate
else:
value += 0
round(calculate, error_decimals)
return print(value)
|
ecbc4e060f67c1dd372616dc55c814158696065c | BasimAhmedKhan/Distance-BTW-the-Points | /Python Program To Compute The Distance Between The Points.py | 503 | 4.4375 | 4 | print(" ")
print('"Python Program To Compute The Distance Between The Points (x1, y1) and (x2, y2)"')
print(" ")
val1 = float(input("Enter Point(x1): "))
print(" ")
val2 = float(input("Enter Point(y1): "))
print(" ")
val3 = float(input("Enter Point(x2): "))
print(" ")
val4 = float(input("Enter Point(y2): "))
print(" ")
print('"By Using Distance Formula!"')
print(" ")
ans = (((val3 - val1)**2 + (val4 - val2)**2)**0.5)
print("Distance = " + str(ans) + " units")
print(" ") |
2a8a38900678d524095d10d1e01c6502645cb362 | nirajchaughule/Python_prac | /nestedif.py | 266 | 3.8125 | 4 | a=int(input("Enter your marks"))
if a>35:
if a<=50 and a>=35:
print("C")
elif a>=51 and a<=60:
print("B")
elif a>=61 and a<=74:
print("A")
elif a>=75 and a<=100:
print("Distinction")
elif a>101:
print("Out of limit")
else:
print("bye")
|
d8cff0b6153c5bd68989914b1749b7bab4d59301 | JoaoLiraDev/Lean_Python | /projeto_jogo_da_velha.py | 3,552 | 3.65625 | 4 | import random
import os
class ticTacToe:
def __init__(self):
self.reset()
def print_board(self):
print("")
print(" " + self.board[0][0] + " | " + self.board[0][1] + " | " + self.board[0][2])
print("------------")
print(" " + self.board[1][0] + " | " + self.board[1][1] + " | " + self.board[1][2])
print("------------")
print(" " + self.board[2][0] + " | " + self.board[2][1] + " | " + self.board[2][2])
def reset(self):
self.board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
self.done = ""
def check_win_or_draw(self):
dict_win = {}
for i in ["X", "O"]:
# Horizontais
dict_win[i] = (self.board[0][0] == self.board[0][1] == self.board[0][2] == i)
dict_win[i] = (self.board[1][0] == self.board[1][1] == self.board[1][2] == i) or dict_win[i]
dict_win[i] = (self.board[2][0] == self.board[2][1] == self.board[2][2] == i) or dict_win[i]
# Verticais
dict_win[i] = (self.board[0][0] == self.board[1][0] == self.board[2][0] == i) or dict_win[i]
dict_win[i] = (self.board[0][1] == self.board[1][1] == self.board[2][1] == i) or dict_win[i]
dict_win[i] = (self.board[0][2] == self.board[1][2] == self.board[2][2] == i) or dict_win[i]
# Diagonais
dict_win[i] = (self.board[0][0] == self.board[1][1] == self.board[2][2] == i) or dict_win[i]
dict_win[i] = (self.board[2][0] == self.board[1][1] == self.board[0][2] == i) or dict_win[i]
if dict_win["X"]:
self.done = "x"
print("X venceu")
return
elif dict_win["O"]:
self.done = "o"
print("O venceu")
return
c = 0
for i in range(3):
for j in range(3):
if self.board[i][j] != " ":
c += 1
break
if c == 0:
self.done = "d"
print("Empate!")
return
def get_player_move(self):
invalid_move = True
while invalid_move:
try:
print("Digite a linha do seu proximo lance:")
x = int(input())
print("Digite a coluna do seu proximo lance:")
y = int(input())
if x > 2 or x < 0 or y > 2 or y < 0:
print("Coordenadas inválidas")
if self.board[x][y] != " ":
print("Posição já preenchida.")
continue
except Exception as e:
print(e)
continue
invalid_move = False
self.board[x][y] = "X"
def make_move(self):
list_moves = []
for i in range(3):
for j in range(3):
if self.board[i][j] == " ":
list_moves.append((i, j))
if len(list_moves) > 0:
x, y = random.choice(list_moves)
self.board[x][y] = "O"
game = ticTacToe()
game.print_board()
next = 0
while next == 0:
os.system("cls")
game.print_board()
while game.done == "":
game.get_player_move()
game.make_move()
os.system("cls")
game.print_board()
game.check_win_or_draw()
print("Digite 1 para sair do jogo ou qualquer tecla para jogar novamente.")
next = int(input())
if next == 1:
break
else:
game.reset()
next = 0 |
1f83f89a4cf54e1f98ae7ab8087c5c93eaa73f84 | mygit-kapil/Python_Projects | /Linear Regression Predictor/Linear Regression Predictor.py | 2,337 | 4.09375 | 4 | import tkinter as tk
from tkinter import filedialog
import numpy as np
import pandas as pd
from math import sqrt
from matplotlib import pyplot as plt
if __name__== "__main__":main()
def main():
file = choosefile()
df = pd.read_csv(file)
print(list(df.columns.values))
col1 = input("Enter the x column name :")
col2 = input("Enter the y column name :")
x_train = df[col1].tolist()
y_train = df[col2].tolist()
mean_x, mean_y = mean(x_train), mean(y_train)
var_x, var_y = variance(x_train, mean_x), variance(y_train, mean_y)
covar = covariance(x_train, mean_x, y_train, mean_y)
b0,b1 = coefficients(x_train, y_train)
print("The linear equation for the provided dataset is : y = ",b0,"+",b1,"x")
file = choosefile()
df = pd.read_csv(file)
list(df.columns.values)
x_test = df[col1].tolist()
y_act = df[col2].tolist()
y_pred = predict(b0,b1,x_test)
rootmse = rmse(y_act, y_pred)
print ('The cost function value is %.3f' %(rootmse))
plt.scatter(x_test, y_act)
plt.scatter(x_test, y_pred, color='red')
plt.plot(x_test, y_pred, color='red')
plt.title('Linear Regression Graph')
plt.xlabel(col1)
plt.ylabel(col2)
plt.show()
def mean(values):
return sum(values)/float(len(values))
def variance(values, mean):
return sum([(x-mean)**2 for x in values])/float(len(values))
def covariance(x, mean_x, y, mean_y):
covar = 0.0
for i in range(len(x)):
covar += (x[i] - mean_x)*(y[i] - mean_y)
return covar/float(len(x))
def coefficients(x,y):
x_mean, y_mean = mean(x), mean(y)
b1 = covariance(x, x_mean, y, y_mean)/variance(x, x_mean)
b0 = y_mean - b1*x_mean
return [b0,b1]
def predict(b0,b1,data):
pred = list()
for x in data:
y = b0+b1*x
pred.append(y)
return pred
def choosefile() :
root = tk.Tk()
root.withdraw()
filename = filedialog.askopenfilename(filetypes=[("csv file","*.csv")],title='Choose a csv file')
if filename != None:
return filename
else:
return null
def rmse(act, pred):
sum_error = 0.0
for i in range(len(act)):
pred_error = pred[i] - act[i]
sum_error += (pred_error**2)
mean_error = sum_error/float(len(act))
return sqrt(mean_error)
|
1ba7b2ae66eb2f4b7a039ae415c1f0bd3bd68db7 | Cyberfallen/Latihan-Bahasa-Pemrograman | /python/a.py | 169 | 3.765625 | 4 | secret = "ngeh"
guess = ""
while guess != secret:
guess = (input("Masukkan Kata : "))
print("Wrong")
if guess == 3:
exit()
print("Sukses") |
6c933cbcfe6e2d9906565bf68e69e89c1cb4c5dd | k8thedinosaur/labs | /weather.py | 2,410 | 4.25 | 4 | # # Lab: PyWeather
#
# Create a program that will prompt a user for city name or zip code.
# Use that information to get the current weather. Display that information
# to the user in a clean way.
# ## Advanced
#
# * Also ask the user if they would like to see the results in C or F.
import requests
package = {
"APPID": "848e9a71a4b1c90877841baf319c1b68",
}
# K to F conversion
def k_to_f(temp):
ans = temp * 9/5 - 459.67
ans = int(ans)
return ans
def k_to_c(temp):
ans = temp - 273.15
ans = int(ans)
return ans
def get_weather():
# ask city or zip
city_zip = input("Would you like to search by (city) or (zip)? ")
# conditional loop for either instance
# if city ...
if city_zip == "city":
city_name = input("Enter your city: ")
package["q"] = city_name
# pull from api and write params to local dictionary package
r = requests.post("http://api.openweathermap.org/data/2.5/weather", params=package)
# convert from js object to python dict or maybe the other way around idk
data = r.json()
# pull temp data from package
temp = (data["main"]["temp"])
area = (data["name"])
# give option to display in different units
units = input("Would you like it displayed in (K), (C), or (F)? ")
if units == "F":
# apply k to f and display
print("It is {} degrees F in {}.".format(k_to_f(temp), area))
# apply k to c
elif units == "C":
print("It is {} degrees C in {}.".format(k_to_c(temp), area))
# default is k
else:
print("It is {} degrees K in {}.".format(int(temp), area))
# if zip ...
elif city_zip == "zip":
zipcode = input("Enter your zipcode: ")
package["zip"] = zipcode
r = requests.post("http://api.openweathermap.org/data/2.5/weather", params=package)
data = r.json()
temp = (data["main"]["temp"])
units = input("Would you like it displayed in (K), (C), or (F)? ")
if units == "F":
print("It is {} degrees F in {}.".format(k_to_f(temp), zipcode))
elif units == "C":
print("It is {} degrees C in {}.".format(k_to_c(temp), zipcode))
else:
print("It is {} degrees K in {}.".format(int(temp), zipcode))
else:
print("Invalid response.")
get_weather()
|
56ebd3224341f356632b1d3fb0b22811180a33ce | pear9123/Python-study | /06A-polygon.py | 146 | 3.671875 | 4 | import turtle as t
n=5
t.color("purple")
t.speed(1)
t.begin_fill()
for x in range(n):
t.forward(50)
t.left(360/n)
t.end_fill()
|
669ca635c9bf4bae8098a58dbbc6446a9e504b7d | vivid-ZLL/tedu | /part_01_python_base/python_core/day4/exercise06.py | 423 | 3.953125 | 4 | import random
count = 0
for times in range(3):
random_number1 = random.randint(1, 10)
random_number2 = random.randint(1, 10)
code_answer = random_number1 + random_number2
input_answer = int(input("请输入" + str(random_number1) + "+" +
str(random_number2) + "=?"))
if code_answer == input_answer:
count += 1
code_score = 10 * count
print("总分是", code_score)
|
ba28e32be40a5262d5e8e1543d45a8b914b6c86b | jhoover4/algorithms | /optimal_util.py | 1,502 | 3.546875 | 4 | # Amazon | OA 2019 | Optimal Utilization
# Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the
# second integer represents a value. Your task is to find an element from a and an element form b such that the sum of
# their values is less or equal to target and as close to target as possible. Return a list of ids of selected elements.
# If no pair is possible, return an empty list.
def optimal_util(first_lis, second_lis, target):
"""
Sorts lists then uses two pointers to find most optimal sets.
Time complexity: Sorts take O(n log n) time and pointers take O(n). Final results is O(n log n).
:param List first_lis:
:param List second_lis:
:param int target:
:return:
"""
if not first_lis or not second_lis:
return []
first_lis = sorted(first_lis, key=lambda x: x[1])
second_lis = sorted(second_lis, key=lambda x: x[1])
closest_diff = target
result = list()
i = 0
j = len(second_lis) - 1
while i < len(first_lis) and j >= 0:
el_sum = first_lis[i][1] + second_lis[j][1]
if target < el_sum:
j -= 1
else:
diff = target - el_sum
if diff == closest_diff:
result.append([first_lis[i][0], second_lis[j][0]])
elif diff <= closest_diff:
result = [[first_lis[i][0], second_lis[j][0]]]
closest_diff = diff
i += 1
return result
|
92c46e55fff7f18f1e7cee23b7041cdf2edb35f9 | makrandp/python-practice | /LeetCode/Solved/Medium/CountNumberOfTeams.py | 3,935 | 4.0625 | 4 | '''
1395. Count Number of Teams
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
Example 1:
Input: rating = [2,5,3,4,1]
Output: 3
Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
Example 2:
Input: rating = [2,1,3]
Output: 0
Explanation: We can't form any team given the conditions.
Example 3:
Input: rating = [1,2,3,4]
Output: 4
Constraints:
n == rating.length
1 <= n <= 200
1 <= rating[i] <= 10^5
'''
from typing import List
from collections import defaultdict
import collections
class Solution:
# Nice and fast brute force solution
# Do not use this as its O(n^3)
def bruteForceNumTeams(self, rating: List[int]) -> int:
out = 0
for i in range(0, len(rating)):
for j in range(i + 1, len(rating)):
for k in range(j + 1, len(rating)):
if rating[i] < rating[j] < rating[k]:
out += 1
elif rating[i] > rating[j] > rating[k]:
out += 1
return out
# Slightly faster solution
# Uses dynamic programming to precompute how many pairs each value has
def numTeamsDP(self, rating: List[int]) -> int:
up = collections.defaultdict(list)
down = collections.defaultdict(list)
index = {val : idx + 1 for idx, val in enumerate(rating)}
# O(n^2) for collection pairs in ascending or descending order
for i in range(1, len(rating)):
r = rating[i]
for c in range(i + 1, len(rating)):
n = rating[c]
if n > r:
up[r].append((r,n))
elif n < r:
down[r].append((r,n))
upKeys = sorted(up.keys())
downKeys = sorted(down.keys())
o = 0
for i, r in enumerate(rating):
for u in upKeys:
if u <= r:
continue
else:
if index[u] > i:
print(r,up[u])
o += len(up[u])
for u in downKeys:
if u >= r:
break
else:
if index[u] > i:
print(r,down[u])
o += len(down[u])
return o
# O(NLogN) Solution
def numTeams(self, rating: List[int]) -> int:
if not rating or len(rating) < 3:
return 0
cnt = 0
dic = {}
for i, num in enumerate(sorted(rating)):
dic[num] = i
cur = rating[:1]
for i in range(1, len(rating)):
total_small = dic[rating[i]]
total_big = len(rating) - 1 - total_small
cur_small = self.findIdx(cur, rating[i])
cur_big = len(cur) - cur_small
cur = cur[:cur_small] + [rating[i]] + cur[cur_small:]
cnt += (cur_small * (total_big - cur_big)) + (cur_big * (total_small - cur_small))
return cnt
def findIdx(self, nums, target):
# nums is sorted
if target > nums[-1]:
return len(nums)
if target < nums[0]:
return 0
k = 1
while 2 * k < len(nums) and nums[2*k] < target:
k *=2
for i in range(k, min(2*k+1, len(nums))):
if nums[i] > target:
return i
s = Solution()
s.bruteForceNumTeams([2,5,3,4,1]) |
1be856a2389ddceaaccd2383fdb5d7f309ce7352 | martincorona007/Graphics | /Project/p2.py | 2,438 | 3.984375 | 4 | from matplotlib import pyplot as plt
import math
#==============MATRIX A==============
#Create matrix A and initialate the matrix with 0 and 1, n1 & n is the rows
n1 = n = 3
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
if i < j:
a[i][j] = 0
elif i > j:
a[i][j] = 0
else:
a[i][j] = 1
"""
for row in a:
print(' '.join([str(elem) for elem in row]))
"""
print("Rotation")
#==============MATRIX B==============
#Create the matrix B and initialate the matrix with 1
n2 = r = 3#rows
m2 = c = 1#columns
b = [[0] * c for i in range(r)]
for i in range(r):
for j in range(c):
b[i][j] = 1
"""
for row in b:
print(row);
"""
#==============ASK DATA==============
#Px=6
#Py=1
print("Enter Point ")
Px=float(input("Enter Px number: "))
Py=float(input("Enter Py number: "))
b[0][0]=Px
b[1][0]=Py
#ro=45
ro=int(input("Enter Rotation: "))
a[0][0]=round(math.cos(math.radians(ro)),2)
a[0][1]=round(math.sin(math.radians(-ro)),2)
a[1][0]=round(math.sin(math.radians(ro)),2)
a[1][1]=round(math.cos(math.radians(ro)),2)
##NOTE
#When I use the function round, it only takes the two decimal numbers and add 1
#==============PRINT==============
print("Matrix A")
for row in a:
print(' '.join([str(elem) for elem in row]))
print("Matrix B")
for row in b:
print(row);
#==============MATRIX RESULT==============
#create the matrix result
c1=m2
r1=n1
result_array=[ [0] * c1 for i in range(r1)]
#==============OPERATION multiplication==============
for i in range(n1):
for j in range(m2):
for x in range(n1):
result_array[i][j]=a[i][x]*b[x][j]+result_array[i][j]
print("Result")
for row in result_array:
print(row);
#==============Graph==============
#mark points and lines
xx1=[0,Px]
yy1=[0,Py]
xx2=[0,result_array[0][0]]
yy2=[0,result_array[1][0]]
yy=[0,result_array[1][0]]
plt.plot(Px,Py, marker="o", color="red")#mark the point
plt.plot(xx1,yy1, marker="+", color="red")#mark the line
plt.plot(result_array[0][0],result_array[1][0], marker="D", color="blue")#mark the point
plt.plot(xx2,yy2, marker="+", color="blue")#mark the line
plt.title("Rotation")
plt.yticks([i for i in range(-10,11)]) #set size to the cartesian plan
plt.xticks([i for i in range(-10,11)]) #set size to the cartesian plan
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.xlabel("X")
plt.ylabel("Y")
plt.show() |
72988d8531acf94a96a8cd8ef14959a48927632a | huiqinwang/KesaiRecommend | /kesaiRecommend/srcs/preprocessor/NewsDict.py | 940 | 3.5625 | 4 | # -*- coding:UTF-8 -*-
import csv
# 创建咨询字典{item_name:item_id}
class NewsDict:
def news_dict(self):
news_file = '../../../data/origin/news_info.csv'
# news_info csv文件最好用csv包处理
news_files = file(news_file)
news_reader = csv.reader(news_files)
news_data = []
for item in news_reader:
news_data.append(item[0])
news_data.pop(0) # title
print 'new_data',len(news_data)
print 'sample ',news_data[0:10]
news_files.close()
# 将ID做成字典
news_dict = {}
for i in range(1,len(news_data)+1):
news_dict.setdefault(news_data[i-1],"")
news_dict[news_data[i-1]]= str(i)
return news_dict
if __name__ == "__main__":
news = NewsDict()
news_dict = news.news_dict()
print "news_dict",len(news_dict.keys())
print "news_dict_sample",news_dict["530202"]
|
758673c636bdad587f13674156f81e09e9ae8137 | miscdats/SnakeParty-RPG | /SnakePartyRPG/classes/Player.py | 2,386 | 3.671875 | 4 | # Whomever is playing assumes the role of player!
import arcade
from constants import *
class Player(arcade.Sprite):
# how far to move and how fast
x = [0]
y = [0]
step = 44
direction = 0
length = 3
hp = STARTING_HP
lives = STARTING_LIVES
sprite = arcade.Sprite("images/rogue_like/rogue_like.png", TEAM_SPRITE_SCALING)
updateCountMax = 2
updateCount = 0
def __init__(self):
# Call the parent Sprite constructor
super().__init__()
for i in range(0, 2000):
self.x.append(-100)
self.y.append(-100)
# initial positions, no collision.
self.x[1] = 1 * 44
self.x[2] = 2 * 44
# Info on where we are going.
# Angle comes in automatically from the parent class.
self.thrust = 0
self.speed = 0
self.max_speed = 4
self.drag = 0.05
self.respawning = 0
# Mark that we are respawning.
self.respawn()
def respawn(self):
"""
Called when we die and need to make a new player.
'respawning' is an invulnerability timer.
"""
# If we are in the middle of respawning, this is non-zero.
self.respawning = 1
self.center_x = SCREEN_WIDTH / 2
self.center_y = SCREEN_HEIGHT / 2
self.angle = 0
def update(self):
""" Changes direction of character dependent of key presses. """
self.updateCount = self.updateCount + 1
if self.updateCount > self.updateCountMax:
# update previous positions
for i in range(self.length - 1, 0, -1):
self.x[i] = self.x[i - 1]
self.y[i] = self.y[i - 1]
# update position of player : party lead
if self.direction == 0:
self.x[0] = self.x[0] + self.step
if self.direction == 1:
self.x[0] = self.x[0] - self.step
if self.direction == 2:
self.y[0] = self.y[0] - self.step
if self.direction == 3:
self.y[0] = self.y[0] + self.step
self.updateCount = 0
# update direction to move in
def moveRight(self):
self.direction = 0
def moveLeft(self):
self.direction = 1
def moveUp(self):
self.direction = 2
def moveDown(self):
self.direction = 3
|
4d37a83221acebe62da737215d4058ce3496ca42 | calvinraveenthran/leetcode-python | /leetcodequestions/ClimbingStairs.py | 443 | 3.875 | 4 | class ClimbingStairs:
def climbStairs(self, n: int) -> int:
init_array = [0,1,2,3,5]
if n < 5:
return init_array[n]
for i in range(5, n+1):
init_array.append(init_array[i-1] + init_array[i-2])
return init_array[n]
def test_climb_stairs():
ts = ClimbingStairs()
answer = ts.climbStairs(5)
assert answer == 8
if __name__ == "__main__":
test_climb_stairs() |
af3dc4766d577cccc556387c55a5b2a720de3400 | yhs3434/Algorithms | /programmers/Summer_Winter(~2018)/primeNumberMaking.py | 875 | 3.546875 | 4 | # 서머코딩 / 윈터코딩 (~2018) - 소수 만들기
# https://programmers.co.kr/learn/courses/30/lessons/12977
from itertools import combinations
def solution(nums):
answer = 0
primes = getPrimes()
combis = list(combinations(nums, 3))
for combi in combis:
num = sum(combi)
if isPrime(num, primes):
answer += 1
return answer
def isPrime(num, primes):
if num in primes:
return True
else:
return False
def getPrimes():
che = [i for i in range(3, 3001, 2)]
che = [2] + che
n = che.pop(0)
primes = [n]
while che:
lChe = len(che)
for i in range(lChe):
i = lChe - i - 1
if che[i] % n == 0:
del che[i]
n = che.pop(0)
primes.append(n)
return primes
print(solution([1,2,3,4]))
print(solution([1,2,7,6,4])) |
c0d9ce638acc7cc4aee09dce7360d5b5f916b52a | chinnuz99/luminarpython | /flow controlls/con 2.py | 143 | 4.3125 | 4 | #check given num is positive or negative
num=int(input("enter the num"))
if(num>0):
print("positive num")
else:
print("negative num")
|
ba9bbe6983b422c40a24840bbb98caf6a389ccf0 | Nicolas-Wursthorn/Exercicios-Python-Brasil | /EstruturaDeRepeticao/exercicio32.py | 724 | 4.0625 | 4 | # O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um conjunto indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas informadas, bem como a média das temperaturas.
temperaturas = []
while True:
graus = float(input("Digite a temperatura em graus (tecle 0 para parar): "))
temperaturas.append(graus)
media = sum(temperaturas) / len(temperaturas)
if graus == 0:
temperaturas.pop()
print("A maior temperatura registrada: {}°C".format(max(temperaturas)))
print("A menor temperatura registrada: {}°C".format(min(temperaturas)))
print("A temperatura média registrada: {}°C".format(media))
break |
1dd41abe3b5184a058e53fc4592648ceb20980bb | nickjtay/Patents2021 | /delete_brf_sum_text.py | 1,394 | 3.828125 | 4 | import csv
import os
import sqlite3
import sys
from operator import itemgetter
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def delete_table(conn, delete_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(delete_table_sql)
except Error as e:
print(e)
def main():
field_size_limit = sys.maxsize
while True:
try:
csv.field_size_limit(field_size_limit)
break
except OverflowError:
field_size_limit = int(field_size_limit / 10)
database = r"D:\Patents\DB\patents - Copy.db"
sql_delete_brf_sum_text_table = """ DROP TABLE brf_sum_text; """
conn = create_connection(database)
if conn is not None:
# create projects table
delete_table(conn, sql_delete_brf_sum_text_table)
else:
print("Error! cannot create the database connection.")
if __name__ == '__main__':
main()
|
4773db8b2ac4191975e9d06238e430de2acabab4 | MajoDiaz/Memorama | /Memorama.py | 2,766 | 3.609375 | 4 | from random import *
from turtle import *
from freegames import path
#A01701879 María José Díaz Sánchez
#A00829556 Santiago Gonzalez Irigoyen
#Este código es un juego de memorama
#30 de octubre de 2020
'''Aquí se genera el contador de taps inicializado
en 0'''
taps = 0
car = path('car.gif')
tiles = list(range(32)) * 2
state = {'mark': None}
hide = [True] * 64
def square(x, y):
"Draw white square with black outline at (x, y)."
up()
goto(x, y)
down()
color('black', 'white')
begin_fill()
for count in range(4):
forward(50)
left(90)
end_fill()
def index(x, y):
"Convert (x, y) coordinates to tiles index."
return int((x + 200) // 50 + ((y + 200) // 50) * 8)
def xy(count):
"Convert tiles count to (x, y) coordinates."
return (count % 8) * 50 - 200, (count // 8) * 50 - 200
def tap(x, y):
"Update mark and hidden tiles based on tap."
spot = index(x, y)
mark = state['mark']
if mark is None or mark == spot or tiles[mark] != tiles[spot]:
state['mark'] = spot
else:
hide[spot] = False
hide[mark] = False
state['mark'] = None
'''Se hace global la variable taps para evitar problemas y se
le suma 1 por cada taps'''
global taps
taps += 1
def draw():
"Draw image and tiles."
clear()
goto(0, 0)
shape(car)
stamp()
#contar número de cuadrados cubiertos, empezando con 64
d=64
for count in range(64):
if hide[count]:
x, y = xy(count)
square(x, y)
else:
#cada vez que se encuentre un cuadrado destapado (se checan todos)
#se resta uno de 'd'
d = d-1
mark = state['mark']
if mark is not None and hide[mark]:
'''Aquí se dibuja el número de cada uno de los cuadros'''
'''Para que los números aparezcan en el centro debemos de
jugar con la función goto, que es la que mueve el texto
En este caso se cambio la posicion de x+18.82', y+12 que logro
centrar mejor el número de los cuadros'''
x, y = xy(mark)
up()
goto(x + 13.82, y + 6)
color('black')
lar = ['#','$','%','@','&']
if tiles[mark] < len(lar):
write(lar[tiles[mark]], font=('Arial', 30, 'normal'))
else:
write(tiles[mark], font=('Arial', 30, 'normal'))
'''Aquí se escribe el contador en el extremo superior derecho'''
up()
color('blue')
goto(180,180)
write(taps)
update()
ontimer(draw, 100)
#cuando se detecten 0 cuadrados cubiertos se cierra el programa
if d == 0:
quit()
#Aquí se crea el espacio del juego
shuffle(tiles)
setup(420, 420, 370, 0)
addshape(car)
hideturtle()
tracer(False)
onscreenclick(tap)
draw()
done()
|
111ffadaf83cf8e4054a31ff496f8c06de42bbab | rebecalvarezc/MovieApp | /movie_sql_program/global_functions.py | 3,032 | 4.0625 | 4 | from datetime import datetime
import sqlite3
from database_queries import *
connection = sqlite3.connect('movie_database.db')
def create_database():
"""
This function creates the database if it does not exists.
"""
with connection:
connection.execute(CREATE_MOVIE_TABLE)
connection.execute(CREATE_USER_TABLE)
connection.execute(CREATE_WATCHED_TABLE)
def add_movies(movie_name: str, release_date: float) -> bool:
"""
This function adds a movie to the database.
:param movie_name: movie name
:param release_date: movie release date
:return: bool
"""
with connection:
movie_exists = connection.execute(CHECK_MOVIE, (movie_name, release_date)).fetchone()
if movie_exists is None:
connection.execute(INSERT_MOVIE, (movie_name, release_date))
return True
return False
def get_movies(upcoming: bool = False) -> list[tuple]:
"""
This function shows movie data depending on the given value.
:param upcoming: True for upcoming movies, False for all movies
:return: list[tuple]
"""
with connection:
movies = connection.cursor()
if not upcoming:
return movies.execute(SHOW_MOVIES).fetchall()
now = datetime.now().timestamp()
upcoming_list = movies.execute(UPCOMING_MOVIES, (now,)).fetchall()
if upcoming_list is not None:
return upcoming_list
return []
def new_watched_movie(username: str, movie_id: int) -> bool:
"""
This function changes the timestamp of a movie that's been already watched by the user.
:param movie_id: movie ID
:param username: user name
:return: bool
"""
with connection:
all_movies = connection.execute(MOVIES_IDS, (movie_id,)).fetchone()
all_usernames = connection.execute(USERS_IDS, (username,)).fetchone()
if all_usernames is not None and all_movies is not None:
connection.execute(ADD_WATCHED_MOVIE, (all_usernames[0], movie_id))
return True
return False
def add_user(name: str, last_name: str, username: str) -> None:
"""
This function adds a user into the database.
:param1 name: user name
:param2 last_name: user last name
:param3 username: user username
"""
with connection:
connection.execute(ADD_USER, (name, last_name, username))
def view_watched_movies(username: str) -> list[tuple]:
"""
This function gets all movies marked as watched in the database.
:param1 username: user username
:return: list[tuple]
"""
with connection:
return connection.execute(VIEW_WATCHED_MOVIES, (username,)).fetchall()
def search_movies(title: str) -> list[tuple]:
"""
This function allows to user to search a movie that contains on its title the information the user provides.
:param1 title: movie title
"""
with connection:
search = '%' + title + '%'
return list(connection.execute(SEARCH_MOVIE, (search,)))
|
c68908b69feb328dc9caf97b1d61a7187c6b20bc | Vyvy-vi/XII-CS-pracs | /PRACTICALS/prac_9.py | 558 | 3.53125 | 4 | # PRACTICAL 9
"""
pascal's triangle
Since, recursion is cut from syllabus, here is an iterative version.
However, I may also make a recursive one.
"""
n = int(input("Enter number of rows in the Pascaline Triangle-"))
p = []
for i in range(n):
p.append([])
p[i].append(1)
for j in range(1, i):
p[i].append(p[i - 1][j - 1] + p[i - 1][j])
if(n != 0):
p[i].append(1)
for i in range(n):
print(" " * (n - i), end=" ", sep=" ")
for j in range(0, i + 1):
print('{0:6}'.format(p[i][j]), end=" ", sep=" ")
print()
|
17b07d768300a1292f02ba84891c8272c177e318 | chetan-mali/Python-Traning | /Python Programs/unlucky.py | 384 | 3.71875 | 4 | while(True):
try:
user_input = list(map(int,input("Enter numbers (seperated by ',')").split(",")))
except Exception:
print("Invalid Input !!!")
else:
break
Sum =0
element =0
while(element < len(user_input)):
if user_input[element] == 13:
element+=2
else:
Sum+=user_input[element]
element+=1
print(Sum) |
23f163388183e06d8fa70bbd7872668f2d11bf64 | ErenBtrk/PythonLambdaExercises | /Exercise23.py | 746 | 4.15625 | 4 | '''
23. Write a Python program to calculate the sum of the positive and negative
numbers of a given list of numbers using lambda function.
Original list: [2, 4, -6, -9, 11, -12, 14, -5, 17]
Sum of the positive numbers: -32
Sum of the negative numbers: 48
'''
list1 = [2, 4, -6, -9, 11, -12, 14, -5, 17]
positive = lambda x : x > 0
negative = lambda x : x < 0
result1 = list(filter(positive,list1))
result2 = list(filter(negative,list1))
# positiveSum = 0
# for item in result1:
# positiveSum += item
# negativeSum = 0
# for item in result2:
# negativeSum += item
# print(f"Positive Sum = {positiveSum}")
# print(f"Negative Sum = {negativeSum}")
print(f"Positive Sum = {sum(result1)}")
print(f"Negative Sum = {sum(result2)}")
|
2e60eaa97a8db5b8d3d573bdd9a126997678b368 | ggoudy/Python | /Learning Python/Dictionaries and Lists/dictionary.py | 463 | 4.40625 | 4 | cars = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(cars)
print(cars["brand"])
print(len(cars))
print(cars["colors"])
# Get Keys method which will return a list of all keys in the dictionary
x = cars.keys()
print(x)
# Add a key to the dictionary
cars["engine"] = "4-cyl", "v6", "v8"
print(x)
# Get Values method will return a list of all the values in the dictionary
y = cars.values()
print(y) |
d3494680cb985e08a8f4a2443295f2c1ab1e7ee4 | narasimhareddyprostack/Ramesh-CloudDevOps | /Basics/eight.py | 87 | 3.6875 | 4 | a = 10
b = 20
if(a>b):
print("A is greather")
else:
print("B is greaterh")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.