blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
34b137094ea311e4199a5faf9423985ed44dfb1e | EvanMisshula/advpy | /7-funcTool.py | 850 | 4.125 | 4 | ## Functional Tools
## partial application of functions (currying)
def exp(base, power):
return base ** power
## 2 ^ power
def two_to_the(power):
return exp(2, power)
from functools import partial
two_to_the = partial(exp, 2)
print two_to_the(3)
square_of = partial(exp, power=2)
print square_of(3)
def ... |
4b3377c6f7f9a843241a1a63d47a0a42d4c505a6 | Phabibi/Python | /Go game/Assigment final.py | 13,127 | 3.875 | 4 | #############################
# DESCRIPTION #
#############################
################################################
# Name: Parsa Habibi #
# Class: CMPT-120 #
# Project: Final Assignment(Flipping Dance Game) #
# Last updated... |
005be5e3de54c33038857f8238db3b93e265dcad | Phabibi/Python | /Assignment 6/6 own.py | 215 | 3.765625 | 4 | def findUpper(st):
i=0
res=0
while i<len(st):
if st[i].isalpha():
if st[i].isupper():
res+=1+len(st[i])
i+=1
return res
print(findUpper("ABsC"))
|
660a064a0cd49115a5738670fb5a67ce54143cd8 | Phabibi/Python | /Assignment 6/Peer/6P A.py | 334 | 3.609375 | 4 | # Assigment 6
# Peer A *Upper
# Parsa Habibi
def UpperLetters (st):
i=0
res=0
while i<len(st):
if st[i].isalpha():
if st[i].isupper():
res=res+1
i+=1
if res==0:
res1="nothing"
else:
res1=res
return res1
print... |
f2d229cc967e7a9ebbd8ffd60ad6652df7530ec6 | huangpintian123/python- | /列表逆序输出.py | 135 | 3.671875 | 4 | list1 = list(input('plz input liebiao: '))
list2 = []
for i in range(len(list1)):
a = list1.pop()
list2.append(a)
print(list2) |
5c0b8e425cdbe5ad565deee56da5bb060b6e8cf1 | Krish0924/Hangman | /hangman.py | 2,290 | 3.703125 | 4 | from termcolor import cprint, colored
word = "hello"
bodyPartsLost = 0
def ldetetcion(letter):
# one character
# in the alphabet
if letter.isalpha() and len(letter) == 1:
return True
else:
return False
def display(letters):
underscores = ["_" for _ in range(len(word))]
global... |
17c4d63ed5169dd1c866584543fd16d962421bc9 | UNOBIOI/bioise_finalSubmission | /cgi-bin/tools/validation-3.py | 2,321 | 3.75 | 4 | from Bio.Seq import Seq
#Function checks to make user's file is correct and then sequence in the file
def file_check():
#Boolean variable used throughout the function, changes to false if there is a fail
checker = True
#Variable used to store the user notifications when a check fails.
response = ''
... |
31953e1136fcff2409d6cfb91fe9dbfb586f87c8 | JustinNew/LeetCode2 | /LongestConsecutiveSequence.py | 1,823 | 3.890625 | 4 | # 128. Longest Consecutive Sequence
# Google Tag
'''
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, ... |
e569cd3f2def38b921d45afb5d4d6cf2118a5534 | JustinNew/LeetCode2 | /MedianofTwoSortedArrays.py | 1,574 | 3.90625 | 4 | # 4. Median of Two Sorted Arrays
# Google Tag
'''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
... |
6e4dfaec1f20cb4811d69ce29cec551a9f5a2583 | JustinNew/LeetCode2 | /FindMedianfromDataStream.py | 1,808 | 3.890625 | 4 | # 295. Find Median from Data Stream
# Google Tag
'''
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data struct... |
bdedf2c7866db5236f6333f45066244ec5fb51d2 | guyneedham/MMDS | /shingles/shingles.py | 575 | 3.75 | 4 | str1 = "ABRACADABRA"
str2 = "BRICABRAC"
def shingle(str):
s = set()
for i,c in enumerate(str):
if i < len(str) - 1:
shing = c+str[i+1]
s.add(shing)
return s
shingle1 = shingle(str1)
shingle2 = shingle(str2)
print('Number of 2-shinlges in ABRACADABRA = '+str(len(shingle1)))... |
37f667c32b7246555adc2c09b73ebcc6e90f1f10 | leggers/python-data-structs-and-algos | /Data Structures/binary_tree.py | 4,256 | 4.15625 | 4 | #!usr/bin/python
# Author: Lucas Eggers
# A binary tree data structure
class BinaryTree(object):
"""A binary tree data structure. A naive implementation.
Not a balanced tree or even a search tree. Just an arbitrary tree."""
def __init__(self):
super(BinaryTree, self).__init__()
self.root =... |
41f512a78ab504113c399ce7da9c62d0977ccf18 | alvarocesped/03Tarea | /Tarea3.py | 3,763 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
from mpl_toolkits.mplot3d import Axes3D
#Parte 1
#Funciones para usar Runge Kutta de orden 3.
def f(y, x):
'''
Función vectorial usada para correr método de integración.
Funciones y=Y(s) y x=dY/ds son los argumentos de est... |
8892ef556e785c89ff869d9332e7da29b00932c5 | dvberkel/stn | /stn.py | 441 | 3.546875 | 4 | #! /usr/bin/env python
import sys
def s(s0, s1):
return 6 * s1 - s0
def t(t0, t1):
return 6 * t1 - t0 + 2
if __name__ == '__main__':
n = 20
if (len(sys.argv) == 2):
n = int(sys.argv[1])
s0 = 0
s1 = 1
t0 = 0
t1 = 1
while (n > 0):
sn = s(s0, s1)
s0 = s1
... |
5126617c4be8de0ee7758957b5b99ff7a9d019fc | SapirShahar/Hangman-game | /Hangman 4.3.1.py | 235 | 3.984375 | 4 | user_guess=input("Guess a letter:")
if len(user_guess)>1:
if user_guess.isalpha() == False:
print ("E3")
else:
print("E1")
elif user_guess.isalpha() == False:
print("E2")
else:
print(user_guess.lower()) |
c47bbb4d5c029e158fa0aa55d6266c31ca802fb1 | SapirShahar/Hangman-game | /Hangman5.5.1.py | 196 | 3.859375 | 4 |
def is_valid_input(letter_guessed):
if len(letter_guessed) > 1 or letter_guessed.isalpha() == False:
return False
else:
return True
x = is_valid_input('kdkdk*')
print(x) |
55ebe1ec20fd1cb1ea55ada814a2d88fd106f5b3 | ShreyanshAtru/PRIDECTION-USING-SUPERVISED-MACHINE-LEARNING | /task1.py | 2,194 | 3.53125 | 4 | # THE SPARK FOUNDATION INTERNSHIP
# SHREYANSH JAIN
# TASK 1 : Predict the percentage of an student based on the no. of hours of studies
# PRIDECTION USING SUPERVISED MACHINE LEARNING
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as s... |
53074bccced971b47b2e9b4095ef0804372e06e5 | monchhichizzq/Leetcode | /Valid_Parenthese.py | 1,394 | 4.0625 | 4 | class Solution:
def isValid(self, s):
'''
To determine whether an input string is valid:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Args:
s: input string
Returns:
bool: ... |
d755ef76a8731410118cd91a00e64cd123ec3bf9 | jinyuz/Data-mining | /kmeans.py | 1,801 | 3.984375 | 4 | import numpy as np
def norm(x):
"""
>>> Function you should not touch
"""
max_val = np.max(x, axis=0)
x = x/max_val
return x
def rand_center(data,k):
"""
>>> Function you need to write
>>> Select "k" random points from "data" as the initial centroids.
"""
pass
def converge... |
6270ef0897bf0bd0b9218eae58f1b29da692eb7a | afmasita/datasciencecodecademy | /games_of_chance.py | 3,062 | 3.828125 | 4 | import random
money = 100
#Write your game of chance functions here
def coin_flip(guess, bet):
if guess == "Heads":
guess_code = 1
elif guess == "Tails":
guess_code = 2
else:
"Invalid bet! Enter Heads or Tails"
random_flip = random.randint(1,2)
if random_flip == guess_code:
return "Yo... |
52d6421973c77d1822ceb68f96e843c897cbb5f9 | Grantmac75/Random_Projects | /Technical_Questions.py | 2,128 | 4.03125 | 4 | # Technical Questions
##############################
# Return counter of words in a sentence/Return most occuring word
##############################
# Version 1, Standard Control Flow
#%%
sentence = 'It was the best of times it was the worst of times it was also a happy time'
sentence_list = sentence.split() # Retur... |
5f3b72d7d17f5093dcbee08f75c9f606b116be7b | Pedrobertuola/curso-em-video-course | /Mundo_3/Ex072.py | 375 | 3.828125 | 4 | T=('zero','Um','Dois','Três','Quatro','Cindo','Seis','Sete','Oito','Nove','Dez','Onze','Doze','Treze',
'Quatorze','Quinze','Dezesseis','Dezessete','Dezoito','Dezenove','Vinte')
while True:
N=int(input('Digite um número de 0 a 20: '))
if 0<=N<=20:
break
else:
print('Erro!Digite um valor en... |
85f32cf0895c99a682d8234a9cbebb504f14b9de | Pedrobertuola/curso-em-video-course | /Mundo_3/Ex94.py | 1,131 | 3.625 | 4 | galera=[]
pessoa={}
soma=media=0
while True:
pessoa.clear()
pessoa['nome']=str(input('Nome: '))
while True:
pessoa['sexo']=str(input('Sexo [M/F]: ')).strip().upper()[0]
if pessoa['sexo'] in 'MF':
break
print('Erro! Por favor, digite apenas M ou F.')
pessoa['idade']=in... |
5fae9aaed3c08fc613b380cf2b3843b8fdbd50e7 | Pedrobertuola/curso-em-video-course | /Mundo_3/Ex78-Maior e menor valores na lista.py | 463 | 3.8125 | 4 | valores=[]
maior=0
menor=0
for c in range(0,5):
valores.append(int(input(f'Digite um valor para posição {c}: ')))
if c==0:
maior=menor=valores[c]
else:
if valores[c]>maior:
maior=valores[c]
if valores[c]<menor:
menor=valores[c]
print(valores)
print(f'O maior ... |
865bedf3a024ced968a195a7c0958cbdef2b4b9e | YancongLi/Python_Essential_Training_ExerciseFiles | /Exercise Files/Chap06/while.py | 439 | 3.859375 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
secret = 'peter666'
pw = ''
auth = False
count = 0
max_attempt = 3
while pw != secret:
count += 1
pw = input(f"{count}: What's the secret word? ")
if pw == secret:
auth = True
if (count + 1) > max_attempt:
print("You trie... |
edfb0426c25b6c036f42c342d68ed6beead9f826 | YancongLi/Python_Essential_Training_ExerciseFiles | /Exercise Files/Chap07/function.py | 995 | 4.15625 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
kitten(6, 6)
kitten(1, 2, 3)
x = 5
print(f'The memory representaiton of x in main is: {id(x)}')
call_by_value(x)
print(f'in main : x is {x}')
y = [2333]
print(f'The memory representaiton of y in main is: {id(y)}... |
8a67540373dc25ed2f2eb7c96ba39defb994a364 | BrayanAnn/python | /banco.py | 1,683 | 3.734375 | 4 | class Cliente:
def __init__(self, nome, sobrenome, cpf):
self.nome = nome
self.sobrenome = sobrenome
self.cpf = cpf
class Conta:
def __init__(self, numero, cliente, saldo, limite):
self.numero = numero
self.titular = cliente
self.saldo = saldo
... |
62470b453777febee5d601a433cd4429e68a9ddb | BrayanAnn/python | /usando_operadores.py | 341 | 4.03125 | 4 | num1 = 10
num2 = 5
print("Soma {} ".format(num1 + num2))
print("Subtração {}" .format(num1 - num2))
print("Multiplicação {}" .format(num1 * num2))
print("Divisão {}" .format(num1 / num2))
print("Divisão inteira {}".format (num1 // num2))
print("Módulo {}". format(num1 % num2))
print("Potenciação {}".format(nu... |
7f90f0a32493bef3ff3786306e59d1fa8b7ea238 | franciscogomes2020/exercises | /en/104/python/main.py | 200 | 3.765625 | 4 | # Create a program that has the readInt() function, which will work similarly to the Python input() function, except that it validates to accept only a numeric value.
Ex: n = readInt('Type one n: ')
|
dd23ec4da909ce0460c62949fd6ddacc7c4ab959 | sgouda0412/regex_101 | /example/02_matching_digits_and_non_digit_characters.py | 274 | 4.1875 | 4 | """
Task
You have a test string S. Your task is to match the pattern xxXxxXxxxx
Here x denotes a digit character, and X denotes a non-digit character.
"""
import re
Regex_Pattern = r"\d\d\D\d\d\D\d\d\d\d"
print(str(bool(re.search(Regex_Pattern, input()))).lower())
|
b2acc6bc18ee909e90e7bcb6698db4cc2b55c72a | sgouda0412/regex_101 | /example/08_matching_character_ranges.py | 646 | 4.09375 | 4 | """
Task
Write a RegEx that will match a string satisfying the following conditions:
The string's length is >= 5.
The first character must be a lowercase English alphabetic character.
The second character must be a positive digit. Note that we consider zero to be neither positive nor negative.
The third character mus... |
2ad852214ea6003ac829571a41c88af35ec018bf | sgouda0412/regex_101 | /example/013_matching_ending_items.py | 296 | 4.125 | 4 | """
Task
Write a RegEx to match a test string, S, under the following conditions:
S should consist of only lowercase and uppercase letters (no numbers or symbols).
S should end in s.
"""
import re
Regex_Pattern = r'^[a-zA-Z]*[s]$'
print(str(bool(re.search(Regex_Pattern, input()))).lower())
|
21a0199d2eaf68758249a6d7125c86a82fa1b861 | sachok42/advanced-life-game | /new_diagonal_bot.py | 1,263 | 3.5 | 4 | from math import sqrt
def step(world):
comand = {}
# print(world["units"])
unit = world["units"][world["self_id"]]
# print(unit)
if unit.hp >= 5:
return {"key" : "split", "give" : 2}
# comands[unit_id] = {"key" : "move", "x" : 5, "y" : 5}
near_food = -1
near_food_length = 0
for food_id in ... |
2b4d58a414e500257e29a506e99d03845d7fe90c | xiaoqiang-zhao/my-cellar | /web/articles/python/demo/12-偏函数.py | 148 | 3.671875 | 4 | import functools
def int2(x, base=2):
return int(x, base)
a = int2('10')
int3 = functools.partial(int, base=8)
b = int3('10')
print(a, b)
# 2 8 |
553b0cbdfe03d43ff6453305384ad50f56fc0a56 | SY-Enigma/pythonStudy | /8_11/C1_iterator.py | 1,047 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/8/11 13:32
# @Author : suyang
# @FileName: C1_iterator.py
# @Software: PyCharm
#迭代器对象可以使用常规for语句进行遍历:
# list=[1,2,3,4]
# it = iter(list) # 创建迭代器对象
# for x in it:
# print (x, end=" ")
# 使用 next() 函数:
# import sys # 引入 sys 模块
#
# list = [1, 2, 3, 4]
# it = iter(list... |
ae1bfb500317ff806e7850557d9f5869968f3d88 | DmitryMantush/PythonBox | /test.py | 1,504 | 3.6875 | 4 | print('Enter expression. Use only + - * / and numbers. Enter "quit" to finish the program.')
while True:
try:
task = str(input())
if task == 'quit':
break
import re
mix = list(re.findall('[+-/*]|\d+', task))
if mix[0] == '-':
mix.insert(0, '0')
... |
7cdb4b0ded5c997b6841d9030a1a0e9e415b14fc | IgnatIvanov/Loan-Calculator_JetBrainsAcademy | /Problems/Young and beautiful/main.py | 275 | 3.859375 | 4 | jack_age = int(input())
alex_age = int(input())
lana_age = int(input())
if jack_age > alex_age:
if alex_age > lana_age:
print(lana_age)
else:
print(alex_age)
else:
if jack_age > lana_age:
print(lana_age)
else:
print(jack_age)
|
6dbc28bfd45fb5c015d4fe7634970c0925871108 | IgnatIvanov/Loan-Calculator_JetBrainsAcademy | /Problems/What day is it/main.py | 137 | 3.921875 | 4 | time_zone = int(input())
if time_zone >= 14:
print("Wednesday")
elif time_zone < -10:
print("Monday")
else:
print("Tuesday") |
0741ccbb4340cef4f861cbf2809db6d2da388cab | Zrxrxrx/Gobang | /tableClass.py | 1,296 | 3.609375 | 4 | class chess:
xy = None
Next = None
rate = 0
def __init__(self,xy,Next=[]):
self.xy=xy
self.Next=Next[:]
def isIN(self,xy):
return xy in self.Next
def add(self,c):
self.Next = []
self.Next.append(c)
@staticmethod
def copy(root):
newc = chess... |
594ef745883453178d2f9060ecf68f45cdc51ac7 | gabrielcn/Python | /programa renda - fatec python.py | 363 | 3.640625 | 4 | #Programa Renda
RND=float(input("Informe Renda"))
if RND>15.760:
print("Classe A")
else:
if RND>7.880:
print("Classe B")
else:
if RND>3.152:
print("Classe C")
else:
if RND>1.576:
print("Classe D")
else:
... |
aab6481c037b18f35265ad8e4d957976d307e104 | gabrielcn/Python | /simuladop2_gabarito.py | 1,050 | 3.71875 | 4 | def matriz_a(n):
a=[]
total=0
while True:
elem=int(input("entre com elemento ==>"))
if total==n:
break
if elem%2==0:
a.append(elem)
total=total+1
else:
print("só aceita par")
return a
#construindo... |
8f3a79d5cf06ed12683bb1bc9519766174819a26 | gabrielcn/Python | /controlewhilefor.py | 324 | 4 | 4 | #(While)
print("While")
controle=15
while controle <= 200:
print("O quadrado de", controle, "é", controle**2)
controle=controle+1
#------------------------------------------------------------------------
#(For)
print("For")
for control in range(15,201,1):
print("O quadrado de", control, "é", control*control... |
360c7b04d006e259d0fc08ad97e2875e10b11dce | saidworks/TTC | /chapter12_Packages_Modules/MyFirstPackage/includes/ModuleA.py | 343 | 4.15625 | 4 | string=input("enter a word").lower()
letter=input("enter the letter you want to know its frequency").lower()
def count_string(string,letter):
times=0
for index in range(len(string)):
if string[index:index+1]==letter:
times+=1
else:
times+=0
return print("the letter oc... |
1c3da19fba3de698b1732330ec6728afd25beee1 | saidworks/TTC | /chapter12_Packages_Modules/Rename_jpg.py | 407 | 3.640625 | 4 | import os
#get directory name
dirname=input("Enter the directory: ")
#create a list
os.chdir(dirname)
dirlist=os.listdir()
#get new lead name
lead=input("What label do you want for the pictures? ")
picture_number=1
#rename pictures
for filename in dirlist:
if filename.endswith('.jpg'):
newname = lead + str... |
1b7604dcebb1a3c9aeeaa8e4a59a8690cf6ff426 | saidworks/TTC | /chapter9_Functions_and_Abstraction/Functions.py | 787 | 4.09375 | 4 | def getBirthday():
m,d,y=input("enter your birth month"),input("enter your birth day"),input("enter your birth year")
birthday=(m,d,y)
s="-"
if birthday==("4","20","1988"):
print("Awesome birthday")
return s.join(birthday)
print(getBirthday())
n=int(input("enter a number"))
def factorial(n... |
bdd0e46637c9cfcc88302e940cc515bf6dd2e789 | saidworks/TTC | /chapter15_Event_Programming/playgroundtk.py | 849 | 3.625 | 4 | import tkinter
class Application(tkinter.Frame):
def __init__(self, master=None):
tkinter.Frame.__init__(self, master)
self.pack()
self.increase_button = tkinter.Button(self)
self.increase_button["text"] = "Increase"
self.increase_button["command"] = self.increase_value
... |
d8bbe8741be1afa86fbf0fa597f53d11fd1b919f | dustyujanin/Python_course | /lesson6/lesson6_2.py | 285 | 3.515625 | 4 | class Road:
def __init__(self, length, width):
self._width = width
self._length = length
self.weight = 25
self.height = 5
def calculate(self):
print(self._length * self._width * self.height * self.weight)
a = Road(2, 1)
a.calculate()
|
b3f28cec7fd3ac91d2e3cb0cb5767c87782c8c89 | dustyujanin/Python_course | /lesson2/lesson2_6.py | 1,473 | 3.6875 | 4 | ed = ['1:шт', '2:кг', '3:л']
my_list = []
my_dict = []
my_result = dict({})
i = 0
while True:
i += 1
print('1.Добавить товар')
print('2.Посмотреть аналитику')
print('3.Выход')
x = int(input("Введите команду: "))
if x == 3:
break
if x == 1:
name = input('Введите название: ')... |
d1ee54d3c1964df24f56517ad82f1dd0eedf3251 | Ankit05012019/Python-Daily-Problems | /array_Of_Number_Of_Smallerelements.py | 573 | 3.6875 | 4 | #Problem - Given an array of integers, return a new array where each element in the new array is the number of smaller elements to the right of that element in the original input array.
def myfunc(arry):
range= len(arry)
range_valid=range - 1
new_lst=[]
n=0
while n < range_valid:
nr=n+1
... |
7e8962759a7dcbb35c92b79b02deba7ac67cd8f3 | mtrestman1/Intro-Python-II | /src/room.py | 448 | 3.65625 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
from item import Item
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.items = [
Item("candle", "it gets dark at night"),
... |
75dbd4acae76bd2735da98cbaa154571641fbcb1 | apcor/geekbrains_py_apcor | /geekbrains_python/functions08/functions08-02.py | 191 | 3.6875 | 4 | def calc_max(numbers):
return max(numbers)
num = []
i = 1
while i<4:
number = int(input(f"Введите {i}-ое число: "))
num.append(number)
i+=1
print(calc_max(num))
|
7787aeafc62dba577150451824335b7733237216 | apcor/geekbrains_py_apcor | /pybasics_webinars/Sogoyan_Arsen_DZ_1/task_4.py | 558 | 3.984375 | 4 | # Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
# user_inp = int(input('Введите целое положительное число: '))
user_inp = 13764328761308748231
max_digit = user_inp % 10
while not user_inp == 0:
if user_inp % ... |
73535b5f98c4f0eb3ce64f039be1e6d338fd6ddd | apcor/geekbrains_py_apcor | /geekbrains_python/tools14/tools14_01.py | 256 | 3.828125 | 4 | list_1 = ['бананы', 'яблоки', 'киви', 'апельсины', 'манго']
list_2 = ['манго', 'мандарины', 'виноград', 'гранаты','киви']
result = [fruit for fruit in list_1 if fruit in list_2]
print(result) |
b3d3380e9b49b5e2f45d6febd116b81a781027ec | apcor/geekbrains_py_apcor | /pybasics_webinars/Sogoyan_Arsen_DZ_6/task_3.py | 864 | 3.953125 | 4 | class Worker:
_income = {"wage": 10, "bonus": 5}
def __init__(self, name, surname, position):
self.name = name
self.surname = surname
self.position = position
class Position(Worker):
def __init__(self, name, surname):
super().__init__(name, surname, Worker._income)
... |
22f258c3de149f6819cf6486fa9a28772ed4df6b | apcor/geekbrains_py_apcor | /geekbrains_python/functions08/functions08-03.py | 581 | 3.75 | 4 | def calc_damage(player_a, player_d):
return player_a['damage'] / player_d['armor']
def attack(player_a, player_d, func):
player_d['health'] -= func(player_a, player_d)
print(player_a, player_d)
name_player = input("Введите имя первого игрока: ")
name_enemy = input("Введите имя второго игрока: ")
playe... |
48f70ec010eb7be7deabef5b641bbed8828264d2 | Shokir-developer/python_intermedite-projects | /calculator/mashq.py | 801 | 3.640625 | 4 | import math
print("1. + ")
print("2. - ")
print("3. * ")
print("4. / ")
print("5. EXIT ")
yana = True
while yana:
command = 4#int(input("Choose command: "))
result = 0
aList = []
if 1 <= command <= 4:
print("Enter numbers: ")
print("QUIT = -1")
while True:
num = int(input(">>> "))
if num == -1:
br... |
2632964f2b3b0286df49fc3e69f6c079b72663b8 | noa19-meet/yl1-201718 | /individual project/agario.py | 8,164 | 3.875 | 4 | import turtle
from turtle import Turtle
import time
import random
import math
class Ball(Turtle):
def __init__(self,x,y,dx,dy,r,color):
Turtle.__init__(self)
self.x=x
self.y=y
self.dx=dx
self.dy=dy
self.penup()
... |
9253b5df8118c1f5f71e80754d4c456807ba7cd9 | noa19-meet/yl1-201718 | /individual project/Ball.py | 561 | 3.84375 | 4 | from turtle import *
import math
class Ball (Turtle):
def __init__(self,x,y,dx,dy,r,color,shape,shapesize):
self.x(x)
self.y(y)
self.dx(dx)
self.dy(dy)
self.r(r)
self.color(color)
self.shape("circle")
self.shapesize(r/10)
self.penup()
def move(self,screen_width,screen_height):
current_x = self.xc... |
d3671674ecb96942c34343c7ba73b8e8b631c317 | nikhilrane1992/Python_Basic_Exercise | /swap_two_variables.py | 466 | 4.125 | 4 | # Python program to swap two variables
# To take input from the user
a, b = input('Enter value by comma seperated: ')
# create a temporary variable and swap the values
temp = a
a = b
a = temp
print('The value of a after swapping: {}'.format(a))
print('The value of b after swapping: {}'.format(b))
# Method 2 for s... |
3e46f9d2a6f9d1bb53b2f6c2bc0c2a9360110ba5 | nikhilrane1992/Python_Basic_Exercise | /calculate_area_of_triangle.py | 255 | 4.125 | 4 | # Python Program to find the area of triangle
a, b, c = 5, 6, 7
# Calulate the sami parameter of triangle
s = (a + b + c) / 2
# Calculate the area
area = (s * (s - a) * (s - b) * (s - c)) ** (1 / 2.0)
print "Area of triangle is : {:.2f}".format(area)
|
ed9f94c9a3d55311b38c7728fdc305e70bebc132 | shubhamyedage/pycharm-codebase | /Test/apps/tree_tests/simple_tree_test.py | 1,356 | 3.640625 | 4 | from treelib import Tree
tree = Tree()
tree.create_node("Root", "Root", data={"Name": "Anthony"})
tree.create_node("Child1", "Child1", data={"Name": "Breta"}, parent="Root")
tree.create_node("Grand_Child1", "Grand_Child1", data={"Name": "Brica"}, parent="Child1")
tree.create_node("Great_Grand_Child1", "Great_Grand_Chi... |
06c0ff6586a8a1053042b79f5f11bd0f2b53f3bf | zl9901/CSCI665-LAB1 | /PoissonMyQuickSort.py | 1,698 | 4.25 | 4 |
import numpy as np
import time
import random
"""
InsertionSort function which is used for InsertionSort algorithm
"""
def InsertionSort(array):
for i in range(1,len(array)):
key=array[i]
j=i-1
while j>=0 and array[j]>key:
array[j+1]=array[j]
j-=1
... |
cbd5dfb1f53671ec9e87dd89469d38046d26bfe8 | Robzabel/AutomateTheBoringStuffScripts | /15.Advanced_Strings.py | 432 | 4.125 | 4 | print('Hello\nHow are you?')
#raw string examples
cat = r'that is Carol\'s cat.'
print(cat)
#or you can print straight ot the terminal
print( r'\c\Documents\Files\Weddingd')
print(""" Hello my name is Rob
I live in Truro.
I have a cat that is stinky,
I also have a wife that is awesome """)
#Lists are sim... |
5b819c48a2512c50ecdd829b614f8bbf69e66249 | Robzabel/AutomateTheBoringStuffScripts | /23.Regex_Dot-Star_&_CarretDollar.py | 2,306 | 4.125 | 4 | import re
#The Caret matches to the beginning
beginsWithHelloRegex = re.compile(r'^Hello')
mo=beginsWithHelloRegex.search('Hello there')
print(mo.group())
#the Dollar character matches to the end
endsWithWorldRegex = re.compile(r'World$')
mo = endsWithWorldRegex.search('Hello World')
print(mo.group())
# you can combine... |
4a864fad9a1129272932455baee3e93776397794 | cafecinqsens/PY_Hiroki | /EPS_181.py | 765 | 3.5 | 4 | # 확률변수의 변환
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
# 분포함수를 G(y)라 하고 파이썬으로 구현
y_range = [3, 5]
def g(y):
if y_range[0] <= y <= y_range[1]:
return (y-3)/2
else:
return 0
def G(y):
return integrate.quad(g, -np.inf, y)[0]
ys = np.linspace(y_range[0],... |
dc9006b8874ed38af7948585a51550f5c096f9fb | prwlnght/deeplearning_practice | /src/bone_animate.py | 791 | 3.609375 | 4 | '''
Sub-project: EAI, how does RNN work? and why does RNN work?
Goals:
1. Implement a classifier based on Recurrent Neural Network and understand its compoments
2. Implement an auto-encoder to 'predict' the next time-stamp
3. Train on the entire network, then animate
4. Switch datasets.
Input:
x,y coodinate data f... |
9d755a49e9e8ef5468c37fb17f98fd0255e413db | KOdunga/Python_Introduction | /PycharmProjects/untitled/lesson1.py | 1,486 | 4.0625 | 4 | print(8000)
print("Modcom")
print (7000)
print (5+6)
print ("Hello")#comment
# Rules in a variable:
# 1. No Spacing
# Don not start with a number, you can end with a number
num1 = 30000 # Ths is an int
num2 = 40000
num3 = 50000
num4 = 70000
num5 = 500.5 # This is a float
# Data Types
# Numbers
# String
# List
# Tuple... |
f7d4d315bd55cdc740a431b3a18a9ccd5dad57b3 | KOdunga/Python_Introduction | /PycharmProjects/untitled1/lesson3.py | 560 | 4.25 | 4 | # Comparison Operators
# Used with decision aking. If Statements, IF..Else,Nested If
marks =int(input("Enter your marks: \n"))
# If Else deals with only a single condition
if marks<50:
print (marks)
print("Failed")
print("You repeat Class")
if marks <32: # Nested If
print (... |
5cb7cbe45c26380fd0fe70b335923b4946c7da99 | dave5801/data-structures | /test_bst.py | 6,233 | 3.890625 | 4 | """Class for testing BST."""
import random
def test_node_exists_no_args(tree_node):
"""Test Create a Tree Node."""
assert tree_node
def test_if_iterable_is_inserted(bst):
"""Test for iterables."""
from bst import Tree
test_iter = [5, 3, 7]
test_node = Tree(test_iter)
assert test_node.roo... |
7545fa71884d0a7efe94e44428a7502a4ce613f5 | dave5801/data-structures | /sorting/test_sort.py | 2,988 | 3.796875 | 4 | """Test class for sorting algorithms."""
from random import randint
def test_sortings_test_none_list():
"""Test none list."""
from bubble_sort import bubble_sort
s = bubble_sort()
assert s == []
def test_bubble_sort_empty_list():
"""Test Bubble sort on empty list."""
from bubble_sort import... |
1d9f73002be109af09cbe6be52a94b2c30f4ad45 | sankethbhongir/Problems-vs-Algorithms | /search_rotated_sorted_arrray_problem/search_rotated_array.py | 2,098 | 4.1875 | 4 | def binary_search(input_list, number, start_index, end_index):
if start_index > end_index:
return -1
mid_index = (start_index + end_index) // 2
mid_item = input_list[mid_index]
if mid_item == number:
return mid_index
elif number < mid_item:
return binary_search... |
1b52fcaf7327cae8d93d25080a3510bedfb68003 | kevinjdonohue/LearnPythonTheHardWay | /ex6.py | 1,324 | 4.40625 | 4 | """Exercise 6."""
# variable assigned the integer value 10
types_of_people = 10
# variable assigned a format string that contains the types_of_people variable
x = f"There are {types_of_people} types of people."
# variable assigned the string "binary"
binary = "binary"
# variable assigned the string don't
do_not = "... |
5e44e0cba86408844b3a0c788039eeedb079d4b0 | kevinjdonohue/LearnPythonTheHardWay | /ex39.py | 1,522 | 4.25 | 4 | """Exercise 39."""
states = {
"Oregon": "OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
}
cities = {"CA": "San Francisco", "MI": "Detroit", "FL": "Jacksonville", "NY": "New York", "OR": "Portland"}
print("-" * 10)
cities_formatter = "{} State has: {}"
print(cities_... |
8be9d77483c213d2d84d9ce178d20606f83a812c | DomathID/python-cok | /mbalik.py | 195 | 4.03125 | 4 | def reverse(k):
str = ""
for i in k:
str = i + str
return str
k = input('word:')
print ("awal : ",end="")
print (k)
print ("dibalik : ",end="")
print (reverse(k))
|
9689172dfd2fa4022e7c8b0f86e4e00623ed5eea | cgsmendes/aulas | /exerc_multaporexcessodepeso.py | 402 | 3.71875 | 4 | peso = float(input("Qual o peso em quilos: "))
if peso > 50:
excessopeso = peso - 50
print("Você excedeu o peso limite em: ",excessopeso,"!")
multa = excessopeso * 4
print("A multa é de R$ 4,00 por quilo excedente, neste caso você deverá pagar um total de: R$ ",multa," de multa!")
else:
print("Você ... |
598a4d7da8f0b7fd2c03f62c730f08a067d76410 | cgsmendes/aulas | /exerc_while.py | 202 | 3.984375 | 4 | a=int(input("\n\nDigite o número ao qual deseja somar as unidades: \n\n"))
c=0
while a!=0:
b=int(a%10)
c=c+b
a=int(a//10)
print("\nA soma das unidades do número digitado é: ",c,"\n\n")
|
9a25c0e4806bc9127f90403cd5453c88e0e73717 | cgsmendes/aulas | /exerc_dobroarea.py | 194 | 3.890625 | 4 | base = float(input("Digite o comprimento da base: "))
altura = float(input("Digite o comprimento da altura: "))
dobroarea = base * altura * 2
print("O dobro da área do quadrado é: ",dobroarea) |
293d21a3ac1a86e9357235e2eb9176cb19fd793f | Alwurts/Connect-4 | /main.py | 17,711 | 3.703125 | 4 | from tkinter import Tk, Label, Frame, LabelFrame, Button, PhotoImage,Message, messagebox, Grid, Entry, StringVar, Canvas
import math
class Base():
def __init__(self):
self.frames = {} # Dictionary to hold the frames that we are going to show
def load_frames(self, *args):
for F in args:
... |
a41bf574deb073702f791273496e5f87198fad12 | kushalkarki1/pythonclass-march1 | /forloop.py | 814 | 3.71875 | 4 | # for <variable> in <iterable_object>:
# code to repeat
# alist = ["ram", "shyam", "hari", "sita"]
# blist = [1, 2, 3, 4, 5, 6]
# for item in alist:
# print(item)
# for item in blist:
# print(item)
# for i in range(100, 1, -2):
# print(i)
# range(start, stop, step)
# range(100)
# start->0, stop... |
2d8ca3dc5138f5d2f151969337d820d3a192044d | bishaljung/try-ticket-system | /ticketsystem.py | 7,123 | 3.953125 | 4 | # here i am going to create the ticket system using class and object for learning purpose.
import pickle
class passenger:
# The _ _init_ _ method initializes the attributes of class passenger.
def __init__(self, name, phone, email):
self.__name = name
self.__phone = phone
self.__e... |
e8ae7cc7c59ee1b4f9484f15fbb58e975aa0625a | zirin12/map-reduce | /wordcount with mapreduce approach (in python )/mapreduce for getting urllist/red.py | 525 | 3.796875 | 4 | #!/usr/bin/env python
import sys
# maps words to their counts
word2count = dict()
# input comes from STDIN
for line in sys.stdin:
text = line.split(" ")
word = text[0]
key= text[1]
if(word == "chumma"):
break
try:
word2count[word].append(key)
except:
word2count[word... |
466077b73bcf88807cc15027fdcd4d9559723425 | ebresie/MyGitStuff | /books/OReillyBooks/LearningPython/regularExpression.py | 101 | 3.71875 | 4 | import re;
S='Hello Python world'
match=re.match('Hello[ \t]*(.*)world', S);
print(match.group(1)); |
9b888904bb57b8a0599ddb827ddece72d007a619 | ustya-k/hse-python | /3 курс/week-1/solution-3.py | 2,854 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: Ustinia Kosheleva
from os import listdir, stat
from os.path import isfile, join
from operator import itemgetter
import sys
def get_file_size(file, dirpath):
'''
Finds size of a file, creates tuple of name of the file and it's size.
Args:
f... |
9986feac92c7b02847d2588b9ab6b8afda6c8dcf | ustya-k/hse-python | /3 курс/week-1/solution-2.py | 2,358 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: Ustinia Kosheleva
import re
def lines_to_dict(lines):
'''
Converts a dictionary given as list of lines to dictionary data structure,
where keys are words and values are lists of meanings.
Args:
lines: list
Returns:
dict
... |
064c683a3d512609f3a2b1549caf65e92cdd3b60 | Patrick-Ali/210CT-Programming-Algorithms-Data-Structures | /FinalPrograms/cleanRecPrime.py | 528 | 4.1875 | 4 | def isPrime(num1, num2):
if (num1 <= 1):
return(False)
elif num1 == 2:
return(True)
elif num2 <= 1:
return(True)
elif num1%num2 == 0:
return (False)
else:
return(isPrime(num1, (num2-1)))
def main():
num1 = int(input("Enter number: "))
prime ... |
9ac22ed7b5c89ffa52f00ee754cec24541390dc8 | kinivera/Tableaux | /pares_c.py | 998 | 3.6875 | 4 | def complementol(l):
if len(l) %2 == 0 :
return l[len(l)-1]
else :
return "-"+l
def complemento(l):
if l.label =="-":
return l.right.label
else :
return "-"+l.label
#print(complemento(l))
def par_complementariol(h):
for i in range (len(h)):
... |
7e8e37733b2651606dbe7d7b82ba953996deeef9 | coffeblackpremium/exerciciosPythonBasico | /pythonProject/EstruturaRepeticao/exercicio011/exercicio011.py | 736 | 4.09375 | 4 | """
011)Altere o programa anterior para mostrar no final a soma dos números.
"""
numero_inteiro1, numero_inteiro2 = float(input('Digite um numero: ')), float(input('Digite outro numero: '))
lista = []
if numero_inteiro1 < numero_inteiro2:
while numero_inteiro1 <= numero_inteiro2:
numero_inteiro1 += 1
... |
e1b1e902888046edebf8b991454382365e49d6e7 | coffeblackpremium/exerciciosPythonBasico | /pythonProject/ExerciciosFuncoes/exercicio003/exercicio003.py | 333 | 4.34375 | 4 | """
003)Faça um programa, com uma função que necessite de um argumento.
A função retorna o valor de caractere
‘P’, se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
"""
def funcao_um_arg(arumento1):
if arumento1 > 0:
return 'P'
else:
return 'N'
print(funcao_um_arg(5))
|
a0dac0dbae5171d64a7e50fbbf566488745ce984 | coffeblackpremium/exerciciosPythonBasico | /pythonProject/ExerciciosFuncoes/exercicio006/exercicio006.py | 1,093 | 4.15625 | 4 | """
006)Faça um
programa que converta da
notação de 24 horas para a notação de 12 horas.
Por exemplo, o programa deve converter 14:25 em 2:25 P.M.
A entrada é dada em dois inteiros. Deve haver pelo menos duas funções:
uma para fazer a conversão e uma para a saída. Registre a informação A.M./P.M.
... |
7237a36927faa0ab72551efa17b2a29406e44f5a | coffeblackpremium/exerciciosPythonBasico | /pythonProject/EstruturaRepeticao/exercicio012/exercicio012.py | 474 | 4.1875 | 4 | """
012)Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10.
O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo:
Tabuada de 5:
5 X 1 = 5
5 X 2 = 10
...
5 X 10 = 50
"""
print(40 * '#', 'PROGRAMA DA TABUADA', 40 * '#... |
9cc44888b5214af1059098b4cf911d4134ebcdc5 | coffeblackpremium/exerciciosPythonBasico | /pythonProject/ExerciciosListas/exercicio012/exercicio012.py | 805 | 3.578125 | 4 | """
012)Faça um programa que receba a temperatura média de
cada mês do ano e armazene-as em uma lista. Após isto,
calcule a média anual das temperaturas e mostre todas as temperaturas
acima da média anual, e em que mês elas ocorreram (mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . ).
"""
import random
con... |
eb5e2dbf64c66be195eac7bd3ef4c0b13ffb2ed8 | coffeblackpremium/exerciciosPythonBasico | /pythonProject/EstruturaSequenciais/exercicio009/exercicio009.py | 352 | 4.21875 | 4 | """
009)Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
C = 5 * ((F-32) / 9).
"""
graus_fahrenheit = float(input('Digite a Temperatura em Fahrenheit: '))
celsius = 5 * ((graus_fahrenheit-32) / 9)
print(f'A Temperatura {graus_fahrenheit}F é Equivalent... |
103d6cad3f3863f86408db0e0823263524b8939a | wyy1234567/leetcode_problems | /binary_tree.py | 6,635 | 3.75 | 4 | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
#find max depth of a tree
def maxDepth(self, root):
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDep... |
2ad5f93ccc537d43a31faf7b35a9b4d7ecc80860 | rupran/adventofcode | /2015/11.py | 1,123 | 3.578125 | 4 | def increment(in_str):
rev_str = list(reversed(in_str))
out_str = []
overflow = True
index = 0
while overflow:
overflow = False
c = rev_str[index]
if c == 'z':
out_str.append('a')
overflow = True
else:
out_str.append(chr(ord(c) + 1)... |
30d0510cc8ac78a4c3ac50d49d7f56ae44b63d06 | rupran/adventofcode | /2020/9.py | 1,211 | 3.53125 | 4 | #!/usr/bin/env python3
import lib.common as lib
import time
def contains_sum(num_list, result):
for idx, x in enumerate(num_list):
if result - x in num_list[idx+1:]:
return True
# for idx2, y in enumerate(num_list[idx:]):
# if result == x + y:
# return True
... |
9193f531f97b47ee2bc766b475873e1c220e29c8 | rupran/adventofcode | /2020/3.py | 914 | 3.890625 | 4 | #!/usr/bin/env python3
import lib.common as lib
def make_grid(line_gen):
grid = []
for line in line_gen: # multi line input
grid.append(line)
return grid
def walk_grid(grid, step_right, step_down):
width = len(grid[0])
height = len(grid)
pos_x, pos_y, trees = 0, 0, 0
while True:
... |
7b624e67619ef19df0322f44ecd187569a83d12c | janina3/Python | /CS 1114/rec04.py | 1,874 | 4.15625 | 4 | def printAsUSDollars(moneyAmt, sign):
'''prints the amount in US dollars
sign must be either $ or USD (with space after USD)
'''
print ("%s%i" % (sign, moneyAmt))
def convertPesosToUSDollars(pesosAmt):
'''returns the pesos amount in dollars'''
conversionRate = .075
dollarCon... |
c8eb5ebf426a2d02fa47acbb8a8d9d6743acaacb | janina3/Python | /CS 1114/hw02.py | 425 | 4.21875 | 4 | def printTwoCharacters():
'''This function prints two characters a certain number of times depending on the distance between them in the alphabet'''
firstChar = str(raw_input("Enter a letter: "))
secondChar = str(raw_input("Enter another letter: "))
firstOrd = ord(firstChar)
secondOrd = ord(sec... |
ee29b49407134061a1928f15beb0ecd12b8f1f67 | janina3/Python | /CS 1114/rec08/rec06New.py | 8,331 | 3.65625 | 4 | #!/usr/bin/python
'''
Programmer: Janina Soriano
Username: js7187
Constraints: None
Assumptions: None
'''
from moneyChangerNew import quantityOfCoins
from moneyChangerNew import printAsCoins
import random
MANAGER_FIRST_NAME = "Manager"
MANAGER_LAST_NAME = "Here"
def displayWelcome():
'''displays the welcome... |
5c691494743f621f4d8d9ddcef60789f0ab10624 | janina3/Python | /CS 1114/rec12new.py | 2,180 | 3.890625 | 4 | #!/usr/bin/python
'''
cs1114
Submission: rec12
Programmer: Janina Soriano
Username: js7817
The purpose of this program is to replace spaces with strings and reverse it.
Assumptions: None
Constraints: None
'''
import os
def getInputFile():
'''The user chooses a file to input'''
validFilename = str(raw_in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.