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 |
|---|---|---|---|---|---|---|
b6badc5994cf8c14eb9c6df3a12706e4377e4ea8 | Isco170/Python_tutorial | /excercises_folder/01_media.py | 276 | 4 | 4 | #nota1 = input("Digite a primeira nota: ")
#nota2 = input("Digite a segunda nota: ")
nota1 = 17
nota2 = 18
media = (int(nota1)+ int(nota2))/2
#Converti media em string, porque nao aceita concatenar float com string para imprimir
print("A media do aluno é de: " + str(media)) |
3c148406a30b6b44dd5378160ada039da6f84ea5 | lanzhiwang/common_algorithm | /leetcode/37_106.py | 1,364 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
106. 从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3])
root = 3
index = 1
root.left = buildTree([9], [9]) [0:index] [0:index]
root.right = buildTree([15, 20, 7], [15, 7, 20]) [index+1:] [index+1:-1]
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not inorder and not postorder:
return None
if len(inorder) == 1 and len(postorder) == 1:
return TreeNode(postorder[-1])
root = TreeNode(postorder[-1])
index = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[0:index], postorder[0:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root
|
71136831e6cda2d39409d8da13d96c6bb286dd99 | MichelleZ/leetcode | /algorithms/python/escapeaLargeMaze/escapeaLargeMaze.py | 1,131 | 3.65625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/escape-a-large-maze/
# Author: Miao Zhang
# Date: 2021-04-06
class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
block = set()
for b in blocked:
block.add((b[0], b[1]))
return self.dfs(source, target, source, block, set()) and \
self.dfs(target, source, target, block, set())
def dfs(self, source: List[int], target: List[int], cur: List[int], block: set, visited: set) -> bool:
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
if cur == target:
return True
if abs(source[0] - cur[0]) + abs(source[1] - cur[1]) > 200:
return True
visited.add((cur[0], cur[1]))
for d in dirs:
x = cur[0] + d[0]
y = cur[1] + d[1]
if 0 <= x < 10 ** 6 and 0 <= y < 10 ** 6 and (x, y) not in visited and (x, y) not in block:
if self.dfs(source, target, [x, y], block, visited):
return True
return False
|
0249165577c3e712cb93140d5e52be92af495416 | vitcmaestro/player | /sine.py | 150 | 3.78125 | 4 | import math
deg = int(input(""))
rad = deg*(math.pi)/180
if(rad<1 and rad>0):
print(round(math.sin(rad),2))
else:
print(round(math.sin(rad)))
|
9c75cb2befa27e9cc053870c7457205c5b0656bf | clusco-2010/clusco-2010 | /Release/PythonCode.py | 1,919 | 3.671875 | 4 | import re
import string
import collections
def Histogram():
# Open both the read and the write files
with open('frequency.dat', "w") as wp:
# Same code as in "ItemCounter" to store the values as a dictionary
with open('CS210_P3.txt') as fp:
counts = collections.Counter(line.strip() for line in fp)
# Write the item and counts to the output file
for key in counts:
wp.write('%s %d\n' % (key, counts[key]))
# If the file was properly closed, tell the user
if wp.closed:
print('Success')
def printsomething():
# Open file use collections module to store the values as a dictionary
with open('CS210_P3.txt') as fp:
counts = collections.Counter(line.strip() for line in fp)
# For every key (item name), print the item and the amount sold
for key in counts:
print('%s %d' % (key, counts[key]))
def veggielist():
print("Vegtables to choose from:\n")
# Open file use collections module to store the values as a dictionary
with open('CS210_P3.txt') as fp:
counts = collections.Counter(line.strip() for line in fp)
# For every key (item name), print the item and the amount sold
for key in sorted(counts):
print(key)
def PrintMe(v):
# Open file use collections module to store the values as a dictionary
with open('CS210_P3.txt') as fp:
counts = collections.Counter(line.strip() for line in fp)
# For every key (item name), print the item and the amount sold
for key in counts:
counts[key]= counts.get(key,0) #calculating frequency
if v in counts: #if given item is present in the string
print("There were ", counts[v]," ", v , " sold today","\n")
return 0
|
244fe3f6725bd00c05587719d75e312466038fb7 | Vagacoder/LeetCode | /Python/LinkedList/Q0002_Add_Two_Numbers.py | 2,343 | 4.03125 | 4 | #
# * Question 2. Add Two Numbers
# * Medium
# You are given two non-empty linked lists representing two non-negative integers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked list.
# You may assume the two numbers do not contain any leading zero,
# except the number 0 itself.
# Example:
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# solution 1
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next: ListNode = None
# helper function to print linked list
def printList(self):
print(self.val)
if(self.next != None):
self.next.printList()
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 != None:
digitFromL1 = l1.val
else:
digitFromL1 = 0
if l2 != None:
digitFromL2 = l2.val
else:
digitFromL2 = 0
sumOfdigits = digitFromL1 + digitFromL2
digitOfResult = sumOfdigits % 10
carrier = sumOfdigits // 10
result = ListNode(digitOfResult)
cursor = result
l1 = l1.next
l2 = l2.next
while (l1 != None or l2 != None):
if l1 != None:
digitFromL1 = l1.val
l1 = l1.next
else:
digitFromL1 = 0
if l2 != None:
digitFromL2 = l2.val
l2 = l2.next
else:
digitFromL2 = 0
sumOfdigits = digitFromL1 + digitFromL2 + carrier
digitOfResult = sumOfdigits % 10
carrier = sumOfdigits // 10
cursor.next = ListNode(digitOfResult)
cursor = cursor.next
if carrier > 0:
cursor.next = ListNode(carrier)
return result
# list1 = [2, 4, 3]
list1 = [2,4,3]
l1 = ListNode(list1[0])
cursor = l1
for i in range(1, len(list1)):
cursor.next = ListNode(list1[i])
cursor = cursor.next
# list2 = [5, 6, 4]
list2 = [5,6,4]
l2 = ListNode(list2[0])
cursor = l2
for i in range(1, len(list2)):
cursor.next = ListNode(list2[i])
cursor = cursor.next
sol = Solution()
print(sol.addTwoNumbers(l1, l2).printList()) |
110606dc8c2150216752c843a0ea816ea19938ef | mmastin/Tutorials | /tutorial1.py | 2,052 | 3.78125 | 4 | nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9]
# my_list = []
# for n in nums:
# my_list.append(n)
# print(my_list)
# my_list = [n for n in nums]
# print(my_list)
# n^2 for each in n in nums
# my_list = [n*n for n in nums]
# print(my_list)
# my_list = map(lambda n: n*n, nums)
# print(my_list)
# I want n for each n in nums if n is even
# my_list = []
# for n in nums:
# if n%2 == 0:
# my_list.append(n)
# print(my_list)
# my_list = [n for n in nums if n%2 ==0]
# print(my_list)
# my_list = filter(lambda n: n%2 == 0, nums)
# print(my_list)
# Want a letter num pair for each letter and each number
# my_list = []
# for letter in 'abcd':
# for num in range(4):
# my_list.append((letter,num))
# # print(my_list)
# my_list = [(letter, num) for letter in 'abcd' for num in range(4)]
# print(my_list)
names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
# # print(zip(names, heros))
# # my_dict = {}
# # for name, hero in zip(names, heros):
# # my_dict[name] = hero
# # print(my_dict)
# dict = {name: hero for name, hero in zip(names, heros) if name != 'Peter'}
# print(dict)
# my_set = set()
# for n in nums:
# my_set.add(n)
# print(my_set)
# my_set = {n for n in nums}
# print(my_set)
nums = [1,2,3,4,5,6,7,8,9,10]
# def gen_func(nums):
# for n in nums:
# yield n*n
# my_gen = gen_func(nums)
# my_gen = (n*n for n in nums)
# for i in my_gen:
# print(i)
# li = [9,1,8,2,7,3,6,4,5]
# li.sort()
# print(li)
# li = [-6,-5,-4,1,2,3]
# s_li = sorted(li, key=abs)
# print(s_li)
# for i in range(1, 11):
# sentence = 'the value is {:03}'.format(i)
# print(sentence)
# pi = 3.14159265
# sentence = 'pi is equal to {:.4f}'.format(pi)
# print(sentence)
# sentence = '1 mb is equal to {:,.2f} bytes'.format(1000**2)
# print(sentence)
import datetime
my_date = datetime.datetime(2016, 9, 14, 12, 30, 45)
sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year'.format(my_date)
print(sentence) |
4791cfc1780df006274f8855eeafcfb8d4dfbb29 | yuliang123456/p1804ll | /第二月/于亮_p10/aa/build/lib/工厂模式.py | 943 | 3.515625 | 4 | class CarStore(object):
def createCar(self,typeName):
pass
def order(self,typeName):
self.car = self.createCar(typeName)
self.car.move()
self.car.stop()
class XiandaiCarStore(CarStore):
def createCar(self,typeName):
self.carFactory=CarFactory()
return self.carFactory.createCar(typeName)
class YilanteCar(object):
def move(self):
print('...车在移动.......')
def stop(self):
print('..停车...')
class SuonataCar(object):
def move(self):
print('......车在移动.......')
def stop(self):
print('...停车.....')
class CarFactory(object):
def createCar(self,typeName):
self.typeName=typeName
if self.typeName =='伊兰特':
self.car=YilanteCar()
elif self.typeName =='索纳塔':
self.car= SuonataCar()
return self.car
suonata=XiandaiCarStore()
suonata.order('索纳塔')
|
fe115f6cd70c3276ef11bb7ecdec0fb54b6ccf14 | ace7chan/leetcode-daily | /code/202011/20201107_327_countRangeSum.py | 609 | 3.546875 | 4 | from typing import List
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
l = len(nums)
res = 0
for i in range(l):
cur_val = nums[i]
if lower <= cur_val <= upper:
res += 1
for j in range(i + 1, l):
cur_val += nums[j]
if lower <= cur_val <= upper:
res += 1
return res
if __name__ == '__main__':
solution = Solution()
nums = [-2, 5, -1]
lower = -2
upper = 2
print(solution.countRangeSum(nums, lower, upper))
|
34f9810d64de2a92c087c978f4fd8d1f4482be1f | MadMerlyn/retirepy | /invest.py | 2,012 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Investment Growth Calculator
@author: MadMerlyn
"""
def Invest(principle, reg_payments, rate, **period):
"""Principle, + regular (monthly) payments, and rate in APR (eg. 0.08)
for period use either 'years=XX' or 'months=XX'
--Prints estimated growth schedule based on anticipated rate of return
--Always prints schedule in years regardless of period selection"""
p = principle #clone value for growth calculation
r = rate/12 #reduce APR to MPR
if 'years' in period:
period = (period['years']*12)+1
elif 'months' in period:
period = period['months']+1
else:
period = 361
results = []
for t in range(period):
balance = p*(1-r**(t+1))/(1-r) #expression for generating interest
if t != 0:
p = balance + reg_payments #maintain total investment cost
principle = principle + reg_payments #update principle amount
growth = p - principle #calculate total interest
invest_data = { #create dict for graphing
'period' : t,
'total' : format(p, '.2f'),
'invested' : format(principle, '.2f'),
'interest' : format(growth, '.2f')
}
results.append(invest_data) #append dicts to results table
if t % 60 == 0 and t != 0:
print("Balance after", int(t/12), "years:", format(p, '.2f'))
print(" Total invested:", format(principle, '.2f'))
print(" Total interest:", format(growth, '.2f'))
print("Expected annual interest on final balance:")
print(" ", format(p*rate, '.2f'))
return results
if __name__ == '__main__':
principle = int(input('Enter starting principle: '))
payment = int(input('Enter monthly payments: '))
rate = float(input('Enter expected APR: '))
Invest(principle, payment, rate)
|
7aae447479d9e8be15cec62fbb71d759d36b1e69 | pangyouzhen/data-structure | /string_/longestNiceSubstring.py | 449 | 3.671875 | 4 | from collections import Counter
from typing import List
class Solution:
def longestNiceSubstring(self, s: str) -> str:
if len(s) == 0:
return ""
c = Counter(s)
not_include_str = []
for i in c.keys():
if i.lower() in c.keys() and i.upper() in c.keys:
pass
pass
if __name__ =="__main__":
func = Solution().longestNiceSubstring
nums =""
print(func(nums)) |
5ec18f9ffa6b9a0230a6b9ed206fe9af84e54deb | prakashreddy31189/Pyhtonprakash | /fpt.py | 320 | 4.28125 | 4 | def even(a):
return a%2==0
print filter(even,(3,5,6,8,10))
print filter(lambda name: name.startswith('p'), ['hari','prakash','atm']) #filter used only for filter operation in group of elements
print 2**3
print map(lambda x: x%3==0,(1,2,3,4,5)) #map is used for manipulation of each element in group of elements
|
4566eeb384aa01ac58bc08e9487cf8c112f4c15c | pranjudevtale/functiongithub | /return4.py | 189 | 4.03125 | 4 | def number():
num=int(input("enter the number"))
i=0
while i<=num:
if i%2==0:
print(i,"even")
else:
print(i,"odd")
i=i+1
number() |
6f6f5fb5c538cfafb557c689c5f7a8e661600e2f | mutedalien/PY | /less_8/main7.py | 784 | 4.25 | 4 | # Набор чисел
numbers = [1, 5, 3, 5, 9, 7, 11]
# Сортировка по возрастанию
print(sorted(numbers))
# Сортировка по убыванию
print(sorted(numbers, reverse=True))
# набор строк
names = ['Max', 'Alex', 'Kate']
# Сортировка по алфавиту
print(sorted(names))
# Города и численность населения
cities = [('Moscow', 1000), ('LosVegas', 500), ('Amsterdam', 2000)]
# Такая сортировка сработает по алфавиту
print(sorted(cities))
# Отсортировать по численности населения
def by_count(city):
return city[1]
print(sorted(cities, key=by_count))
# lambda-функция
print(sorted(cities, key=lambda city: city[1])) |
c231071347c2f819ade100bc5c12a496d96085a8 | watorutart/python_prog | /clock.py | 901 | 3.546875 | 4 | import datetime
import turtle
screen = turtle.Screen()
screen.setup(450, 350)
screen.tracer(0) # 画面のちらつきを防止。ただしタートルの移動などのアニメーションが行われなくなる
time_turtle = turtle.Turtle()
time_turtle.hideturtle()
time_turtle.setposition(-150, -80)
date_turtle = turtle.Turtle()
date_turtle.penup()
date_turtle.hideturtle()
date_turtle.setposition(-170, 30)
weekdays = ["月", "火", "水", "木", "金", "土", "日"]
def clock():
now = datetime.datetime.now()
wday = weekdays[now.weekday()]
date = f"{now.year:}年{now.month}月{now.day}日({wday})"
date_turtle.clear()
date_turtle.write(date, font=("helvetica", 30))
time = f"{now.hour:02d}:{now.minute:02d}:{now.second:02d}"
time_turtle.clear()
time_turtle.write(time, font=("helvetica", 50))
screen.ontimer(clock, 100)
clock()
screen.mainloop()
|
f532e819d14a5170045bae809abde7d788ef8d7a | Azezl/CodeForces_PY | /Problems_Difficulty_800/Word.py | 305 | 3.90625 | 4 | input_string = input()
lst = list(input_string)
num_upper = 0
num_lower = 0
for i in range(len(lst)):
if lst[i].isupper():
num_upper = num_upper + 1
else:
num_lower = num_lower + 1
if num_upper > num_lower:
print(input_string.upper())
else:
print(input_string.lower())
|
419534e4ef413c4da3a5c8698edc44fcfa019100 | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/Exam Problems 15062019/Oscars.py | 473 | 3.640625 | 4 | actor_name = input()
academy_points = float(input())
jury_number = int(input())
result = academy_points
for i in range(1,jury_number+1):
jury_name = input()
jury_points = float(input())
if result > 1250.5:
break
result += (len(jury_name) * jury_points) / 2
if result > 1250.5:
print(f'Congratulations, {actor_name} got a nominee for leading role with {result:.1f}!')
else:
print(f'Sorry, {actor_name} you need {(1250.5-result):.1f} more!') |
09c48a27b153238852c79eea84c64a32fc8ba8df | zokaaagajich/Global-Register-Allocation | /lexer.py | 1,137 | 3.59375 | 4 | import lex
tokens = (
'NUMBER',
'VARIABLE',
'OPERATOR',
'LGT',
'ASSIGN',
'IF',
'GOTO',
'IFFALSE',
'RETURN',
'ARRAY'
)
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
def t_IFFALSE(t):
r'(ifFalse)|(IFFALSE)|(iffalse)'
t.value = "ifFalse"
return t
def t_IF(t):
r'(if)|(IF)'
t.value = t.value.lower()
return t
def t_ARRAY(t):
r'[\[\]]'
return t
def t_GOTO(t):
r'(goto)|(GOTO)'
t.value = t.value.lower()
return t
def t_RETURN(t):
r'(return)|(RETURN)'
t.value = t.value.lower()
return t
def t_VARIABLE(t):
r'[A-Za-z]+[0-9]?'
return t
def t_OPERATOR(t):
r'[+*/-]'
return t
def t_LGT(t):
r'(<=)|[<>]|(>=)'
return t
def t_ASSIGN(t):
r':='
return t
t_ignore = ' \t\n'
# Error handling rule
def t_error(t):
print("Illegal character: %s" % t.value[0])
t.lexer.skip(1)
# Build the lexer
lexer = lex.lex()
# data = """ IFFALSE t < 3 GOTO 3 """
#
# lexer.input(data)
# while True:
# tok = lexer.token()
# if not tok:
# break # No more input
# print(tok)
|
9abbfa2c0792e57b3910bb75f96a3f6855a8c618 | Yegaston/testPython | /Condicionales/bucles.py | 336 | 3.921875 | 4 | # for i in ["primavera", "verano", "otoño", "invierno"]:
# print(i)
#
# email = False
# dirEmail = input("Introduce tu direccion de email: ")
#
# for i in dirEmail:
# if(i == "@"):
# email == True
#
# if email == True:
# print("Correct email")
# else:
# print("Bad mail")
for i in range(4):
print("xd", i)
|
c17005e21c75eb9bb55a0bb396a5926a3301f9a0 | BManduca/Curso_Python3 | /06_resultado_aprovacao_aluno.py | 3,936 | 3.921875 | 4 | '''
Peça ao usuario as seguintes informações sobre um aluno:
Nome
Nota prova 1
Nota prova 2
Total de faltas
Considere que foram dadas 20 aulas e que para passar o aluno precisa de pelo
menos 70% de presença e média 6,0 ou mais.
Ao final imprima
-> Nome do Aluno
-> Média
-> Percentual de Presença(assiduidade)
-> Resultado(Repovado por falta e média, Reprovado por Faltas, Reprovado por média,
Aprovado)
Novo Exercicio:
no programa que calcula a média e imprime a situação do aluno, foi feito
no exercicio sobre condicionais. Aplique a validação de dados para que:
-> o programa nunca seja interrompido por erro
-> a nota seja entre 0 e 10
-> o peso seja entre 0 e 10
-> o número de faltas seja entre 0 e 20
'''
print("\n|----------------------Boletim anual-----------------------|\n\n")
def ponderada(peso1,peso2,prova1,prova2):
soma_pesos = peso1 + peso2;
med = ((peso1 * prova1) + (peso2 * prova2)) / soma_pesos;
return med;
nome = input('Insira o nome do Aluno: ');
controle_boletim = False;
while controle_boletim == False:
nota1 = input('Insira a nota da prova 1: ');
try:
nota1 = float(nota1);
if nota1 < 0 or nota1 > 10:
print('Nota 1 inserida está incorreta! O valor precisa estar entre 0 e 10!');
else:
controle_boletim = True;
except:
print('Valor da nota é inválido! Favor utilizar somente números e separar os decimais através do ".". (Ex.: 9.5)');
controle_boletim = False;
while controle_boletim == False:
nota2 = input('Insira a nota da prova 2: ');
try:
nota2 = float(nota2);
if nota2 < 0 or nota2 > 10:
print('Nota 2 inserida está incorreta! O valor precisa estar entre 0 e 10!');
else:
controle_boletim = True;
except:
print('Valor da nota é inválido! Favor utilizar somente números e separar os decimais através do ".". (Ex.: 9.5)');
controle_boletim = False;
while controle_boletim == False:
peso1 = input('Insira peso da prova 1: ');
try:
peso1 = float(peso1);
if peso1 < 0 or peso1 > 10:
print('Peso 1 está incorreto! O valor precisa estar entre 0 e 10!');
else:
controle_boletim = True;
except:
print('Valor do peso é inválido! Favor utilizar somente números e separar os decimais através do ".". (Ex.: 3.5)');
controle_boletim = False;
while controle_boletim == False:
peso2 = input('Insira peso da prova 2: ');
try:
peso2 = float(peso2);
if peso2 < 0 or peso2 > 10:
print('Peso 2 está incorreto! O valor precisa estar entre 0 e 10!');
else:
controle_boletim = True;
except:
print('Valor do peso é inválido! Favor utilizar somente números e separar os decimais através do ".". (Ex.: 3.5)');
controle_boletim = False;
while controle_boletim == False:
total_faltas = input('Insira o total de faltas do aluno: ');
try:
total_faltas = float(total_faltas);
if total_faltas < 0 or total_faltas > 20:
print('Total de faltas está incorreto! O valor precisa estar entre 0 e 20!');
else:
controle_boletim = True;
except:
print('Quantidade de faltas está inválido! Favor utilizar somente números e separar os decimais através do ".". (Ex.: 15.5)');
media = ponderada(peso1,peso2,nota1,nota2);
presenca = (20 - total_faltas);
assiduidade = ((100 * presenca) / 20);
if assiduidade >= 70 and media >= 6.0:
mensagem = 'Aluno aprovado com mérito!';
elif assiduidade >= 70 and media < 6.0:
mensagem = 'Aluno reprovado por média!!';
elif assiduidade < 70 and media >= 6.0:
mensagem = 'Aluno reprovado por faltas!!';
else:
mensagem = 'Aluno reprovado por falta e média!!';
print("\n\n|---------------------------------------------------------|\n");
print('Aluno:',nome,'\n');
print('Média:',f'{media:.2f}\n');
print('Percentual de presença(assiduidade):',str(assiduidade) + '%\n');
print('Resultado:',mensagem);
print("\n|--------------------Fim do programa----------------------|\n");
input('Pressione enter para finalizar o programa.\n'); |
f967304f0857d12d4d696baa08dedcb29e5bf7f5 | robin025/Flappy-Bird-Game | /main.py | 7,866 | 3.5 | 4 | """
Author : Robin Singh
Flapy Bird Game Devlopment
"""
import random
import sys
import pygame
from pygame.locals import *
pygame.init()
# Game specific Variables for the game
FPS = 40
screen_width = 300
screen_height = 500
game_window = pygame.display.set_mode((screen_width,screen_height))
ground_y =screen_height * 0.8
images = {}
sounds= {}
bird = 'images/bird.png'
backGround = 'images/background.png'
pipee = 'images/pipe.png'
def welcomeScreen():
player_x = int(screen_width/5)
player_y = int((screen_height -images['bird'].get_height())/2)
message_x = int((screen_width -images['message'].get_width())/2)
message_y = int(screen_height*0.13)
base = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# If the user presses space or up key, start the game for them
elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP):
return
else:
game_window.blit(images['background'], (0, 0))
# game_window.blit(images['bird'], (player_x, player_y))
game_window.blit(images['message'], (message_x,message_y ))
game_window.blit(images['base'], (base,ground_y))
pygame.display.update()
clock.tick(FPS)
def mainGame():
score = 0
player_x = int(screen_width/5)
player_y = int(screen_width/2)
base_x = 0
pipe_1 = getRandomPipe()
pipe_2 = getRandomPipe()
upperPipes = [
{'x':screen_width+200, 'y':pipe_1[0]['y']},
{'x':screen_width+200+(screen_width/2), 'y':pipe_2[0]['y']},
]
lowerPipes = [
{'x':screen_width+200, 'y':pipe_1[1]['y']},
{'x':screen_width+200+(screen_width/2), 'y':pipe_2[1]['y']},
]
pipe_Vel_X = -4
playerVelY = -9
playerMaxVelY = 10
playerMinVelY = -8
player_speed = 1
Flap_speed = -8 #flapping speed
playerFlapped = False #when bird is flapping then this value will be true
while True:
for event in pygame.event.get():
if event.type == QUIT:
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_UP:
if player_y > 0:
playerVelY = Flap_speed
playerFlapped = True
sounds['wing'].play()
if event.key == K_DOWN:
score+=1
# if the bird is crashed then isCollide Function Will return True
crashTest = isCollide(player_x, player_y, upperPipes, lowerPipes) # This function will return true if the player gets crashed
if crashTest:
return
#checking score
playerMidPos = player_x +images['bird'].get_width()/2
for pipe in upperPipes:
pipeMidPos = pipe['x'] +images['pipe'][0].get_width()/2
if pipeMidPos<= playerMidPos < pipeMidPos +4:
score +=1
# print(f"Your score is {score}")
sounds['point'].play()
if playerVelY <playerMaxVelY and not playerFlapped:
playerVelY += player_speed
if playerFlapped:
playerFlapped = False
playerHeight =images['bird'].get_height()
player_y = player_y + min(playerVelY,ground_y - player_y - playerHeight) #When Bird touches the base then we will take min() function to determine if bird touches the ground or not if yes then we will get (ground_y-play_y-player_Height = 0)
# will moves lower and upper pipes to left
for upperPipe , lowerPipe in zip(upperPipes, lowerPipes):
upperPipe['x'] += pipe_Vel_X
lowerPipe['x'] += pipe_Vel_X
# before removig a pipe we will add a new pipe into the scrren
if 0<upperPipes[0]['x']<5:
newpipe = getRandomPipe()
upperPipes.append(newpipe[0])
lowerPipes.append(newpipe[1])
# when pipes are getting out of the scrren then remove it
if upperPipes[0]['x'] < -images['pipe'][0].get_width():
upperPipes.pop(0)
lowerPipes.pop(0)
#now we will blit all the images
game_window.blit(images['background'], (0, 0))
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
game_window.blit(images['pipe'][0], (upperPipe['x'], upperPipe['y']))
game_window.blit(images['pipe'][1], (lowerPipe['x'], lowerPipe['y']))
game_window.blit(images['base'], (base_x,ground_y))
game_window.blit(images['bird'], (player_x, player_y))
myDigits = [int(x) for x in list(str(score))]
width = 0
for digit in myDigits:
width += images['numbers'][digit].get_width()
Xoffset = (screen_width - width)/2
for digit in myDigits:
game_window.blit(images['numbers'][digit], (Xoffset,screen_height*0.12))
Xoffset +=images['numbers'][digit].get_width()
pygame.display.update()
clock.tick(FPS)
def isCollide(player_x, player_y, upperPipes, lowerPipes):
if player_y>ground_y- 25 or player_y<0:
sounds['hit'].play()
sounds['die'].play()
return True
for pipe in upperPipes:
pipeHeight =images['pipe'][0].get_height()
if(player_y < pipeHeight + pipe['y'] and abs(player_x - pipe['x']) <images['pipe'][0].get_width()):
sounds['hit'].play()
sounds['die'].play()
return True
for pipe in lowerPipes:
if (player_y +images['bird'].get_height() > pipe['y']) and abs(player_x - pipe['x']) <images['pipe'][0].get_width():
sounds['hit'].play()
sounds['die'].play()
return True
return False
#function for generating random postions of pipes on the screen
#Very Important Function
def getRandomPipe():
pipe_height =images['pipe'][0].get_height()
offset =screen_height/3
y2 = offset + random.randrange(0, int(screen_height -images['base'].get_height() - 1.2 *offset))
pipeX = screen_width + 10
y1 = pipe_height - y2 + offset
pipe = [
{'x': pipeX, 'y': -y1}, #upper Pipe
{'x': pipeX, 'y': y2} #lower Pipe
]
return pipe
if __name__ == "__main__":
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption('FLAPPY BIRD')
images['numbers'] = (
pygame.image.load('images/0.png'),
pygame.image.load('images/1.png'),
pygame.image.load('images/2.png'),
pygame.image.load('images/3.png'),
pygame.image.load('images/4.png'),
pygame.image.load('images/5.png'),
pygame.image.load('images/6.png'),
pygame.image.load('images/7.png'),
pygame.image.load('images/8.png'),
pygame.image.load('images/9.png'),
)
images['message'] =pygame.image.load('images/message.png')
images['base'] =pygame.image.load('images/base.png')
images['pipe'] =(pygame.transform.rotate(pygame.image.load(pipee).convert_alpha(),180),
pygame.image.load(pipee)
)
sounds['die'] = pygame.mixer.Sound('sounds/die.wav')
sounds['hit'] = pygame.mixer.Sound('sounds/hit.wav')
sounds['point'] = pygame.mixer.Sound('sounds/point.wav')
sounds['swoosh'] = pygame.mixer.Sound('sounds/swoosh.wav')
sounds['wing'] = pygame.mixer.Sound('sounds/wing.wav')
images['background'] = pygame.image.load(backGround)
images['bird'] = pygame.image.load(bird)
while True:
welcomeScreen()
mainGame() |
dce657514fe66437d1315753422211a7a1823e95 | wingsthy/python | /eg/eg1.py | 411 | 3.65625 | 4 | name = "ada"
print(name.upper())
print(name.lower())
first_name = "hello"
last_name = "world"
full_name = first_name + " " +last_name
print(full_name)
print("\tPython")
print("Language:\nPython\nC\nJavaScript")
favorite_language = 'python '
print(favorite_language)
favorite_language.rstrip()
print(2+4)
age = 24
message = "Happy " + str(age) + "rd Birthday"
print(message)
print("hello world")
|
2e8d6685b9b5b6e22e25024278e049e5ac3d0e4c | himani1213/SpringMicroservices | /New Workspace/BasicPrograms/controlprog.py | 116 | 3.78125 | 4 | n=int(input("Enter a number: "))
i=1
while i<n and i<=100:
i+=1
if(i%10==0):
continue
print(i)
|
853034927ac1da25edb398f5b2cbd805eafc6c62 | hongxchen/algorithm007-class01 | /Week_09/G20200343040079/LeetCode_787_0079.py | 4,400 | 3.78125 | 4 | #! /usr/bin/env python
# coding: utf-8
# 学号:G20200343040079
""" https://leetcode.com/problems/cheapest-flights-within-k-stops/
题目描述
787. Cheapest Flights Within K Stops
Medium
There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.
Now given all the cities and flights, together with starting city src and the destination dst,
your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
Note:
The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
The size of flights will be in range [0, n * (n - 1) / 2].
The format of each flight will be (src, dst, price).
The price of each flight will be in the range [1, 10000].
k is in the range of [0, n - 1].
There will not be any duplicated flights or self cycles.
"""
from typing import List
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# # 解法1 DFS深度优先遍历
# from collections import defaultdict
# f = defaultdict(dict)
# for a, b, p in flights:
# f[a][b] = p # 城市之间的距离
#
# def _dfs(src, k, dist):
# nonlocal ans
# if src == dst:
# ans = min(ans, dist)
# return
# if k < 0: return
#
# for d in f[src]:
# if d in visited: continue # // todo do not visit the same city twice.剪枝, 否则不通过
# if dist + f[src][d] > ans: continue # // todo IMPORTANT!!! prunning, 剪枝, 否则不通过
#
# visited.add(d)
# _dfs(d, k - 1, dist + f[src][d])
# visited.remove(d)
# return
#
# ans = float('inf')
# visited = set()
# visited.add(src)
# _dfs(src, K, 0)
# return -1 if ans >= float('inf') else ans
# # 解法2 BFS广度优先遍历
# from collections import defaultdict
# f = defaultdict(dict)
# for a, b, p in flights:
# f[a][b] = p
#
# ans = float('inf')
# k = 0
# from collections import deque
# q = deque([(src, 0)])
# while q:
# for _ in range(len(q)):
# s, distance = q.popleft()
# if s == dst:
# ans = min(ans, distance)
# continue
# for p in f[s]:
# if distance + f[s][p] > ans: continue # todo IMPORTANT prunning 剪枝
# q.append((p, distance + f[s][p]))
# if k > K: break
# k += 1
# return -1 if ans >= float('inf') else ans
# 解法3 动态规划, Bellman-Ford algorithm
# todo 将一次转机作为动作转移
# todo 问题分析是关键, 动作是飞行
# 动态规划
dp = [float('inf')] * n
dp[src] = 0
for _ in range(K + 1):
tmp = dp[:]
for u, v, c in flights:
dp[v] = min(dp[v], tmp[u] + c) # todo 注意min里面, 转机是从tmp过来的
return -1 if dp[dst] == float('inf') else dp[dst]
# # 解法4 Dijkstra算法
# from collections import defaultdict
# f = defaultdict(dict)
# for u, v, d in flights:
# f[u][v] = d
#
# import heapq
# heap = [(0, src, K)]
# while heap:
# distance, u, k = heapq.heappop(heap)
# if u == dst: return distance
#
# if k >= 0:
# for v, d in f[u].items():
# heapq.heappush(heap, (distance + d, v, k - 1))
# return -1
print(Solution().findCheapestPrice(3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 1))
|
6f4bd9adc3a050d83032812aa37941219cc49bf9 | fl-ada/Toy_programs | /Python_programming/sudoku.py | 1,739 | 3.734375 | 4 | #sudoku
#fill_in_box not yet
import numpy as np
def find_empty(matrix):
for i in range(9):
prod = int(1)
for j in range(9):
prod = int(prod*matrix[i][j])
if prod == 0:
return i+1 # return empty row, 1-9
return 0 # sudoku completed
def fill_in_row(matrix):
for i in range(9):
arr = [x+1 for x in range(9)]
for j in range(9):
if matrix[i][j] != 0:
arr.remove(matrix[i][j])
else:
key = j
if len(arr)==1:
matrix[i][key]=arr[0]
def fill_in_col(matrix):
for j in range(9):
arr = [x+1 for x in range(9)]
for i in range(9):
if matrix[i][j] != 0:
arr.remove(matrix[i][j])
else:
key = i
if len(arr)==1:
matrix[key][j]=arr[0]
def fill_in_box(matrix):
# 1 2 3
# 4 5 6
# 7 8 9
mat[0]=matrix[0:2,]
mat[1]=matrix[3:5,]
mat[2]=matrix[6:8,]
for i in range(3):
mat[i][0]=mat[i,0:2]
mat[i][1]=mat[i,3:5]
mat[i][2]=mat[i,6:8]
for i in range(3):
for j in range(3):
mat = sum(mat[i][j],[])
arr = [x+1 for x in range(9)]
for k in range(9):
if mat[k] != 0:
arr.remove(mat[k])
else:
key = k
if len(arr)==1:
matrix[k]=arr[0]
matrix[mat_arr[i]][mat_arr[j]] = [list(map(int, mat)) for i in range(9)]
matrix = [list(map(int, input().split())) for i in range(9)]
while find_empty(matrix) != 0:
fill_in_row(matrix)
fill_in_col(matrix)
fill_in_box(matrix)
print(matrix) |
0f1aed36b74427ad50c9a9fc67f3944163df5755 | jansenmtan/Project_Euler | /23.py | 1,260 | 3.625 | 4 | #-*-coding:utf8;-*-
#qpy:3
#qpy:console
'''Thanks Stack Overflow!'''
def factorizer(number,limit):
factors = []
gate = isinstance(limit,int)
for x in range(1,int(number ** 0.5) + 1):
'''if x % round(number / 100) == 0:
print("Iteration: {}".format(x))'''
if number % x == 0:
factors.append(x)
if x != int(number / x):
factors.append(int(number / x))
if gate == True:
if len(factors) > limit:
break
factors.sort()
return factors
def is_abundant(number):
number_factors = factorizer(number,"")[:-1]
if sum(number_factors) > number:
return True
else:
return False
abundants = [number
for number in range(1,28123 + 1)
if is_abundant(number)]
print("Made abundants")
not_addends = {abundant + bundant
for abundant in abundants
for bundant in abundants[abundants.index(abundant):]
if abundant + bundant < 28123 + 1}
print("Made not addends")
addends = [number
for number in range(1,28123 + 1)
if number not in not_addends]
print("Made addends")
print(sum(addends)) |
0a13894b42fe38779a259891aeea085007f7f27a | Luoxsh6/superintendent | /src/superintendent/controls/timer.py | 1,227 | 3.96875 | 4 | import time
from math import nan
from contextlib import ContextDecorator
class Timer(ContextDecorator):
"""
A timer object. Use as a context manager to time operations, and compare to
numerical values (seconds) to run conditional code.
Usage:
.. code-block:: python
from superintendent.controls import Timer
timer = Timer()
with timer:
print('some quick computation')
if timer < 1:
print('quick computation took less than a second')
"""
def __init__(self):
self._time = nan
self._t0 = nan
def start(self):
self._time = nan
self._t0 = time.time()
def stop(self):
self._time = time.time() - self._t0
def __enter__(self):
self.start()
def __exit__(self, *args):
self.stop()
def __eq__(self, other):
return self._time == other
def __lt__(self, other):
return self._time < other
def __le__(self, other):
return self._time <= other
def __gt__(self, other):
return self._time > other
def __ge__(self, other):
return self._time >= other
def __repr__(self):
return "{} s".format(self._time)
|
7170cf11792aabb7ea9d265b790c2a4d31f0eaad | BOYGABAS/Activity2-Fibonacci | /fibbonacci.py | 2,034 | 3.984375 | 4 | '''
Isaiah Andre Pabillon
BSCS-2
2018-5769
Algorithm(Do Better):
Combining recursion and iteration algorithm to produce "Andre" algorithm
1) Define a function that has 1 non-default(fib) and 3 default(kawnter,lead and tail) parameters
2) The after every iteration, plug in the sum of the lead and tail in the place of a new lead
And plug in the lead as the new tail for the next recursive iteration
3) If the counter reaches the non default parameter, return the lead as the final term
'''
import time
import matplotlib.pyplot
def fib_1(fib):
if fib<=1:
return fib
else:
return fib_1(fib-1)+fib_1(fib-2)
def fib_2(fib):
lead=1
tail=0
newlead=1
for i in range(fib-1):
newlead=lead+tail
tail=lead
lead=newlead
return newlead
def fib_3(fib,kawnter=1,lead=1,tail=0):
if kawnter>=fib:
return lead
return fib_3(fib,kawnter+1,lead+tail,lead)
#print(fib,fib1)
fib_times=[[],[],[]]
xaxis=[]
print("\"He that can have patience can have what he will.\" - Benjamin Franklin")
#print(fib_3())
for x in range(30):
x+=1
start=time.time()
fib_1(x)
fib_times[0].append(time.time()-start)
#print(fib_times)
start=time.time()
fib_2(x)
fib_times[1].append(time.time()-start)
#print(fib_times)
start=time.time()
fib_3(x)
fib_times[2].append(time.time()-start)
xaxis.append(x)
#print(fib_times)
matplotlib.pyplot.plot(xaxis, fib_times[0], label="Recursive")
matplotlib.pyplot.plot(xaxis, fib_times[1], label="Iterative")
matplotlib.pyplot.plot(xaxis, fib_times[2], label="Andre's Algorithm")
matplotlib.pyplot.xlabel('Terms')
matplotlib.pyplot.ylabel('Time')
matplotlib.pyplot.title('Time to produce a term in a fibbonaci sequence')
matplotlib.pyplot.legend()
matplotlib.pyplot.show()
#print(fib_times[0][-1])
'''
print(fib_1(5))
print(1+1+2+3+5)
print(1024+512+256+128+64+16)
print(64)
print(fib_2(5))
print(fib_3(5))
'''
|
2178b28727be547b157bf16959d474e9efce8457 | daniel-reich/ubiquitous-fiesta | /GAbxxcsKoLGKtwjRB_16.py | 301 | 3.828125 | 4 |
def sum_primes(lst):
sum = 0
if len(lst)!=0:
for num in lst:
if num==2:
sum += num
elif num==1:
continue
else:
for i in range(2,num):
if num%i==0:
break
else:
sum += num
return sum
else:
return None
|
885a7d173a135e751cc2a0b3ba66a673331528d2 | baloooo/coding_practice | /inorder_traversal.py | 2,152 | 4.15625 | 4 | # coding:utf-8
"""
Given a binary tree, return the inorder traversal of its nodes’ values.
Example :
Given binary tree
1
\
2
/
3
return [1,3,2].
"""
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
Inorder using morris traversal
https://en.wikipedia.org/wiki/Tree_traversal#Morris_in-order_traversal_using_threading
"""
inorder_repr = []
now = root
while now:
if now.left:
pre = now.left
while pre.right and pre.right != now:
pre = pre.right
if pre.right != None:
pre.right = None
inorder_repr.append(now.val)
now = now.right
else:
pre.right = now
now = now.left
else:
inorder_repr.append(now.val)
now = now.right
return inorder_repr
def inorder_recursion(root):
inorder_list = []
def inorder(root):
if root is None:
return
inorder(root.left)
inorder_list.append(root.val)
inorder(root.right)
inorder(root)
return inorder_list
def inorder_iteration(root):
# trick is to use stack, which recursion uses also.
from tree_base import Node
stack = [root]
tos = None
in_order = []
while(stack or tos is not None):
if tos is None:
tos = stack.pop()
if not isinstance(tos, Node):
in_order.append(tos)
try:
tos = stack.pop()
except IndexError:
tos = None
continue
if tos.right is not None:
stack.append(tos.right)
stack.append(tos.val)
tos = tos.left
return in_order
if __name__ == '__main__':
from tree_base import level_order_array_to_tree
# arr = [1, None, 2, None, None, 3, None]
# arr = ['A', 'B', 'C', 'D', "E", "F", "G"]
# arr = ['A', 'B', 'C']
arr = ['a', 'b']
root = level_order_array_to_tree(arr)
print inorder_iteration(root)
|
3226bbae5aaeb6172fcaecb6e6b1e55a58354a5a | AayushRajput98/PythonML | /Practice/Tut1/Program12.py | 267 | 4.28125 | 4 | def is_palindrome(s):
if s == s[::-1]:
print("The string '{0}' is a palindrome string".format(s))
else:
print("The string '{0}' is not a palindrome string".format(s))
s=input("Enter the string to be checked for palindorme: ")
is_palindrome(s) |
fb9b6327e89dbfad188af38427b81f4d69ad1cc3 | banalna/pip-services3-commons-python | /pip_services3_commons/convert/IntegerConverter.py | 2,237 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
pip_services3_commons.convert.IntegerConverter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Integer conversion utilities
:copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
class IntegerConverter():
"""
Converts arbitrary values into integers using extended conversion rules:
- Strings are converted to floats, then to integers
- DateTime: total number of milliseconds since unix epoсh
- Boolean: 1 for true and 0 for false
Example:
value1 = IntegerConverter.to_nullable_integer("ABC") // Result: None
value2 = IntegerConverter.to_nullable_integer("123.456") // Result: 123
value3 = IntegerConverter.to_nullable_integer(true) // Result: 1
value4 = IntegerConverter.to_nullable_integer(datetime.datetime.now()) // Result: current milliseconds
"""
@staticmethod
def to_nullable_integer(value):
"""
Converts value into integer or returns null when conversion is not possible.
:param value: the value to convert.
:return: integer value or null when conversion is not supported.
"""
# Shortcuts
if value == None:
return None
try:
value = float(value)
return int(value)
except:
return None
@staticmethod
def to_integer(value):
"""
Converts value into integer or returns 0 when conversion is not possible.
:param value: the value to convert.
:return: integer value or 0 when conversion is not supported.
"""
return IntegerConverter.to_integer_with_default(value, 0)
@staticmethod
def to_integer_with_default(value, default_value):
"""
Converts value into integer or returns default value when conversion is not possible.
:param value: the value to convert.
:param default_value: the default value.
:return: integer value or default when conversion is not supported.
"""
result = IntegerConverter.to_nullable_integer(value)
return result if result != None else default_value
|
9d030c689096d8f4652003ddf090700dded63317 | williamh890/annual_return | /python/annual_return.py | 2,937 | 3.546875 | 4 | import csv
import random
import time
import copy
random.seed(time.time())
class Year(object):
def __init__(self, year=None, stocks=None, bonds=None, treasuries=None):
self.year = int(year)
self.stocks = float(stocks) / 100
self.bonds = float(bonds) / 100
self.treasuries = float(treasuries) / 100
def __str__(self):
return "{}, {}, {}, {}".format(self.year, self.stocks,
self.bonds, self.treasuries)
def get_ratios(self):
return [self.stocks, self.bonds, self.treasuries]
class Strategy(object):
def __init__(self, addition, stocks, bonds, treasuries):
self.addition = addition
self.stocks = stocks
self.bonds = bonds
self.treasuries = treasuries
if stocks + bonds + treasuries > 1:
raise StandardError("Over 100 entered for strategy")
def __repr__(self):
return "Strategy({}, {}, {}, {})".format(3600, self.stocks, self.bonds, self.treasuries)
def __str__(self):
return "{}, {}, {}".format(self.stocks, self.bonds, self.treasuries)
years = []
with open("historical_data.csv", "r") as historical_data_csv:
historical_data = csv.reader(historical_data_csv)
for year in historical_data:
new_year = Year(
year=year[1],
stocks=year[2][:-1],
treasuries=year[3][:-1],
bonds=year[4][:-1]
)
years.append(new_year)
def annual_return(num_years, strategy):
balance = 0
distribution = {}
deviations = []
for y in range(num_years):
if y != num_years:
balance += strategy.addition
# Find the random year values
random_year = random.choice(years)
distribution = {"stocks": balance * strategy.stocks * random_year.stocks,
"bonds": balance * strategy.bonds * random_year.bonds,
"treasuries": balance * strategy.treasuries * random_year.treasuries}
for invest_class, amount in distribution.items():
balance += amount
return round(balance)
def write_results(strat_returns):
with open("data.csv", "w") as data_file:
for returns in strat_returns:
line = ""
for run in returns:
line += "{}, ".format(run)
data_file.write(line[:-1] + "\n")
if __name__ == "__main__":
acending_decending_percentages = zip(
[x / 10 for x in range(0, 11, 1)],
[x / 10 for x in range(10, -1, -1)]
)
strats = [
Strategy(3600, stock_amount, bond_amount, 0) for stock_amount, bond_amount in acending_decending_percentages
]
strat_returns = []
for strat in strats:
returns = []
for run in range(1000):
returns.append(annual_return(30, strat))
strat_returns.append(sorted(returns))
write_results(strat_returns)
|
13ff4e38a6849f94813bd02d5791e0cf42c9bdee | DiegoMeruoca/Python4-String | /Ex3-Pesquisa in e not in.py | 742 | 4.4375 | 4 | # Exemplo 3 - Pesquisa in e not in
S = "Maria Amélia Souza" # Cria a String
print("Amélia" in S)
# Verifica se Amelia está na String, neste caso True
print("Maria" in S)
# Verifica se Maria está na String, neste caso True
print("Souza" in S)
# Verifica se Souza está na String, neste caso True
print("a A" in S)
# Verifica se a A está em alguma parte da String, neste caso True
print("amélia" in S)
# Verifica se amelia está na String, neste caso False por causa da letra minuscula
S = "Todos caminhos levam a Roma"
print("levan" not in S) # Verifica se levam não está na String, neste caso True
print("Caminhos" not in S) # Verifica se Caminhos não está na String,
# neste caso True, pois caminhos é diferente de Caminhos
|
627bafe8a115b7ecca57e2bd051698ffb315cc77 | ifnfn/haha_video | /kola/singleton.py | 409 | 3.546875 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
class SingletonType(type):
def __call__(cls):
if getattr(cls, '__instance__', None) is None:
instance = cls.__new__(cls)
instance.__init__()
cls.__instance__ = instance
return cls.__instance__
# Usage
class Singleton(object,metaclass=SingletonType):
def __init__(self):
print('__init__:', self)
|
508077440da08e8da892bf0d7631c634df0cb0c1 | jwymanumich/SI650Team | /ir_work.py | 4,361 | 3.53125 | 4 | ''' file that handles code for parsing tweet text and doing TFIDF type things '''
import math
from document import Document
from invertedindex import InvertedIndex
class Collection():
''' Just a bunch of documents '''
def __init__(self):
self._documents = []
self.num_docs = 0
self.avg_dl = None
def add_document(self, cur_document):
''' Add a document to this collection '''
self._documents.append(cur_document)
self.num_docs = len(self._documents)
self.avg_dl = None
def get_document(self, index):
''' Access a document in this collection '''
return self._documents[index]
def get_documents(self):
''' Access a document in this collection '''
return self._documents
def get_avg_dl(self):
''' get length of average document as a decimal '''
if(self.avg_dl is None):
total_size = sum([len(item._words) for item in self._documents])
self.avg_dl = total_size / self.num_docs
return self.avg_dl
def get_doc_count(self):
''' get the total number of documents in the collection '''
return self.num_docs
"""
sd.num_docs: total number of documents in the index
sd.avg_dl: average document length of the collection
sd.total_terms: total number of terms in the index
sd.corpus_term_count: number of times a term t_id appears in the collection
sd.doc_count: number of documents that a term t_id appears in
sd.doc_term_count: number of times the term appears in the current document
sd.doc_size: total number of terms in the current document
sd.doc_unique_terms: number of unique terms in the current document
sd.query_length: the total length of the current query (sum of all term weights)
sd.query_term_weight: query term count (or weight in case of feedback)
"""
def score_one_bm25(word, document, inverted_index, collection, k1, b, k3):
num_docs = collection.get_doc_count()
doc_count = len(inverted_index.get_word_info(word)['doc_ids'])
# doc_term_count = inverted_index.get_word_info(word)['document_frequency']
doc_term_count = document.term_count(word)
avg_dl = collection.get_avg_dl()
doc_unique_terms = document.total_term_count()
idf_value = float(num_docs - doc_count + 0.5) / float(doc_count + 0.5)
numerator = (float(k1 + 1) * doc_term_count)
denominator = (k1 * (1 - b + b * (float(doc_unique_terms)/avg_dl)) + doc_term_count)
r = math.log(idf_value) * (numerator / denominator)
# * (((k3 + 1) * sd.query_term_weight) / (k3 + sd.query_term_weight))
return r
def score_tf_idf(word, document, inverted_index, collection, k1, b, k3):
doc_term_count = document.term_count(word)
doc_count = collection.get_doc_count()
term_document_count = inverted_index.get_term_document_count(word)
type_freq = float(doc_term_count)/document.total_term_count()
idf = doc_count/ term_document_count
return type_freq * math.log(idf)
def load_data2(tweets, stop_words):
return "A String"
def load_data(tweets, stop_words):
''' Load words from file, skipping items matching values
in the provided set of stop_words'''
my_inv_index = InvertedIndex()
my_collection = Collection()
friends = []
for tweet in tweets:
cur_document = Document(tweet['id'], tweet['text'], stop_words)
for mention in tweet["entities"]["user_mentions"]:
# print(mention["id"])
friends.append(mention["id_str"])
my_inv_index.add_document(cur_document)
my_collection.add_document(cur_document)
# for friend in set(friends):
# tw_handle = TwitterWrapper(friend)
# for tweet2 in tw_handle.load_tweets(cache_only=True):
# print(tweet2["text"])
i = 0
max_value = 0
d2 = None
query = my_collection.get_documents()[0]
# return "ASDFfffFF"
# for document in my_collection.get_documents()[1:]:
# value = 1
# for word in query.get_words():
# value *= score_tf_idf(word, document, my_inv_index, my_collection, k1 = 1.2, b = 0.75, k3 = 500)
# value *= score_one_bm25(word, document, my_inv_index, my_collection, k1 = 1.2, b = 0.75, k3 = 500)
# if(value > max_value):
# max_value = value
# d2 = document
return my_inv_index, my_collection
|
1e86b1477e8095224a251a9c3532d9a8e7c199e8 | kurama1711/Tic-Tac-Toe | /tic-tac-toe.py | 2,671 | 3.640625 | 4 | cross = True
step = 1
moves = {}
for i in range(0, 3):
for j in range(0, 3):
moves[(i, j)] = '-'
def print_field():
print(" 0 1 2")
for i in range(0, 3):
row = str(i)
for j in range(0, 3):
row += " " + moves[(j, i)]
print(row)
def game_check():
print_field()
for i in range(0, 3):
x_counter_Ox = x_counter_Oy = o_counter_Ox = o_counter_Oy = 0
for m in moves:
if m[0] == i and moves[m] == 'X':
x_counter_Ox += 1
if m[1] == i and moves[m] == 'X':
x_counter_Oy += 1
if m[0] == i and moves[m] == 'O':
o_counter_Ox += 1
if m[1] == i and moves[m] == 'O':
o_counter_Oy += 1
if any([x_counter_Ox == 3, x_counter_Oy == 3,
moves[(0, 0)] == moves[(1, 1)] == moves[(2, 2)] == 'X',
moves[(0, 2)] == moves[(1, 1)] == moves[(2, 0)] == 'X']):
print("\nИгра окончена!\nПобедил Игрок 1 (крестики)!")
return 1
if any([o_counter_Ox == 3, o_counter_Oy == 3,
moves[(0, 0)] == moves[(1, 1)] == moves[(2, 2)] == 'O',
moves[(0, 2)] == moves[(1, 1)] == moves[(2, 0)] == 'O']):
print("\nИгра окончена!\nПобедил Игрок 2 (нолики)!")
return 2
if step == 9:
print("\nИгра окончена.\nВышла ничья.")
return 0
print("\nИгра продолжается.")
return 3
print("Добро пожаловать в игру Крестики-Нолики!\n\n1) Двое Игроков ходят по очереди.\n2) Игра всегда начинается с хода крестиком.\n3) Чтобы сделать ход, нужно ввести координаты клетки через пробел: X Y\n")
print_field()
while step <= 9:
if cross == True:
print("\nСейчас ходит Игрок 1 (крестики)")
else:
print("\nСейчас ходит Игрок 2 (нолики)")
x_y = tuple(map(int, input("Введите координаты клетки: ").split(' ')))
if 0 <= x_y[0] <= 2 and 0 <= x_y[1] <= 2:
if moves[x_y] != '-':
print("Эта клетка уже занята. Введите другие координаты.")
continue
else:
if cross == True:
moves[x_y] = 'X'
else:
moves[x_y] = 'O'
print("Ход сделан.\n")
else:
print("Введены недопустимые координаты. Введите другие.")
continue
if cross == True:
cross = False
else:
cross = True
game_check()
step += 1
|
6d318977d45d98ba702520934f00f18bb706d7cc | WakeArisato/Personal_Stuff | /Bubble Sorting.py | 656 | 3.78125 | 4 | import time
import random
List_Range = input("What is the length of your list? ")
list = random.sample(range(int(List_Range)), int(List_Range))
def sorting(bad_list):
M = int(0)
length = len(bad_list) - 1
Sorted = False
while not Sorted:
Sorted = True
for i in range(length):
if bad_list[i] > bad_list[i+1]:
Sorted = False
M = M + 1
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
print(list)
time.sleep(.1)
print(list)
print(M)
sorting(list)
#Attempts
#1:2324
#2:2494
#3:2475
#4:2413
#5:2230
#6:2534
#avg = 2387.2 |
fc0204347dd2ac4e29914007bf37f2fd1d99f6ce | chaotism/python-snake | /my_snake/game_source/snake.py | 2,615 | 3.53125 | 4 | # coding: utf-8
from __future__ import generators, print_function, division, unicode_literals
from collections import deque
import pygame
from random import randrange
import sys
from pygame.locals import *
from graphics import Blocks, Point, DIRECTION_RIGHT
from settings import SNAKE_START_LENGTH, SNAKE_SPEED_INITIAL, SNAKE_SPEED_INCREMENT, TIME_DELTA, GROWTH_PENDING
class Snake(Blocks):
def __init__(self, start=Point((1, 1)), start_length=2, growth_pending=1):
self.speed = SNAKE_SPEED_INITIAL # Speed in squares per second.
self.timer = self.get_timer() # Time remaining to next movement.
self.timedelta = TIME_DELTA # need to config
# Number of segments still to grow.
self.growth_pending = growth_pending
self.direction = DIRECTION_RIGHT # Current movement direction.
seq = [start - self.direction * i for i in xrange(start_length)]
return super(Snake, self).__init__(seq, form='snake', eatable=False)
def get_timer(self):
return 1.0 / self.speed
def change_direction(self, direction):
"""Update the direction of the snake."""
# Moving in the opposite direction of current movement is not allowed.
if self.direction != -direction:
self.direction = direction
def get_head(self):
"""Return the position of the snake's head."""
return self[0]
def check_timer(self):
"""Update the snake by dt seconds and possibly set direction."""
self.timer -= self.timedelta
if self.timer > 0:
return True
else:
self.timer = self.get_timer()
return False
def update(self):
if self.check_timer():
return False
if self.get_head() + self.direction != self[1]:
self.appendleft(self.get_head() + self.direction)
else:
self.appendleft(self.get_head() - self.direction)
if self.growth_pending > GROWTH_PENDING:
self.growth_pending -= GROWTH_PENDING
else:
# Remove tail.
self.pop()
return True
def grow(self):
"""Grow snake by one segment and speed up."""
self.growth_pending += 1
self.speed += SNAKE_SPEED_INCREMENT
def self_intersecting(self):
"""Is the snake currently self-intersecting?"""
it = iter(self)
head = next(it)
return head in it
def bound(self, world_size):
"""Detect border."""
head = self.get_head()
head[0] = head.x % (world_size)
head[1] = head.y % (world_size)
|
b2ee6358773ea249caf04489d09c993e0ad732ce | Asadullo-aka/python_darslar | /python_10-dars/takrorlash.py | 549 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 09:55:26 2021
@author: Asadullo
"""
#primitiv data types
a= int ()
b=float()
c=bool()
d=str()
#non -pritive data types
n1=list()
n2=tuple()
n3=set()
n3=dict()
#%%
print(*'salom',sep=',',end='?')
son= int(input ('son :'))
print('son_',son)
print(" salom "*5)
print(10**2,10//3,10/3,10%3)
a,b,c=input().split()
print(a,b,c)
lis=list()
lis=input ('son vergull bn').split(',')
print(lis)
#%%
print(int (16**(1/2)))
a=123.456
a=int(a)
print(a)
b=float(a)
print(b)
str1='123'
str1=int (str1)
print(str1) |
898f2b3dc6ed130bf7fb1aab68d956d2df3b402e | ChadDiaz/CS-masterdoc | /1.2 Data Structures & Algorithms/Hash Tables II/wordPattern.py | 1,366 | 4.15625 | 4 | """
Given a pattern and a string a, find if a follows the same pattern.
Here, to "follow" means a full match, such that there is a one-to-one correspondence between a letter in pattern and a non-empty word in a.
Example 1:
Input:
pattern = "abba"
a = "lambda school school lambda"
Output: true
Example 2:
Input:
pattern = "abba"
a = "lambda school school coding"
Output:
false
Example 3:
Input:
pattern = "aaaa"
a = "lambda school school lambda"
Output: false
Example 4:
Input:
pattern = "abba"
a = "lambda lambda lambda lambda"
Output: false
Notes:
pattern contains only lower-case English letters.
a contains only lower-case English letters and spaces ' '.
a does not contain any leading or trailing spaces.
All the words in a are separated by a single space.
[execution time limit] 4 seconds (py3)
[input] string pattern
[input] string a
[output] boolean
"""
def csWordPattern(pattern, a)
words = a.split(" ")
if not len(words) == len(pattern):
return False
mapping = dict()
for char in range(len(words)):
if pattern[char] not in mapping:
if words[char] not in mapping.values():
mapping[pattern[char]] = words[char]
else:
return False
else:
if not mapping[pattern[char]] == words[char]:
return False
return True |
15a092964af045d2f619f4b2f0034ff8def8bee4 | Emfir/task-5 | /NumberGuesser.py | 974 | 3.59375 | 4 | import random
import enums
class NumberGuesser():
def __init__(self):
self.numberToGues = random.randint(0 , 100);
def nextGuess(self, clientNumber):
if clientNumber == self.numberToGues:
return enums.resultsOfTheGuess.goodGuess
elif clientNumber > self.numberToGues:
return enums.resultsOfTheGuess.tooBig
elif clientNumber < self.numberToGues:
return enums.resultsOfTheGuess.tooSmall
# while 1 :
#
# try:
# clientNumber = int(input("whats your gues\n"))
# except Exception as error:
# print("Write proper input!")
# continue
#
#
#
# if clientNumber == numberToGues:
# print ("You guest")
# break
# elif clientNumber > numberToGues:
# print ("to big")
# elif clientNumber < numberToGues:
# print ("to small")
|
03b9a0158268e6850721657f340a2ba9374e2f07 | AtIasz/TWweekNo1 | /TWweekNO1/MinMaxAvg.py | 391 | 3.6875 | 4 | RandomList=[-5,23,0,-9,12,99,105,-43]
numMin=RandomList[0]
numMax=RandomList[0]
numAVG=0
for i in range(len(RandomList)):
if numMin>RandomList[i]
:
numMin=RandomList[i]
if numMax<RandomList[i]:
numMax=RandomList[i]
numAVG+=RandomList[i]
numAVG=numAVG/len(RandomList)
print("Maximum: "+str(numMax))
print("Minimum: "+str(numMin))
print("Average: "+str(numAVG)) |
35b231b41e328a8d7b37ff1994fde31ed2504ea0 | brouse12/othello | /othello_viz.py | 2,949 | 4.1875 | 4 | '''
Brian Rouse
CS5001
Homework 7 - othello_viz.py
December 2, 2018
Module for drawing a game of Othello.
Note: some functions take Point objects as arguments. See othello.py module.
'''
TILE_RADIUS = 20
import turtle
def draw_tile(point, color):
'''parameters: x,y coordinates for turtle to draw an Othello tile (a point);
and tile color (a string, typically 'white' or 'black')
returns: nothing
'''
# Setup turtle to draw tile.
turtle.hideturtle()
turtle.speed(0)
turtle.color('black', color)
turtle.setheading(90)
# Go to point and draw the tile.
turtle.penup()
turtle.goto(point.x, point.y)
turtle.pendown()
turtle.begin_fill()
turtle.circle(TILE_RADIUS)
turtle.end_fill()
def draw_board(n, tile_positions, square_size):
'''parameters: n, an int for # of squares;
tile_positions, a nested list with positions and colors
for initial tiles (format: [[point, color]...]);
square_size - an int for length/width of each square
returns: nothing
does: draws an nxn Othello board with a green background and 4 starting
tiles
'''
turtle.setup(n * square_size + square_size, n * square_size + square_size)
turtle.screensize(n * square_size, n * square_size)
turtle.bgcolor('white')
# Create the turtle to draw the board
othello = turtle.Turtle()
othello.penup()
othello.speed(0)
othello.hideturtle()
# Line color is black, fill color is green
othello.color("black", "forest green")
# Move the turtle to the upper left corner
corner = -n * square_size / 2
othello.setposition(corner, corner)
# Draw the green background
othello.begin_fill()
for i in range(4):
othello.pendown()
othello.forward(square_size * n)
othello.left(90)
othello.end_fill()
# Draw the horizontal lines
for i in range(n + 1):
othello.setposition(corner, square_size * i + corner)
draw_lines(othello, n, square_size)
# Draw the vertical lines
othello.left(90)
for i in range(n + 1):
othello.setposition(square_size * i + corner, corner)
draw_lines(othello, n, square_size)
draw_initial_game_tiles(tile_positions)
def draw_lines(turt, n, square_size):
'''parameters: turt, a turtle object;
n, the number of squares, an int;
square_size, an int
returns: nothing
does: draws a line, called by draw_board function
'''
turt.pendown()
turt.forward(square_size * n)
turt.penup()
def draw_initial_game_tiles(tile_positions):
'''parameters: tile_positions, a nested list with positions and colors
for initial game tiles (format: [[point, color]...])
returns: nothing
'''
for tile in tile_positions:
draw_tile(tile[0], tile[1])
|
7a7b5ec82a43ec332c91726532c00b71ce79629e | goytia54/Epicduelz | /board.py | 2,026 | 3.890625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 6 18:15:23 2016
@author: Michael
"""
import random
import os
from prompt import *
def board():
playing_board = [[0 for y in xrange(7)] for x in range(7)] #board grid
return playing_board
def dice_roll(player):
roll = random.randint(1,6)
if roll == 1: # one character can move 3 places
max_spaces = 3
roll_string ='player {0}, {1}, you rolled a 3'.format(player.ID,player.name)
elif roll == 2: # 3 all
max_spaces = 3
roll_string ='player {0}, {1}, you rolled a 3 ALL'.format(player.ID,player.name)
elif roll == 3: # 4
max_spaces = 4
roll_string ='player {0}, {1}, you rolled a 4'.format(player.ID,player.name)
elif roll == 4: # 5
max_spaces = 5
roll_string ='player {0}, {1}, you rolled a 5'.format(player.ID,player.name)
elif roll == 5: # 2 all
max_spaces = 2
roll_string ='player {0}, {1}, you rolled a 2 ALL'.format(player.ID,player.name)
else: # 4 all
max_spaces = 4
roll_string ='player {0}, {1}, you rolled a 4 ALL'.format(player.ID,player.name)
print roll_string
return max_spaces
def place_character(p_list,playing_board):
for i in range(len(p_list)):
playing_board[p_list[i].pos[0]][p_list[i].pos[1]] = p_list[i].ID
print '{0} PLACED ON POSTION {1},{2}'.format(p_list[i].name,p_list[i].pos[0],p_list[i].pos[1])
def draw_board(playing_board,board_dim):
os.system('cls' if os.name == 'nt' else 'clear')
game_prompt()
board_str=''
bd_loop = board_dim-1
board_str+='\n '+board_dim*'---'+'\n'
for i in xrange(board_dim):
board_str += str(bd_loop-i)+'|'
for j in xrange(board_dim):
board_str+= ' ' + str(playing_board[j][bd_loop-i])+ ' '
board_str+= '\n'
board_str+=' '+board_dim*'---'+'\n '
for i in xrange(board_dim):
board_str+=' '+str(i)+' '
print board_str
|
59b707eae414f35c4de2ab3007a468507fc82323 | TomaszSkrzypinski/kurs_taps_2020 | /scripts/pętle.py | 342 | 3.546875 | 4 | liczby = [1, 2, 3, 4, 5]
for i in liczby:
print(i)
for i in range(5, 10):
print(i)
licznik = 0
while licznik < 10:
print(licznik)
licznik += 1
licznik2 = 0
while True:
print(licznik2)
licznik2 += 1
if licznik2 >= 5:
break
for x in range(20):
if x % 2 == 0:
continue
print(x) |
5957ba25a4c2d9e2e9f606d595eb4e70a82d795c | Samuel-Sorial/Python-Parser | /parsers/utils.py | 1,591 | 3.75 | 4 | import re
import argparse
import sys
import os
# Compile the pattern to improve performance
# Inspired by: https://stackoverflow.com/a/1176023/13089670
pattern = re.compile(r'(?<!^)(?=[A-Z])')
def pascal_to_snake_case(text):
text = text.strip()
return pattern.sub('_', text).lower()
def extract_args():
# Returns the command line arguments
parser = argparse.ArgumentParser(
description="Parse given files from a given format to JSON format")
parser.add_argument("format", choices=[
"csv", "xml"],
help="The format of the given file(s)")
parser.add_argument("files", nargs='+', help="File(s) to be parsed")
arguments = parser.parse_args(sys.argv[1:])
return arguments.format, arguments.files
def validate_file(file, format):
# Check if the file doesn't exist or not with the given format!!
format_len = len(format)
if not os.path.exists(file):
file_without_path = get_file_name_from_path(file)
raise FileNotFoundError(
f"error: The file {file_without_path} doesn't exist!!")
if file[-format_len:] != format:
file_without_path = get_file_name_from_path(file)
raise ValueError(
f"error: The file {file_without_path} is not a {format} file!!")
def get_file_name_without_extension(file_name):
# Returns file name without the .extension
# file.xml -> file
file_without_path = get_file_name_from_path(file_name)
return file_without_path[: file_without_path.find('.')]
def get_file_name_from_path(path):
return path[path.rfind('/') + 1:]
|
ebb71fb4a4cebe86eaba583605906284e589aa23 | WeTySun/Python-Algorithms | /InsertionSort.py | 759 | 4.40625 | 4 | # Insertion sort algorithm in the beginning compare the two first elements, compare them and sort in correct order
# Then algorithm pick up third element and compare between previous two elements. This algorithm must be write
# in very efficient way because for longer and unsorted list it can take longer to compare each other and write
# in correct order.
def insertion_sort(inputList): # define insertion sort function
for i in range(1, len(inputList)):
j = i - 1
next_element = inputList[i]
while(inputList[j] > next_element) and (j >= 0):
inputList[j+1] = inputList[j]
j = j - 1
inputList[j + 1] = next_element
l = [23,4,63,45,23,74,12,90]
insertion_sort(l)
print(l)
|
d47077d467e592c4b0e8bd8815a68a81768ccc11 | FabioFortesMachado/WebScraping | /1-web_scraping_paises.py | 2,446 | 3.515625 | 4 | '''
Nesse script eu leio as informações dos países deste website
https://scrapethissite.com/pages/simple/
Depois eu salvo no MySQL.
Aviso: coloque a sua senha para fazer a conexão com o banco de dados
e confira se o database exista também, ou crie um
'''
import requests
from bs4 import BeautifulSoup
from mysql.connector import connect, Error
import re
connection = connect(host= '127.0.0.1', port= 3306, user= 'root',
password= 'COLOQUE SUA SENHA', database= 'web_scraping',
charset='utf8')
cursor = connection.cursor(buffered=True)
cursor.execute('''
CREATE TABLE IF NOT EXISTS countries(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NULL,
capital VARCHAR(100) NULL,
population INT NULL,
area INT NULL)
''')
connection.commit()
def insertCountryIfNotExists(countryName, countryCapital, countryPopulation, countryArea):
'''
Confiro se os dados já exitem no banco de dados
Se não, os adiciono.
'''
cursor.execute('SELECT * FROM countries WHERE name = %(countryName)s AND capital = %(countryCapital)s',
{'countryName': countryName, 'countryCapital': countryCapital})
if cursor.rowcount == 0:
cursor.execute('''
INSERT INTO countries
(name, capital, population, area)
VALUES (%s, %s, %s, %s)''', (countryName, countryCapital, countryPopulation, countryArea))
connection.commit()
def getBeautifulSoupFromHTML(url):
try:
page = requests.get(url,headers={'User-Agent': 'Mozilla/5'})
except requests.exceptions.RequestException as e:
print(e.message)
raise SystemExit(e)
bs = BeautifulSoup(page.text, 'html.parser')
return bs
bs = getBeautifulSoupFromHTML('https://scrapethissite.com/pages/simple/')
# acesso as informações de cada país
countries = bs.find_all('div', {'class': re.compile(r'country$')})
for country in countries:
name = country.h3.get_text().strip()
capital = country.find('span', {'class': 'country-capital'}).get_text()
population = int(country.find('span', {'class': 'country-population'}).get_text())
area = int(float(country.find('span', {'class': 'country-area'}).get_text()))
insertCountryIfNotExists(name, capital, population, area)
cursor.execute('SELECT * FROM countries LIMIT 5')
for row in cursor.fetchall():
print(row)
cursor.execute('SELECT COUNT(id) FROM countries')
print(cursor.fetchone())
cursor.close()
connection.close()
|
2cf532b74535e65f17d5ca37f22d04cad5794369 | gonzarugil/BD | /Utils/Text.py | 1,329 | 3.6875 | 4 | import re
from bs4 import BeautifulSoup
from nltk.corpus import stopwords # Import the stop word list
from stemming.porter2 import stem
import config_vars
def textCleaner(input):
# 1. Remove HTML
# To avoid joining of words when html is cleaned we add spaces
input = input.replace("<", " <")
input = input.replace(">", "> ")
html_free_text = BeautifulSoup(input, "html.parser").get_text()
# 2. Remove non-letters
letters_only = re.sub("[^a-zA-Z]", " ", html_free_text)
# 3. Convert to lower case, split into individual words
words = letters_only.lower().split()
# 4. In Python, searching a set is much faster than searching
# a list, so convert the stop words to a set
stops = set(stopwords.words("english"))
# 5. Remove stop words
if config_vars.STEMMING:
meaningful_words = [stem(w) for w in words if not w in stops]
else:
meaningful_words = [w for w in words if not w in stops]
# 6. Stem the words to get rid of variations of the same word
# 7. Translate the list to a string separated by spaces
return meaningful_words
def parseinput(input):
input = input.lower()
if config_vars.STEMMING:
input = [stem(w) for w in ",".split(input)].join(" ")
output = [x.strip() for x in input.split(',')]
return output
|
017e84ea12d179e38e0024cfd123a54bf360904d | crazcalm/Py3.4_exploration | /Tk_practice/Basics/learn_windows_and_text.py | 4,553 | 4.25 | 4 | """
In this chapter, we were suppose to build a text editor. However, the code is
incomplete and (in some places) incorrect.
My new game plan is to write notes on this section.
"""
"""
The below code creates a scrollbar.
Issues:
-------
Because I do not know how to set the default size of the main window, the
entire application is a 1 by 1 pixel square...
Notes:
------
1. The pattern seems to place a known section object on to root (in this case,
it is 'Text(root)') and then configure/add what you want to the Text(root).
"""
from tkinter import *
def scrollBar():
root = Tk()
textpad = Text(root)
textpad.pack(expand=YES, fill=BOTH)
scroll = Scrollbar(textpad)
textpad.configure(yscrollcommand = scroll.set)
scroll.config(command=textpad.yview)
scroll.pack(side=RIGHT, fill=Y)
root.mainloop()
"""
Universal Widget Methods:
-------------------------
Intro:
------
Tkinter's Text widget comes with some handy built-in functionality to handle
common text-related functions.
The documentation of Tcl/Tk 'universal widget methods' tells us that we can
trigger events without any external stimulus using the following command:
-----> textpad.event_generate("<<Cut>>")
Below is a code snippet of how you would use it:
-----------------------------------------------------------------------------------------------------------------------
- def cut(): -
- textpad.event_generate("<<Cut>>" -
- # Then define a command callback from our exiting cut menu like -
- -
- editmenu.add_command(label="Cut", compound=LEFT, image=cuticon, accelerator="Ctrl+x", command=cut)) -
- -
-----------------------------------------------------------------------------------------------------------------------
Text Widget:
------------
Intro:
------
The Text widget offers us the ability to manipulate its content using
index, tags, and mark, which lets us target a position or placce within the
text area for manipulation.
Index:
------
Indexing helps you target a particular place within a text.
Index Formats:
-------------
x.y : The yth character on line x
@x.y : the character that covers the x.y coordinate within the text's window.
end : The end of the text.
mark : The character after a named mark.
tag.first : The first character in the text that has been tagged with a given tag.
tag.last : The last character in the text that has been tagged with a given tag.
window.name : The position of the embedded window whose name is widowname.
imagename : The position of the embedded image whose name is imageName.
INSERT : The posistion of the insertion cursor.
CURRENT : The position of the character closet to the mouse pointer.
selection : This corresponds to the current selection. The constants SEL_FIRST,
(SEL_FIRST, : and SEL_LAST refer to the start position and the end position in the
SEL_LAST) : selection. Tkinter raises a TclError exception if there is no selection
Note:
-----
Indexes are often used as arguments for other functions.
EX:
---
text.delete(1.0, END): This means that you can delete from line 1, column 0 up till the end.
"""
"""
Tkinter four types of windows:
------------------------------
Main Toplevel window :
----------------------
These are the ones that we have contructed so far.
Child Toplevel window :
-----------------------
These are the ones that are independent of the root. The child Toplevel behaves
independently of its root but it gets destroyed if its parent is destroyed.
Transient TopLevel window:
--------------------------
This always appears on top of its parent. This wondow is hidden if the parent
is minimized and it is destroyed of the parent is destroyed.
Undecorated TopLevel window:
----------------------------
A Toplevel window is undecorated if it does not have a window manager.
An undecorated window cannot be resized or moved.
"""
if __name__ == "__main__":
scrollBar()
|
32366e0bca332c49b9607adf0d26a10e3bf77854 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2219/60750/257186.py | 337 | 3.546875 | 4 | import math
def solve():
num = int(input())
i = 1
while True:
tmp = num - i *i
if tmp <0:
print(False)
return
else:
if tmp - math.sqrt(tmp) * math.sqrt(tmp) == 0:
print(True)
return
else:
i += 1
solve()
|
f1fb18a9f520d798d799bcdeffe14dd2b8e2890f | Wb-Alpha/PythonStudy | /Chapter15/knowledge.py | 914 | 3.671875 | 4 | #Python内置了SQLite3,可以直接使用import导入SQLite3模块
import sqlite3
'''
#连接到数据库文件'mrsoft.db'没有文件会自动创建
conn = sqlite3.connect('mrsoft.db')
#创建一个curosr(游标)
cursor = conn.cursor()
#SQL语句
cursor.execute('CREATE TABLE user (id int(10) primary key, name varchar (20)')
#关闭游标
cursor.close()
conn.close()
#本段代码仅能执行一次,若重复执行则因为user表已经存在而报错
'''
#操控SQLite
#插入数据
conn = sqlite3.connect('mrsoft.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO user (id, name ) values ("1", "MRSOFT") ')
cursor.execute('INSERT INTO user (id, name) values ("2", "Andy")')
cursor.execute('SELECT * FROM user')
#查询一条数据
result = cursor.fetchone()
#查询多条数据
result1 = cursor.fetchmany(2)
print(result1)
#获取所有记录
result3 = cursor.fetchall()
print(result3)
|
6bc48b7fa38268f4cb4471dc91cb6aff670c70d9 | sidd315/BFS-2.1 | /employeeImportanceDFS.py | 914 | 3.9375 | 4 | """
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def __init__(self):
self.dataStore = dict()
self.result = 0
def getImportance(self, employees: List['Employee'], id: int) -> int:
if not employees:
return None
for e in employees:
self.dataStore[e.id] = e
self.dfs(id)
return self.result
def dfs(self, id: int):
#base
#logic
curr = self.dataStore[id]
self.result+=curr.importance
for value in curr.subordinates:
self.dfs(value)
# recursive dfs solution.
# time and space complexity is O(n)
|
81a30674bc85c80753876cfaa94bb8d0a61d9077 | timothyshort/data_analysis | /03_data_analysis/03-data_analysis-process/21_visuals_quiz.py | 877 | 3.984375 | 4 |
# coding: utf-8
# # Exploring Data with Visuals Quiz
# Use the space below to explore `powerplant_data_edited.csv` to answer the quiz questions below.
# In[4]:
# imports and load data
import pandas as pd
get_ipython().magic('matplotlib inline')
df = pd.read_csv('powerplant_data_edited.csv')
df.head()
# In[7]:
# plot relationship between temperature and electrical output
df.plot(x='Atmospheric Temperature in C', y='Power Output', kind='scatter');
# In[9]:
# plot distribution of humidity
df.hist('Relative Humidity');
# In[32]:
# plot box plots for each variable
df['Atmospheric Temperature in C'].plot(kind='box');
# In[33]:
df['Exhaust Vacuum Speed'].plot(kind='box');
# In[34]:
df['Atmospheric Pressure'].plot(kind='box');
# In[35]:
df['Relative Humidity'].plot(kind='box');
# In[36]:
df['Power Output'].plot(kind='box');
# In[ ]:
|
a13d878c144a08f1ae62729efdac0b7c74a87afb | catomania/Random-late-night-time-wasters | /ctci/Chapter-1/question_8.py | 932 | 4.40625 | 4 | #Assume you have a method isSubstring which checks if one word is a
#substring of another. Given two strings, s1 and s2, write code to check if s2 is
#a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle" is a rotation of "erbottlewat").
def rotatedStringHasSubstring(s1, s2):
# make sure s1 and s2 are of the same length
if len(s1) != len(s2):
return False
else:
# rotation = moving letters from front to back but not mixing up letters
# make an s1s1 string
double_s1 = s1 + s1
# call isSubstring and return the results
return isSubstring(double_s1, s2)
def isSubstring(s1, s2):
# is s2 a substring s1
# http://www.tutorialspoint.com/python/string_find.htm
# returns either True or False
return s1.find(s2) > -1
#testing
if rotatedStringHasSubstring("waterbottle", "erbottlewat"):
print "Passed test 1!"
if not rotatedStringHasSubstring("catnaps", "pinkys"):
print "Passed test 2!"
|
0b76a68a12c43a86f32794f6abfa613bfbbef677 | shrutisaxena0617/Data_Structures_and_Algorithms | /all/longestUniqueSubstring.py | 418 | 3.78125 | 4 | def longestUniqueSubstring(mystr):
if mystr:
i = 0
j = 0
max_len = 0
myset = set()
while i < len(mystr) and j < len(mystr):
if ord(mystr[j]) not in myset:
myset.add(ord(mystr[j]))
j += 1
max_len = max(max_len, j-i)
else:
myset.remove(ord(mystr[i]))
i+=1
return max_len
print(longestUniqueSubstring('asdhsflsdhfd'))
|
3510b76b69ee2c462837609d79f1ea30976723ee | TheDycik/algPy | /les2/les4.py | 1,432 | 3.71875 | 4 | # 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив
# со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5 (помните, что
# индексация начинается с нуля), т. к. именно в этих позициях первого массива стоят четные числа.
from random import random
import timeit
import cProfile
def chetInd(n):
x = [0]*n
ch = []
for i in range(n):
x[i] = int(random() * 10) + 10
if x[i] % 2 == 0:
ch.append(i)
return x, ch
# "les_4.chetInd(10)"
# 1000 loops, best of 5: 3.08 usec per loop
# "les_4.chetInd(100)"
# 1000 loops, best of 5: 26.8 usec per loop
# "les_4.chetInd(1000)"
# 1000 loops, best of 5: 272 usec per loop
cProfile.run('chetInd(1000)')
# 1 0.000 0.000 0.000 0.000 les4.py:10(chetInd) 10
# 2 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
# 1 0.000 0.000 0.000 0.000 les4.py:10(chetInd) 100
# 54 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
#1 0.001 0.001 0.001 0.001 les4.py:10(chetInd) 1000
# 507 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} |
1f3622410bc78a38c83ec9eec32eee2ee5b09d60 | deepakpm92/Data-Structures-and-Algorithms-in-python | /recursive_binarysearch.py | 675 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 11:27:15 2019
@author: d.padmanabhan.menon
"""
# Recursive Binary Search
def binarySearch (arr, low, high, element):
if high >= low:
mid = int(low + (high - low)/2)
if arr[mid] == element:
return mid
elif arr[mid] > element:
return binarySearch(arr, low, mid-1, element)
else:
return binarySearch(arr, mid + 1, high, element)
else:
return -1
arr = [ 2, 3, 4, 10, 40]
element = 10
low = 0
high = len(arr)-1
found = binarySearch(arr, low, high, element)
if found != -1:
print("Element is present at index {}".format(found))
else:
print("Element is not present in array")
|
5b440d20da93d0cd4c212da7271d2558a635cf54 | 4WHITT04/COM411 | /visual/plots/simple.py | 234 | 3.515625 | 4 | import matplotlib.pyplot as plt
def display (x, y):
plt.plot(x, y)
plt.show()
def run ():
print("displaying data in readable format....")
xVal = [1, 2, 3, 4, 5]
yVal = [1, 4, 9, 16, 25]
display(xVal, yVal)
run() |
4bbca3fcd2f13517a68056cbb7496be1f248d3fe | srinaveendesu/Programs | /leetcode/day6.py | 1,015 | 3.703125 | 4 | # https://leetcode.com/problems/add-binary/submissions/
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
#https://leetcode.com/problems/merge-sorted-array/submissions/
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
del nums1[m:]
del nums2[n:]
i = 0
j = 0
while i < m and j < n:
if nums1[i] < nums2[j]:
i += 1
else:
nums1.insert(i, nums2[j])
j += 1
i += 1
m += 1
if i == m and j < n:
while j < n:
if bool(nums1) and nums1[i - 1] <= nums2[j]:
nums1[i + 1:] = nums2[j:]
break
else:
nums1.insert(i, nums2[j])
i += 1
j += 1
|
359c7a21f8da36c6321cda40afc13cc8aa00b843 | sabiul/python-practice | /looop.py | 1,506 | 3.828125 | 4 | __author__ = 'Rashed'
# n = 1
# while n <= 10:
# print(n)
# n = n+1
# n = 1
# while n <= 10:
# print(n)
# n = n+1
# a = {'name' : 'MD. Maksudur Rahman Khan', 'nickname' : 'Maateen', 'email' : 'maateen@outlook.com', 'phone' : '01711223344'}
#
# print(a)
# print(type(a))
# for item in a:
# print(item)
#
# range(5, 20, 2)
# l = list(range(5, 20, 2))
# print(l)
# for number in range(1, 11):
# if number == 5:
# break
# print(number)
# for item in range(40,403):
# print(item)
#
# a = ['onion', 'potato', 'ginger', 'cucumber']
# for item in a:
# print(item)
# a = [3,45,66,4543,43,'dsdsd']
# for item in a:
# print(item)
# i = 1
# while i > 0:
# i += 1
# print(i)
# ইউজার যেকোন একটা পূর্ণসংখ্যা ইনপুট দেবে। আর ঐ পূর্ণসংখ্যার নামতা আউটপুট হিসাবে দেখাতে হবে।
#
# print('Please, input the number:')
# number = int(input())
# count = 1
#
# while count <= 10:
# print(number, 'x', count, '=', number*count)
# count += 1
# print('Please, input the number:')
# number = int(input())
# temp = number
#
# while number > 0:
# count = temp
# while count > 0:
# print('*', end='')
# count -= 1
# print()
# number -= 1
my_list = [i**2 for i in range(20) if i % 2 == 0]
print(my_list)
a_list = ['Maateen', 'Khan', 'Maksudur', 'a', 'b', 'c']
my_set = {i for i in a_list if len(i) > 1}
print(my_set) |
39bd032d717237d92b5f92384fbd5811d92fb0e9 | ryu-0406/study-python | /basic/pythonweb/tuple/pythonweb07-01-07.py | 579 | 4.46875 | 4 | # coding:utf-8
# 指定した値と同じ値を持つ要素が含まれているかの確認
mytuple = ("A", "B", "C", "D", "E")
print("B" in mytuple)
print("D" in mytuple)
print("G" in mytuple)
# 指定の値と同じ要素が何個タプルに含まれているかの確認
mytuple = ("A", "B", "A", "A", "C")
print(mytuple.count("A"))
print(mytuple.count("B"))
print(mytuple.count("D"))
# 指定の値と同じ値を持つ要素のインデックスを取得
mytuple = ("A", "B", "A", "A", "C")
print(mytuple.index("A"))
print(mytuple.index("B"))
print(mytuple.index("C")) |
9c76fb3e690c309586465dac8f63c9818c80ae25 | Divyansh-03/PythoN_WorK | /NewNumber.py | 530 | 4.3125 | 4 | ''' If a five-digit number is input through the keyboard, write a
program to print a new number by adding one to each of its
digits. For example if the number that is input is 12391 then
the output should be displayed as 23402. '''
n = int(input( " Enter a 5-digit number "))
temp = n
d1=n%10
n//=10
d2=n%10
n//=10
d3=n%10
n//=10
d4=n%10
d5=n//10
# New digits
d1=(d1+1) %10
d2=(d2+1) %10
d3=(d3+1) %10
d4=(d4+1) %10
d5=(d5+1) %10
print(" The new number formed by " + str(temp) + " is " + str(d5)+str(d4)+str(d3)+str(d2)+str(d1)) |
da091469fada726200ea26e1f63d45a5303239b9 | devAmoghS/Algorithms-Princeton-University | /quick_find_eager.py | 511 | 3.546875 | 4 | # Eager implementation of the Quick Find algorithm
# Problem: Dynamic Connectivity
# ** Peformance
# 1. is_connected: takes constant time - O(1)
# 2. union: takes linear time - O(N)
class QuickFindUF:
def __init__(self, arr, size):
self.arr = [i for i in range(0, size)]
def is_connected(self, p, q):
array = self.arr
return array[p] == array[q]
def union(self, p, q):
array = self.arr
p_id = array[p]
q_id = array[q]
for i in array:
if i == p_id:
i = q_id
|
d5a547319776a8616cae6e58ca64812ba8dd8205 | magnuskonrad98/max_int | /FORRIT/python_verkefni/leika/circumference.py | 214 | 4.375 | 4 | import math
my_radius = float(input("Enter the radius: "))
circumference = 2 * math.pi * my_radius
area = math.pi * ( my_radius ** 2 )
print("Your circumference is:", circumference, "and your area is: ", area)
|
50e14926fce55d9f86860cc109e3f6f424fe1bbb | Seun1609/Python-Training | /Thursday/class_sample.py | 1,011 | 3.78125 | 4 | class Dog:
# It should have the properties name, color, weight
# It should have the methods bark, eat, sleep
def __init__(self, n, c, w):
self.name = n
self.color = c
self.weight = w
def bark(self):
print("Woof!")
def eat(self):
print(self.name + " is eating...")
def sleep(self):
print(self.name + " is sleeping...")
bingo = Dog("Bingo", "yellow", 10)
spike = Dog("Spike", "white", 8)
print("Bingo's details: ")
print(bingo.name)
print(bingo.color)
print(bingo.weight)
print("\nSpike's details: ")
print(spike.name)
print(spike.color)
print(spike.weight)
print("\nReassigning Spike's weight to 12...")
spike.weight = 12
print("\nSpike's details: ")
print(spike.name)
print(spike.color)
print(spike.weight)
print("\nCreating a new property...")
spike.breed = "Some random breed"
print(spike.breed)
print("\nMake Bingo bark...")
bingo.bark()
print("\nMake Bingo eat...")
bingo.eat()
print("\nMake Spike sleep...")
spike.sleep()
|
05fbaab4600359a57227dd8fa959af5d3c780df0 | jfriend08/LeetCode | /CombinationSumII.py | 1,240 | 3.625 | 4 | '''
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
'''
class Solution(object):
def combineSumHandler (self, candidates, target):
result = []
if not candidates or candidates[0] > target:
return []
if candidates[0] == target:
return [[candidates[0]]]
withme = self.combineSumHandler(candidates, target-candidates[0])
result = [ [candidates[0]] + elm for elm in withme ]
withoutme = self.combineSumHandler(candidates[1:], target)
result.extend(withoutme)
return result
def combinationSum(self, candidates, target):
return self.combineSumHandler(sorted(set(candidates)), target)
sol = Solution()
print sol.combinationSum([2,3,6,7], 7)
print sol.combinationSum([1, 2], 3)
print sol.combinationSum([1], 2) |
591f431083f1ef79188aaf417e9b6a2707f857b2 | ramnathj/CodeArena | /PythonCodes/Ex8.py | 322 | 4 | 4 | '''
Sort strings in lexicographic order
'''
class Sorting(object):
def __init__(self,lst):
self.lst=lst
def sortStrings(self):
self.lst = sorted(self.lst)
def printStrings(self):
print ','.join(self.lst)
s = raw_input()
S = Sorting(s.split(','))
S.sortStrings()
S.printStrings()
|
6e07c33d80e198c58d98e2102115ffb7a41834d0 | rafaelperazzo/programacao-web | /moodledata/vpl_data/132/usersdata/189/40905/submittedfiles/al14.py | 203 | 3.9375 | 4 | # -*- coding: utf-8 -*-
n=int(input('digite o numero de pessoas:'))
soma=0
cont=1
for i in range(1,n+1,1):
i=int(input('digite a idade:')
soma=soma+i
media=(soma/n)
print('%.2f' %media)
|
48a547d778fd39776de9af748974e70e039a7243 | MikhailErofeev/a3200-2015-algs | /classic-algs/lab2/Morozov/test.py | 335 | 3.765625 | 4 | __author__ = 'vks'
def sieve(n):
primes = [True for i in range(n + 1)]
primes[0] = False
primes[1] = False
i = 2
while (i ** 2 <= n):
if (primes[i] == True):
for j in range(i * i, n + 1, i):
primes[j] = False
i += 1
return primes
n = int(input())
print(sieve(n))
|
afbc644cdcd7c8ecfae5685e84d7230b2fe3818d | nikhilp93/cmpe287 | /arraysort.py | 1,107 | 4.25 | 4 | # Python program to merge two sorted arrays
# Merge A[0..n1-1] and
# B[0..n2-1] into
# C[0..n1+n2-1]
def mergeArrays(A, B, n1, n2):
C = [None] * (n1 + n2)
i = 0
j = 0
k = 0
# Traverse both array
while i < n1 and j < n2:
# Check if current element of first array is smaller than current element of second array.
#If yes, store first array element and increment first array index.
# Otherwise do same with second array
if A[i] < B[j]:
C[k] = A[i]
k = k + 1
i = i + 1
else:
C[k] = B[j]
k = k + 1
j = j + 1
# Store remaining elements of first array
while i < n1:
C[k] = A[i];
k = k + 1
i = i + 1
# Store remaining elements of second array
while j < n2:
C[k] = B[j];
k = k + 1
j = j + 1
print("Array after merging")
for i in range(n1 + n2):
print(str(C[i]), end = " ")
# Driver code
A = [1, 2, 7, 11]
n1 = len(A)
B = [3,7,13,16,29]
n2 = len(B)
mergeArrays(A, B, n1, n2); |
f9fa8435852de5b4e42a63241bc5b251bae1663b | EduardaValentim/programacao-orientada-a-objetos | /listas/lista-de-exercicio-04/questao1.py | 1,450 | 3.515625 | 4 | # Variáveis para a item 1
a = []
a_sem_ponto = []
item1 = []
# Variáveis para a item 2
item2 = []
# Variáveis para a item 3
c = []
c_sem_ponto = []
item3 = []
# Variáveis para a item 4
d = []
d_sem_ponto = []
item4 = []
# Leitura do arquivo
arquivo = open('amazon.csv', 'r')
for linha in arquivo:
dados = linha.strip('\n').split(',')
# Manipulação de dados
if dados[0] == '2015' and dados[1] == '"Acre"':
a = dados[3]
str(a)
a_sem_ponto = a.replace('.', '')
a_inteiro = int(a_sem_ponto)
item1.append(a_inteiro)
elif dados[0] == '2014' and dados[1] == '"Ceara"':
passando_para_int = int(dados[3])
item2.append(passando_para_int)
elif dados[1] == '"Amazonas"':
c = dados[3]
str(c)
c_sem_ponto = c.replace('.', '')
c_inteiro = int(c_sem_ponto)
item3.append(c_inteiro)
if dados[0] == ('2010' and '2011' and '2012' and '2013' and '2014' and '2015' and '2016' and '2017') and dados[1] == '"Mato Grosso"':
d = dados[3]
str(d)
d_sem_ponto = d.replace('.', '')
d_inteiro = int(d_sem_ponto)
item4.append(d_inteiro)
# exibição dos dados manipulados
print('Em 2015 ocorreram {} queimadas no Estado do Acre.'.format(sum(item1)))
print('Em 2014 ocorreram {} queimadas no Estado do Ceará.'.format(sum(item2)))
print('No Estado do Amazonas ocorreram {} queimadas, de 1998 a 2017.'.format(sum(item3)))
print('No Estado do Mato Grosso ocorreram {} queimadas, de 2010 a 2017.'.format(sum(item4)))
arquivo.close() |
fdf6dd9972fea07abd24ff3b085e867efd16ba8a | xandhiller/learningPython | /picnicItems.py | 466 | 4 | 4 | # Is testing the .center(), .rjust() and .ljust() functions.
def printDictionary(d, lWidth, rWidth):
print('PICNIC ITEMS'.center(lWidth + rWidth, '-'))
for k,v in d.items():
print(("k is: " + k).center(lWidth + rWidth, ' '))
print(("v is: " + str(v)).center(lWidth + rWidth, ' '))
# Must cast v as string because value = int
return 0
picnicItems = {'sandwiches':5, 'apples':3, 'bananas':7}
printDictionary(picnicItems, 20, 20)
|
0f43c1f32ca27f8d917815f1638f6b06a077ab4c | mmeadx/python-challenge | /PyPoll/main.py | 3,355 | 3.640625 | 4 | #PyPoll - Vote Counting
#Thanks to Allan Hunt for the help!
#Import add ons
import os
import csv
#Define path to collect data from election_data.csv
election_data = os.path.join("Resources", "election_data.csv")
#Define Values
TotalVotes = 0
#Create Lists & Dictionaries
candidate_votes = {} #This will hold unique candidates and their vote count
percentages = {} #This will hold unique candidates and the percentages
percentages_compare = [] #This is a list of the percentages to compare for winner
compare_lib = {} #Created dictionary to get candidate as output value
winning_candidate = "This will be replaced by the winning candidate" #placeholder value
#read budget_data.csv
with open(election_data, 'r') as csvfile:
#split data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
#print(f'CSV Header: {header}') # check to see if it can read
#read through csv file
for line in csvreader:
# Count the number of votes
TotalVotes = TotalVotes + 1 #Finding total number of votes
#Find unique candidates and put them into a dictionary while adding number of votes
if line[2] not in candidate_votes:
#If unique, add them to list with a starting vote value of 1
candidate_votes[line[2]] = 1
else:
#If already in list, add a vote to their count
candidate_votes[line[2]] += 1
#print(candidate_votes) #test to see if counter worked
#-----Find percentages for each candidate-----
for candidate in candidate_votes:
percent_vote = candidate_votes[candidate] / TotalVotes #divide candidate vote count by total votes
percent_vote_changed = "{:.3%}".format(percent_vote) #changing format of percentage
#Add candidate percentage to library to be referenced
percentages[candidate] = percent_vote_changed
#Make a list and library to compare percentages to find winner
percentages_compare.append(percent_vote_changed) #adding percentages to list
compare_lib[percent_vote_changed] = candidate #reversing order of candidate for output
#-----Find winner-----
winning_candidate = compare_lib[max(percentages_compare)]
#print(winning_candidate) # Test print winning candidate
#test print all lists & dictionaries
# print(candidate_votes)
# print(percentages)
# print(percentages_compare)
# print(compare_lib)
#-----Print results to terminal-----
print('') #spacing away from command line
print('Election Results')
print('-------------------------')
print(f'Total Votes: {TotalVotes}')
print('-------------------------')
for candidate in candidate_votes: #Loop through candidate_votes to get individual results
print(f'{candidate}: {percentages[candidate]} ({candidate_votes[candidate]})')
print('-------------------------')
print(f'Winner: {winning_candidate}')
print('-------------------------')
#-----Print results to txt file-----
f = open("analysis/poll_analysis.txt", 'w')
f.write('Election Results\n')
f.write('-------------------------\n')
f.write(f'Total Votes: {TotalVotes}\n')
f.write('-------------------------\n')
for candidate in candidate_votes:
f.write(f'{candidate}: {percentages[candidate]} ({candidate_votes[candidate]})\n')
f.write('-------------------------\n')
f.write(f'Winner: {winning_candidate}\n')
f.write('-------------------------\n')
f.close()
|
76c2b53506eecd8cba094bbc9a023817b3b7b72c | ehivan24/learnigPython | /Animal.py | 2,077 | 3.9375 | 4 | '''
Created on Jan 12, 2015
@author: edwingsantos
'''
class Animal(object):
__name = ""
__height = 0
__weight = 0
__sound = 0
def setName(self, name): #setter
self.__name = name
def getName(self): #getter
return self.__name
def setWeight(self, weight): #setter
self.__weight = weight
def getWeight(self): #getter
return self.__weight
def setHeight(self, height): #setter
self.__height = height
def getHeight(self): #getter
return self.__height
def setSound(self, sound): #setter
self.__sound = sound
def getSound(self): #getter
return self.__sound
def getType(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kgs and say {}".format(self.__name, self.__height,self.__weight,self.__sound)
def __init__(self, name, height, weight, sound):
'''
Constructor
'''
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
cat = Animal("Wiskers", 33, 20, "Meow")
print cat.toString()
class Dog(Animal):
__owner = None
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def setOwner(self, owner):
self.__owner = owner
def getOwner(self):
return self.__owner
def getType(self):
print("Dog")
def toString(self):
return "{} is {} cm tall and {} kgs and say {} his owner {} ".format(self.__name, self.__height, self.__weight, self.__sound, self.__owner)
spot = Dog("spot", 53, 27, "ruff", "Amy")
print "Height: " , spot.getHeight()
print "Name: " , spot.getName()
print "Owner: ", spot.getOwner()
print "Weight: ", spot.getWeight()
print "Sound: ", spot.getSound()
print "Type: ", spot.getType() |
d09cd5636e518cf5aa3be4523ff05c1648cf35fd | Symbii/python_Oj | /keyboard_row.py | 968 | 3.734375 | 4 | #!/usr/bin/env python
import string
import sys
import traceback
def findwords(list):
res=[]
flag=1
dict={'q':1,'w':1,'e':1,'r':1,'t':1,'y':1,'u':1,'i':1,'o':1,
'a':2,'s':2,'d':2,'f':2,'g':2,'h':2,'j':2,'k':2,'l':2,
'z':3,'x':3,'c':3,'v':3,'b':3,'n':3,'m':3}
for k in list:
temp = k.lower()
for i,j in enumerate(temp):
if len(temp) != 1:
try:
if i<len(temp)-1 and dict[temp[i]] != dict[temp[i+1]]:
flag=0
break
elif i<len(temp)-1 and dict[temp[i]] == dict[temp[i+1]]:
flag=1
except:
traceback.print_exc()
return
else:
flag = 1
if flag==1:
res.append(k)
return res
if __name__ == '__main__':
list = sys.argv
list.pop(0)
res = findwords(list)
print (res)
|
81f7b858db7018c07d6f31e2506327b7a9b95872 | tsevans/AdventOfCode2020 | /day_2/puzzle_1.py | 1,378 | 4.3125 | 4 | # Count the number of invalid passwords based on rules in the input.txt 'database'.
def load_input():
"""
Load the contents of input.txt into a list.
Returns:
([str]): Lines of input.txt as a list of strings.
"""
with open("input.txt", "r") as infile:
lines = [line.rstrip() for line in infile]
return lines
def split_line(line):
"""
Split up a single line into individual components.
Args:
line (str): Single line containing policy and password.
Returns:
(str, str, str, str): Min, max, character, and password.
"""
policy, char, password = line.split()
minimum, maximum = policy.split("-")
char = char.rstrip(":")
return minimum, maximum, char, password
def count_invalid_passwords(lines):
"""
Count the number of invalid passwords in the database.
Args:
lines ([str]): Lines of input.txt database file as a list.
Returns:
(int): Number of invalid passwords.
"""
invalid_count = 0
for line in lines:
lower, upper, char, password = split_line(line)
occurrences = password.count(char)
if occurrences < int(lower) or occurrences > int(upper):
invalid_count += 1
return invalid_count
if __name__ == "__main__":
lines = load_input()
num_valid = len(lines) - count_invalid_passwords(lines)
print("%s out of %s passwords in this database are valid." % (num_valid, len(lines)))
|
a5cfa8c6e56d2508e36e2465801382f63219cec7 | ninjaboynaru/my-python-demo | /leetcode/11.py | 611 | 3.625 | 4 | from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
areaMax = (j-i) * min(height[i], height[j])
while (i < j):
print("i: {}, j: {}, areaMax: {}".format(i, j, areaMax))
if height[i] < height[j]:
i = i+1
else:
j = j - 1
areaNew = (j-i) * min(height[i], height[j])
print(areaNew)
areaMax = max(areaNew, areaMax)
return areaMax
if __name__ == "__main__":
print(Solution().maxArea([1,8,6,2,5,4,8,3,7]))
|
5fa01e89ffd56a15ae1a26d396740141c6238818 | Shawn-H-Wang/Python-Tutorial | /7.5.py | 954 | 3.546875 | 4 | d = {}
while True:
cho = input("请输入选择功能:1-添加 2-查询 3-退出:")
if cho is "1":
f = open("dictionary.txt","w")
word = input("请输入添加的单词:")
mean = input("请输入添加单词的意思:")
lw = [word , mean]
f.writelines(lw)
elif cho is "2":
f = open("dictionary.txt","r")
ls = []
for line in f:
line = line.replace("\n","")
ls.append(line.split(":"))
f.close()
elif cho is "3":
print("退出程序!")
break
else:
print("输入错误,请重新输入!")
continue
def main():
pro = input("请输入选择功能:1-添加 2-查询 3-退出:")
while True:
if pro is "1":
add()
elif pro is "2":
serch()
elif pro is "3":
esc()
break
else:
|
9665582f0149cb39bf01e546692a2356e79d0115 | stevenwongso/Python_Fundamental_DataScience | /7 Beautiful Soup/0_basic.py | 554 | 3.640625 | 4 | ### web scraping: pip install beautifulsoup4
from bs4 import BeautifulSoup
### from html text:
soup = BeautifulSoup('<p>Some<b>bad<i>HTML', 'html.parser')
print(soup)
### from html file:
soup = BeautifulSoup(open('0.html', 'r'), 'html.parser')
print(soup)
### from website:
import requests
r = requests.get("https://ezalin.com")
soup = BeautifulSoup(r.content, 'html.parser')
print(soup)
### from website using urllib
import urllib.request
url = urllib.request.urlopen('https://ezalin.com').read()
soup = BeautifulSoup(url, 'html.parser')
print(soup) |
d161602381f50dd9976fc299570c516560582811 | Reed1114/2020_2d | /grafiske_brugerflader/eks1/knap.py | 880 | 3.515625 | 4 | import tkinter as tk
class KnapProgram1(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
#Her oprettes en knap. Med argumentet "command" vælges hvilken
#funktion, der skal udføres når man klikker på knappen.
self.button1 = tk.Button(self, text = 'OK', command = self.knap1_action)
#For at placere knappen på vores frame kaldes funktionen "pack"
self.button1.pack(side=tk.TOP)
#Og en label, så vi kan lave noget output når man klikker på knappen
self.label1 = tk.Label(self, text = 'En label til tekst')
self.label1.pack(side=tk.TOP)
#Til sidst skal vores frame også "packes"
self.pack()
def knap1_action(self):
self.label1.configure(text = "Du har klikket på knappen!")
root = tk.Tk()
prg = KnapProgram1()
prg.master.title('Eksempel 1')
prg.mainloop()
|
b73951e73296ce1b9b681a150d929549748a503e | sanbaideng/Python-SQLite | /SqliteHelper.py | 1,222 | 3.96875 | 4 | import sqlite3
class SqliteHelper:
def __init__(self,name=None):
self.conn = None
self.cursor = None
if name:
self.open(name)
def open(self, name):
try:
self.conn = sqlite3.connect(name)
self.cursor = self.conn.cursor()
print(sqlite3.version)
except sqlite3.Error as e:
print("Failed connecting to database...")
def create_table(self):
c = self.cursor
c.execute("""CREATE TABLE users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
year INTEGER,
admin INTEGER
)""")
def edit(self,query):#INSERT & UPDATE
c = self.cursor
c.execute(query)
self.conn.commit()
def select(self,query):#SELECT
c = self.cursor
c.execute(query)
return c.fetchall()
test = SqliteHelper("test.db")
#test.create_table()
#test.edit("INSERT INTO users (name,year,admin) VALUES ('john',1992,0) ")
test.edit("UPDATE users SET name='jack' WHERE name = 'john'")
print(test.select("SELECT * FROM users"))
|
692057566b2620f899797b0f3e6e3098d54ded51 | Bruceaniing/environment | /matlib.py | 1,826 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true")
df.head()
top_10 = (df.groupby('name')['ext price', 'quantity'].agg({'ext price': 'sum', 'quantity': 'count'})
.sort_values(by='ext price', ascending=False))[:10].reset_index()
top_10.rename(columns={'name': 'Name', 'ext price': 'Sales', 'quantity': 'Purchases'}, inplace=True)
top_10
plt.style.use('ggplot')
top_10.plot(kind='barh', y="Sales", x="Name");
fig, ax = plt.subplots() # 向plt.subplots() 添加了一个额外的调用,并将ax传递给绘图函数
top_10.plot(kind='barh', y="Sales", x="Name", ax=ax);
fig, ax = plt.subplots()
top_10.plot(kind='barh', y="Sales", x="Name", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set(title= '2014 Revenue' , xlabel= 'Total Revenue' , ylabel= 'Customer'); # 快捷键,同时设置标题和两个标签
fig, ax = plt.subplots(figsize=(5,6)) # 通过figsize()修改图窗大小
top_10.plot(kind='barh', y="Sales", x="Name", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set(title='2014 Revenue', xlabel='Total Revenue', ylabel='Customer') # 快捷键,同时设置标题和两个标签
ax.legend().set_visible(False);
# def currency(x, pos):
# if x >= 1000000:
# return ${:1.1f}M .format(x*1e-6)
# return ${:1.1f}K .format(x*1e-3)
# fig, ax = plt.subplots()
#
# top_10.plot(kind= barh , y="Sales", x="Name", ax=ax)
#
# ax.set_xlim([-10000, 140000])
#
# ax.set(title= '2014 Revenue' , xlabel= 'Total Revenue' , ylabel= 'Customer' )
#
# formatter = FuncFormatter(currency)
#
# ax.xaxis.set_major_formatter(formatter)
#
# ax.legend().set_visible(False)
|
35e037f6d3130e8bbd7f3d445c8873c43725769a | alvaroabascar/algorithmic_toolbox | /challenges/week1/2_maximum_pairwise_product/max_pairwise_product.py | 776 | 3.671875 | 4 | import numpy as np
def max_pairwise_product(numbers):
idx_max1 = -1
idx_max2 = -1
for i, num in enumerate(numbers):
if idx_max1 == -1 or num > numbers[idx_max1]:
idx_max2 = idx_max1
idx_max1 = i
elif idx_max2 == -1 or num > numbers[idx_max2]:
idx_max2 = i
return numbers[idx_max1]*numbers[idx_max2]
def main():
n = int(input())
nums = list(map(int, input().split()[:n]))
print(max_pairwise_product(nums))
def stress():
iters = 1000000
max_n = 20;
max_num = 1000;
for i in range(iters):
n = np.random.randint(max_n - 2) + 2
nums = np.random.randint(max_num, size=(1, n))
max_pairwise_product(nums)
if __name__ == '__main__':
stress()
|
3764c5838770336bf5ed906ac7762bcab5f574c9 | pavelnyaga/MITx_6 | /Week-1.Python Basics/set1.py | 1,158 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 8 15:58:19 2017
@author: Pavel
"""
#Assume s is a string of lower case characters.
#
#Write a program that counts up the number of vowels contained in the string s.
#Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
#For example, if s = 'azcbobobegghakl', your program should print:
# Number of vowels: 5
s = 'azcbobobegghakl'
#program 1
#count = 0
#
#for char in s:
# if char in ['a', 'e', 'i', 'o', 'u']:
# count += 1
#
#print(count)
#program 2
#count = 0
#
#for k in range(len(s)):
# if s[k:k+3] == 'bob':
# count += 1
#
#print(count)
# program 3
#ab = "abcdefghijklmnopqrstuvwxyz"
#s = 'abcbcd'
#s = 'zyxwvutsrqponmlkjihgfedcba'
soutmax = ""
scur = ""
countmax = 0
countcur = 0
for i in range(len(s)):
countcur = 1
scur = s[i]
for k in range(i,len(s)-1):
if s[k] <= s[k+1]:
countcur += 1
scur = scur + s[k+1]
else:
break
if countcur > countmax:
countmax = countcur
soutmax = scur
print("Longest substring in alphabetical order is: ", soutmax)
|
4f5208b3dab69892a4dee695774ec08fdb112c19 | subedisapana/python-fundamentals | /Python Modules & Packages/list_comprehension.py | 642 | 3.921875 | 4 | # square of list and storing in another list
l= [100,200,300,400,500,600]
l1=[]
for i in l:
l1.append(i*i)
print(l1)
#Similarly using list comprehension
l2= [100,200,300,400,500,600]
l3=[value*value for value in l2]
print(l3)
#Sum of all the elements
l4 = [10,20,30,40,50,60]
l5 = []
sum=0
for v in l4:
sum=sum+v
l5.append(sum)
print(l5)
# only even number
l6=[10,20,30,40,50,60,65,70,85]
l7=[val for val in l6 if val%2 == 0]
print(l7)
#length
l11=['abc', 'abcd', 'abcde', 'zzzz']
l12= [len(j) for j in l11]
print(l12)
#nested loop
l13 = [(value1,value2) for value1 in range(1,5) for value2 in range(100,103)]
print(l13)
|
7a684770293655b93699b2ec08d0c6c77113449a | hardikahalpara/Translator-using-Python | /Translator.py | 627 | 3.71875 | 4 | import tkinter as tk
from googletrans import Translator
win=tk.Tk()
win.title("Translator")
win.geometry("250x150")
def translation():
word=entry.get()
translator=Translator(service_urls=['translate.google.com'])
translation1=translator.translate(word,dest="gu")
label1=tk.Label(win,text="translated to gujarati : %s "%translation1.text,bg="yellow")
label1.grid(row=2,column=0)
label=tk.Label(win,text="Enter Word : ")
label.grid(row=0,column=0,sticky="W")
entry=tk.Entry(win)
entry.grid(row=1,column=0)
button=tk.Button(win,text="Translate",command=translation)
button.grid(row=1,column=2)
win.mainloop()
|
fd9b120d8c1a0b88d42c95d8feec4a2fac29a2da | JemrickD-01/Python-Activity | /Fibonacci2.py | 572 | 4.34375 | 4 | def myFib(number):
if number<=0:
return None
if number<3:
return 1
summ=0
num1=1
num2=1
for i in range(3,number+1):
summ=num1+num2
num1=num2
num2=summ
return summ
only=['y','n']
choice='y'
while True:
myNumber=int(input("Enter your number: "))
for a in range(1,myNumber+1):
print(a,">",myFib(a))
choice=input("Would you like to continue? ")
while choice not in only:
print("Enter y or n only")
choice=input("Would you like to continue? ")
|
dbf59f2c9f314d1faf5744f374d0269c0e879344 | civitaslearning/openclass-python-api | /openclass/api.py | 6,769 | 3.578125 | 4 | import json, requests, urllib
class OpenClassAPI(object):
"""
OpenClassAPI class handles all requests to and from Pearson's OpenClass.com API.
Example: get info on a course.
>>> oc_api = OpenClassAPI('sam@classowl.com', 'password', 'openclass_api_key')
>>> r = oc_api.make_request('GET', '{}/v1/campus/coursesections/8303682'.format(oc_api.BASE_API_URL))
>>> r
{ 'courseTitle': 'Math 51', 'courseCode': 'MATH 51', ......... }
"""
# ====================================================
# static-ish variables
# ====================================================
BASE_API_URL = 'https://api.openclasslabs.com'
# For fetching the authentication token
IDENTITY_URL = '{}/v1/identities/login/basic'.format(BASE_API_URL)
IDENTITY_REFRESH_URL = '{}/v1/identities/login/refresh'.format(BASE_API_URL)
"""
OpenClassAPI
Purpose: establishes a connection with the OpenClass API, saves API key for later use
Returns: __init__ functions can't return anything! derrrrr
Required parameters:
- admin_email: email of OpenClass admin
- admin_pw: password of OpenClass admin
- api_key: OpenClass API key
Optional parameters:
- auth_token: authentication token (if you cached it)
- refresh_token: refresh token (if you cached it)
"""
def __init__(
self,
admin_email,
admin_pw,
api_key,
auth_token = None,
refresh_token = None,
debug = False
):
self.api_key = api_key
self.debug = debug
if auth_token and refresh_token:
if self.debug: print 'Auth tokens passed in at instantiation'
self.auth_token = auth_token
self.refresh_token = refresh_token
else:
if self.debug: print 'Getting auth tokens at instantiation'
self.set_auth_tokens(admin_email, admin_pw)
if self.debug:
print 'Auth tokens: {}'.format({'auth_token': self.auth_token, 'refresh_token': self.refresh_token})
# ====================================================
# authenticating with OpenClass
# ====================================================
"""
set_auth_tokens
Purpose: sets auth tokens from an admin email and password
Returns: None
"""
def set_auth_tokens(self, admin_email, admin_pw):
tokens = self.get_new_auth_tokens(admin_email, admin_pw)
self.auth_token = tokens['auth_token']
self.refresh_token = tokens['refresh_token']
"""
refresh_auth_tokens
Purpose: refreshes the OpenClass auth_token we need to make requests to their API
Returns: None
"""
def refresh_auth_tokens(self):
tokens = self.get_refreshed_auth_tokens()
if self.debug: print 'Auth tokens: {}'.format(tokens)
self.auth_token = tokens['auth_token']
self.refresh_token = tokens['refresh_token']
"""
get_new_auth_tokens
Purpose: gets a new auth token from OpenClass in order to make valid requests to their API
Returns: {'auth_token': <auth_token>, 'refresh_token': <refresh_token>}
Required parameters:
- admin_email: email address of OpenClass admin
- admin_pw: password of OpenClass admin
"""
def get_new_auth_tokens(self, admin_email, admin_pw):
url = '{}?apiKey={}'.format(self.IDENTITY_URL, self.api_key)
payload = {'email': admin_email, 'password': admin_pw}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data = payload, headers = headers)
status_code = r.status_code
# http status code != 200? raise an error!
r.raise_for_status()
data = r.json()['data']
return {'auth_token': data['authToken'], 'refresh_token': data['refreshToken']}
"""
get_refreshed_auth_tokens
Purpose: gets the new auth tokens by using the refresh token
Returns: {'auth_token': <auth_token>, 'refresh_token': <refresh_token>}
"""
def get_refreshed_auth_tokens(self):
url = self.IDENTITY_REFRESH_URL
payload = {'apiKey': self.api_key, 'refreshToken': self.refresh_token}
r = requests.get(url, params = payload)
data = r.json()['data']
return {'auth_token': data['authnToken'], 'refresh_token': data['refreshToken']}
# ====================================================
# do you take requests? now we do!
# ====================================================
"""
make_request
Purpose: creates a request to the OpenClass API
Returns: json response from OpenClass API
Required parameters:
- request_type: must be 'GET', 'POST', 'PUT', or 'DELETE'
- url: valid OpenClass API url
Optional parameters:
- payload: dictionary of extra parameters that will be encoded in request URL as GET vars
- headers: dictionary of extra headers you may need in the request
- data: dictionary of data that will be json'ed and sent in body of POST or PUT
"""
def make_request(self, request_type, url, payload = {}, headers = {}, data = {}):
xauth = {'X-Authorization': self.auth_token}
api_key = {'apiKey': self.api_key}
headers.update(xauth)
payload.update(api_key)
if request_type == 'POST':
r = requests.post(url, headers = headers, params = payload, data = json.dumps(data))
elif request_type == 'PUT':
r = requests.put(url, headers = headers, params = payload, data = json.dumps(data))
elif request_type == 'DELETE':
r = requests.delete(url, headers = headers, params = payload)
else:
r = requests.get(url, headers = headers, params = payload)
if self.debug:
print 'Requested URL: {}&token={}'.format(r.url, urllib.quote_plus(self.auth_token))
if payload: print 'Payload: {}'.format(payload)
if headers: print 'Headers: {}'.format(headers)
if data: print 'Data: {}'.format(data)
# If we don't have the latest auth token, refresh it on the fly and re-run the request.
if r.status_code == 401:
self.refresh_auth_tokens()
return self.make_request(request_type, url, payload = payload, headers = headers, data = data)
data = r.json()
if self.debug: print 'Response: {}'.format(data)
return data |
ed44dd41c1f76f4244bf6f837ac6b27430340b58 | boro1234/Algorithm | /Anagrams.py | 664 | 4.15625 | 4 | # Given two strings str1 and str2, write a function to determine if str1 is an anagram of str2. The string will only contain lowercase english letters.
def anagrams(str1,str2):
str1List = [ s for s in str1]
str2List = [ s for s in str2]
str1Set = set(str1List)
str2Set = set(str2List)
return str1Set == str2Set
str1 = 'bob'
str2 = 'bbo'
print(anagrams(str1,str2))
str1 = "bob"
str2 = "bod"
print (anagrams(str1, str2))
str1 = "race"
str2 = "acer"
print (anagrams(str1, str2))
#def anagram(str1, str2):
# d1 = {}
# d2 = {}
# for s in str1:
# d1[s] = d1.get(s,0) + 1
# for s in str2:
# d2[s] = d2.get(s,0) + 1
# return d1 == d2 |
3ef299ac5b6ea423efa0a7982e9bcbb3c063c820 | lddsjy/leetcode | /python/kthNode.py | 1,395 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
arr = []
arr = self.minnode(pRoot,arr)
print(arr)
if k<=len(arr) and k>0:
return arr[k-1]
else:
return None
def minnode(self,pRoot,arr):
if not pRoot:
return None
self.minnode(pRoot.left,arr)
arr.append(pRoot.val)
self.minnode(pRoot.right,arr)
return arr
# class Solution:
# # 返回对应节点TreeNode
# def KthNode(self, pRoot, k):
# if not pRoot:
# return None
# arr = [pRoot]
# arrOut = [pRoot.val]
# while arr:
# p = arr.pop(0)
# if p.left:
# arr.append(p.left)
# arrOut.append(p.left.val)
# if p.right:
# arr.append(p.right)
# arrOut.append(p.right.val)
# arrOut = sorted(arrOut)
# if k>len(arrOut) or k<1:
# return None
# return arrOut[k-1]
t1= TreeNode(8)
t2= TreeNode(6)
t3= TreeNode(10)
t4= TreeNode(5)
t5= TreeNode(7)
t6= TreeNode(9)
t7= TreeNode(11)
t1.left=t2
t1.right=t3
t2.left=t4
t2.right=t5
t3.left=t6
t3.right=t7
s=Solution()
print(s.KthNode(t1,0)) |
a1aa4505cd02c90e73cdca3262a2b3fb02d9332b | umnstao/lintcode-practice | /binary tree/453.flatten_binary_tree_toList.py | 564 | 3.90625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
# @param root: a TreeNode, the root of the binary tree
# @return: nothing
def flatten(self, root):
if not root:
return None
self.flatten(root.left)
self.flatten(root.right)
right = root.right
root.right = root.left
root.left = None
cur = root
while cur.right:
cur = cur.right
cur.right = right
|
c725cef6feff4939ebf55579861960c5cb188a01 | kendraregmi/Assignment1 | /Assignment/DataTypes/problem40.py | 231 | 4.34375 | 4 | # 40. Write a Python program to add an item in a tuple.
tuple1= (1, "Bob", "Kathmandu")
add_item= input(" Insert the item to add in tuple: ")
tuple2= (add_item,)
print(type(tuple2))
new_tuple= tuple1+tuple2
print(new_tuple) |
56db65775c008f5f4d555c621efe580e0da5698c | Subaru3000/my_python | /ИТ.py | 1,131 | 3.5625 | 4 | import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/dm-fedorov/pandas_basic/master/data/it.csv')
wage = df[df['З/п в валюте найма'].str.contains('₽')]
meanWage = wage['З/п в валюте найма'].str.translate(str.maketrans({'₽': '', ',': '.', '\xa0': ''})).astype(float).mean()
print('Средняя зарплата по данным в рублях: ', meanWage)
print("Технология с максимальной зарплатой по данным в рублях: ", wage.groupby(['Технология'])['З/п в валюте найма'].max().sort_values(ascending=False).index[0])
print('Возраст програмистов с макисмальной зарплатой: ', wage.groupby(['Дата рождения'])['З/п в валюте найма'].max().sort_values(ascending=False).index[0])
print("Зарплаты работников, у которых в названии вакансии встречается слово Engineer", df[df['Вакансия'].str.contains('Engineer')][['Вакансия','З/п в валюте найма']])
|
1e7ce57a37b25440e448b376bf7d912cacc4614c | Rohan-J-S/school | /seq_neg.py | 366 | 3.9375 | 4 | x = float(input("enter a number: "))
n = int(input("enter nth power: "))
out = 0
sign = -1
for y in range(n+1):
sign *= -1
out += (x**y)*sign
if y != n:
if sign == -1:
print(x,"^",y,sep = "",end = " - ")
else:
print(x,"^",y,sep = "",end = " + ")
else:
print(x,"^",y,sep = "",end = " ")
print ("=",out)
|
c49b4601811b1faacebcb2ec13f03a72b2cbab84 | dbabby/ForeverLove | /python3/student.py | 1,313 | 4.09375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# class Student(object):
# def __init__(self, name, score):
# self.name = name
# self.score = score
# def get_grade(self):
# if self.score >= 90:
# return 'A'
# elif self.score >= 60:
# return 'B'
# else:
# return 'C'
# lisa = Student('Lisa', 99)
# bart = Student('Bart', 59)
# print(lisa.name, lisa.get_grade())
# print(bart.name, bart.get_grade())
# bart.age = 8
# print('bart.age: %s' % bart.age)
# print(lisa.age)
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
def get_grade(self):
if self.__score >= 90:
return 'A'
elif self.__score >= 60:
return 'B'
else:
return 'C'
bart = Student('Bart Simpson', 59)
print('bart.get_name() =', bart.get_name())
bart.set_score(60)
print('bart.get_score() =', bart.get_score())
print('DO NOT use bart._Student__name:', bart._Student__name)
|
dc199ca573cbbe0c9c33e86bfe43d9dc659f3582 | sachinjose/100_days_of_code | /Day_2/day2.py | 816 | 3.859375 | 4 | # x# Python has 4 primitive data type 1. Integer 2. String 3. Float 4. Boolean
# # Strings
# print("Hello"[0])
# print("Hello" + "World")
# #Integer
# print(123+345)
# print(123_456_789)
# ## Float
# print(3.1415)
# ##Boolean
# print(True)
# print(False)
# num_char = len(input("What is your name: "))
# print(type(num_char))
# print("Your name has " + str(num_char) + " characters") #str is used to convert to string
# a = str(123)
# print(type(a))
# a=(input("Enter a two digit number "))
# one = int(a[0])
# two = int(a[1])
# print(one+two)
# print(3+5)
# print(7-4)
# print(3*2)
# print(6/3)
# print(2**3)
# print(round(2.34563,2))
# print(8//3) #to get integer output for division
##fstring
score = 0
height = 1.8
isWinning = True
print(f"Your score is {score}, Your height is {height}")
|
27ede59a4240ea65507b9a4b132c01249efbbe19 | NicVG/curso1-miniproyecto2 | /miniproyecto2.py | 3,262 | 3.890625 | 4 | nombres=input("Ingrese los nombres de los jugadores de la siguiente manera:(nombre1) (nombre2)\n")
nombres_lista=nombres.split()
nombre1=nombres_lista[0][0:3].upper()
nombre2=nombres_lista[1][0:3].upper()
if nombre1==nombre2:
nombre2+="2"
print("\n")
print(nombre1+" 501")
print(nombre2+" 501\n")
puntaje_y_lanzamientos1=[501,0,0,0]
puntaje_y_lanzamientos2=[501,0,0,0]
error=0
while puntaje_y_lanzamientos1[0]!=0 and puntaje_y_lanzamientos2[0]!=0:
print("Ingrese los últimos 3 lanzamientos de "+nombres_lista[0]+" seguido de los últimos 3 lanzamientos de "+nombres_lista[1]+".")
print("Debe ingresar: (multiplicador) (puntaje), Single Bull, Double Bull o Null (para lanzamiento perdido).\n")
for i in range(1,4):
lanzamientoi=input()
if lanzamientoi.upper()=="SINGLE BULL":
lanzamientoi=25
elif lanzamientoi.upper()=="DOUBLE BULL":
lanzamientoi=50
elif lanzamientoi.upper()=="NULL":
lanzamientoi=0
else:
multiplicacion=lanzamientoi.split()
if int(multiplicacion[0])<1 or int(multiplicacion[0])>3 or int(multiplicacion[1])<1 or int(multiplicacion[1])>20:
error=1
lanzamientoi=int(multiplicacion[0])*int(multiplicacion[1])
puntaje_y_lanzamientos1[i]=lanzamientoi
puntaje_y_lanzamientos1[0]=puntaje_y_lanzamientos1[0]-puntaje_y_lanzamientos1[1]-puntaje_y_lanzamientos1[2]-puntaje_y_lanzamientos1[3]
if puntaje_y_lanzamientos1[0]<0:
puntaje_y_lanzamientos1[0]=abs(puntaje_y_lanzamientos1[0])
for i in range(1,4):
lanzamientoi=input()
if lanzamientoi.upper()=="SINGLE BULL":
lanzamientoi=25
elif lanzamientoi.upper()=="DOUBLE BULL":
lanzamientoi=50
elif lanzamientoi.upper()=="NULL":
lanzamientoi=0
else:
multiplicacion=lanzamientoi.split()
if int(multiplicacion[0])<1 or int(multiplicacion[0])>3 or int(multiplicacion[1])<1 or int(multiplicacion[1])>20:
error=1
lanzamientoi=int(multiplicacion[0])*int(multiplicacion[1])
puntaje_y_lanzamientos2[i]=int(lanzamientoi)
puntaje_y_lanzamientos2[0]=puntaje_y_lanzamientos2[0]-puntaje_y_lanzamientos2[1]-puntaje_y_lanzamientos2[2]-puntaje_y_lanzamientos2[3]
if puntaje_y_lanzamientos2[0]<0:
puntaje_y_lanzamientos2[0]=abs(puntaje_y_lanzamientos2[0])
if error==1:
print("\n")
print("Error al ingresar los lanzamientos (multiplicador o puntaje inexistentes).")
print("El programa terminará.")
break
print("\n")
print(nombre1+" "+str(puntaje_y_lanzamientos1[0]))
print(nombre2+" "+str(puntaje_y_lanzamientos2[0])+"\n")
if puntaje_y_lanzamientos1[0]==0 and puntaje_y_lanzamientos2[0]==0:
print("Es un empate!")
elif puntaje_y_lanzamientos1[0]==0:
print("Gana "+nombres_lista[0]+"! Felicitaciones.")
elif puntaje_y_lanzamientos2[0]==0:
print("Gana "+nombres_lista[1]+"! Felicitaciones.")
|
6e34b6ec628c1dd70405d176ee0258fdb916c1b4 | tango1542/Capstone-Lab-1 | /q1 guess.py | 454 | 4 | 4 | import random
for x in range(1):
rando = random.randint(1,20)
print (rando)
guesses = 0;
while True:
print ("Guess a number between 1 and 20")
guess = input()
guess = int(guess)
guesses += 1
if rando > guess:
print("Too low, guess again")
if rando < guess:
print ("Too high, guess again")
if rando == guess:
print ("That's right! It took you " + str(guesses) + " guesses")
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.