blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9ecf1df964796de0c75126df6741b822dc1dd8b6 | falecomlara/CursoEmVideo | /ex066.py | 371 | 3.671875 | 4 | # leia varios numeros inteiros
# so vai parar quando for 999
# no final mostre quantos foram digitados e qual a soma deles
soma = media = num = cont = 0
while num != 999:
num = int(input('Digite um valor [999=parar] '))
if num == 999:
break
soma += num
cont += 1
media = soma/2
print (f'A soma ... |
888b36e1b17ec28ede219f675d23431dae84f3f7 | cpkimber/cs107 | /fib.py | 306 | 3.515625 | 4 | #! /home/cam/anaconda3/bin/python3
"""
file: fib.py
Cameron Kimber
date: 2018-10-24
Class: CSE107
Assignment:
"""
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return (fib(x - 1) + fib(x - 2))
def main():
n = 7
print(fib(n))
if __name__ == "__main__":
main()
|
4ed99b6e3f40be6e9de9bd557f9be66079f09760 | lianxiaopeng/python | /python/hello8.py | 559 | 3.796875 | 4 | #装饰器作业
import functools
from collections import Iterable
def log(p1):
#print("log")
#print(p1)
def log_f1(p1):
#print("log_f1")
#print(p1)
@functools.wraps(p1)
def log_f2(*args):
print("log_f2")
print(args)
p1()
return 1
return log_f2
def log_f3(*args):
print("log_f3")
print(args)
p... |
ace3da0ea87e1fb7f4da3a2660c2f5048cc6bdb9 | hrshtt/conf-ai-repo | /old_dir/poc/csv_generator.py | 2,500 | 3.828125 | 4 | import csv # import csv library
import pandas
import time_util
def append_to_csv( name, fields ):
with open(r'output/' + name + '', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
def dict_to_csv( name, csv_columns, dict_data ):
""" Creates csv file named name in current directory
... |
37fa710f1be54fa7f3eaef529b59a0c77142bb87 | SysOverdrive/real-estate-web-scrapper | /helper_functions.py | 896 | 3.59375 | 4 | import csv
def insert_headers_to_csv(csv_path, csv_file_name, headers):
csv_file = open(csv_path + csv_file_name, 'a', encoding="utf-8", newline='')
try:
with csv_file as f:
for header in headers:
writer = csv.writer(f)
writer.writerow(list(header.v... |
ed18162ff3f645766fd91f0e63941a7fb58ff664 | dreamchild7/python-challenge-solutions | /AnuOyeboade/phase1/BASIC/DAY5/Q31.py | 355 | 3.921875 | 4 | """
Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
"""
x = float(input("x = "))
y = float(input("y = "))
f = int(y/2)
def GCD(x,y):
GCD = 1
if x%y == 0:
return y
for a in range(f,0,-1):
if x%a == 0 and y%a == 0:
GCD = a
b... |
cb890e67626a9f252ffe2f06e552f4df754a0018 | ultrasuper/LearnPython | /playground/recursive_practice.py | 851 | 3.9375 | 4 | # -*- coding:utf-8 -*-
from random import randint
# # Calc the sum of the list
# l = [1,2,3,4]
# def recursive_sum(l:list) -> int:
# if len(l) == 0:
# return 0
# elif len(l) == 1:
# return l[0]
# else:
# return l[0] + recursive_sum(l[1:])
# result = recursive_sum(l)
# print(result)
# Calc the total number ... |
e7f46d84d6b9dd5fa57f127f3979a9d52de64856 | anatulea/Educative_challenges | /Arrays/05_find_second_maximum.py | 1,506 | 3.984375 | 4 | '''
Given a list of size n, can you find the second maximum element in the list? Implement your solution in Python and see if your output matches the correct output!
'''
# Solution #1: Sort and index O(nlogn)
def find_second_maximum(lst):
lst.sort()
if len(lst) >= 2:
return lst[-2]
else:
r... |
d86f2b4edbd30c2a96e14869cca83ddffd58bc8e | snowsaturday/SD_project | /main/number_game.py | 2,195 | 3.546875 | 4 | import random
number_pool = 20
# Диван
player_1_win_number = (1, 2, 3)
# клиент
player_2_win_number = (4, 5, 6, 7, 8, 9)
def player_1_pool_generator():
array = []
for i in range(0, int(number_pool) - int((number_pool / 100) * 30)):
x = random.choice(player_1_win_number)
y = random.choice(range(1, 99))
resu... |
e29935a75875e56345e323fd6c38b0bcbdb6ff95 | logs10/Exercism-Exercises | /reverse-string/reverse_string.py | 344 | 4.25 | 4 | def reverse(input=''):
"""Reverse a given string, return empty string if empty string passed"""
sorted_list = []
if input:
for index, char in enumerate(input):
sorted_list.append(tuple([index, char]))
sorted_list.sort(reverse=True)
sorted2 = [char[1] for char in sorted_list]
return ''.join(sorte... |
02d6ae4fa5feb7264d831dc94d55f0dd72308eff | svvay/CodeWars | /work_directory/Simple_Pig_Latin.py | 569 | 4.0625 | 4 | # Move the first letter of each word to the end of it, then add "ay"
# to the end of the word. Leave punctuation marks untouched.
text = 'Aaa ! Hallo a A world ?'
def pig_it(text):
pig_text = []
for latin in text.split():
if latin.isalpha():
pig_text.append(latin[1:] + latin[0] + 'ay')
... |
cbe9ffa732efdce8ed52eb2a8dcdcb56d5600764 | Tima222/algorithms | /code.py | 415 | 3.796875 | 4 | Задано натуральное число А (А?9999). Определить, что больше заданное число А или число, записанное этими же цифрами, но в обратном порядке.
a=int(input())
a=str(a)
b=a[::-1]
if int(a)>int(b):
print("Число А больше")
else:
print("Перевернутое число А больше")
|
c6aa37427c1b14a981799690a576b6df61a84943 | DishantNaik/Python_prac | /hackExe.py | 714 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 22:52:48 2020
Provlem description:Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
You are given scores. Store them in a list and find the score of the runner-up.
Difficulty Level: Eas... |
706872aad8e54dd03339b8e634834696d3a629d0 | dergaj79/python-learning-campus | /unit5_function/unit_5_hangman_5_5_1.py | 1,033 | 3.6875 | 4 | import pyfiglet
import sys
from pyfiglet import figlet_format
from pyfiglet import Figlet
custom_fig = Figlet(font='standard')
MAX_TRIES = 6
hangman_banner = pyfiglet.figlet_format("Hangman",font='standard')
print(hangman_banner,MAX_TRIES)
word = input ("Please enter a word: ")
print ("_ " * len(word))
print ()
letter... |
5a559c08cd64b4bdf746224a465de65fdcc9dacb | HatGuy68/practice | /GreatLearning/Python_ML/lesson-3.py | 826 | 3.6875 | 4 | import numpy as np
# Comparing Elements
# Finding common elements in arrays
print('\nFinding common elements in arrays')
n1 = np.array([10, 20, 30, 40, 50])
n2 = np.array([40, 50, 60, 70])
print('\n>>> np.intersect1d(n1,n2)')
print(np.intersect1d(n1,n2))
print('-'*30)
# Finding uncommon elements
print('\nFinding un... |
b1e759ed2a4f7bf882bc1003f957bd0ff5e0f147 | childe/leetcode | /continuous-subarray-sum/solution.py | 2,123 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/continuous-subarray-sum/description/
Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n... |
5dafd3dc47af284c5295ddebbe06ee8200ad8251 | nadiamarra/learning_python | /grades_average.py | 349 | 3.953125 | 4 | def calculate_average(assignment_grades):
'''(list of lists[str, num])->float
Return the average of grades in assignment_grades.
>>>calculate_average([['Assig1',80],['Assig2',90]])
85.0
'''
result=0
for item in assignment_grades:
result+=item[1]
return resu... |
7859818a79fff62f392011d6ac619180cd54233e | jaldd/python | /jichu/file/encode.py | 233 | 3.5625 | 4 | # -*- coding:utf-8 -*-
# Author:Dan Li
import sys
print(sys.getdefaultencoding())
s="你好"
s_gbk=s.encode("gbk")
print(s)
print(s_gbk)
print(s.encode())
print("utf8",s_gbk.decode("gbk").encode("utf-8"))
print(s_gbk.decode("gbk"))
|
17fe566dcbffd4e98127f81962df564d85c40b08 | Ale-Natalia/Games_Python | /battleship/game.py | 3,842 | 3.953125 | 4 | from players import Player, Human, Computer
import random
class Game(object):
def __init__(self, gameBoard1, gameBoard2, player1, player2):
self._gameBoard1 = gameBoard1
self._gameBoard2 = gameBoard2
self._player1 = player1
self._player2 = player2
@property
def Ships(self):... |
54e6a4bd7b0080ad2dbc2cfe6ae610cdd75877e2 | muneerqu/AlgDS | /Part1/03-Conditions/01-Syntax.py | 643 | 4.1875 | 4 | #
#
#
if False:
print('if True')
elif False:
print('elif False 1')
elif False:
print('elif False 2')
elif True:
print('elif False 3')
elif False:
print('elif False 4')
elif False:
print('elif False 5')
elif False:
print('elif False 6')
else:
print('neither True or False')
print('#######... |
f886849532196b81f6ebde575210419ce866b905 | Parya1112009/mytest | /re_cisco.py | 98 | 3.6875 | 4 | import re
str = "abb"
match = re.search(r'(.*)?',str)
print match.group()
#print match.group(2)
|
a31738e8dd336afde1656dfd827aa101561dffde | Xingyu-Zhao/algorithm020 | /Week7/Trie.py | 3,083 | 3.59375 | 4 | import collections
class Trie(object):
def __init__(self):
self.root = {}
self.end_of_word = "#"
def insert(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word)... |
66a6efc546c34cdf9947380e5ca5c52b77949917 | lc-orozco/Leisure-Programming | /Programming—Python/todo.py | 1,865 | 3.890625 | 4 | class Todo():
def __init__(self):
self.data = []
def add(self, chore):
self.data.append(chore)
def length_dec(self):
num = len(self.data)
pos_nums = []
while (num != 0):
pos_nums.append(num % 10)
num = num // 10
... |
bb35031d8fd1b9f04ed66fd01f5dfb16db767629 | wwstory/leetcode | /easy/29.两数相除.py | 1,332 | 3.640625 | 4 | # 超时
# class Solution:
# def divide(self, dividend: int, divisor: int) -> int:
# count = 0
# symbol = (dividend < 0) ^ (divisor < 0)
# dividend = abs(dividend)
# divisor = abs(divisor)
# while dividend >= divisor:
# dividend -= divisor
# cou... |
a77b1a6528d53df66b2ecf424a8bb666ed20a3ef | StephenwCrown/PayrollProject | /payroll.py | 839 | 4.125 | 4 | #Payroll#
#Name,Gross,Tax,Net#
#gross pay = hours worked x hourly pay rate#
#gross = total#
#tax = percentage taken off the gross#
#tax = static variable#
#name = user input#
#gross shaved off by tax end goal is net pay#
def payroll():
tax = float(0.2)
hourly_pay =10
hours_worked = 0
pay = hourly_pay *... |
8a43e2919e3ef2faae147c667aac71a9f2195583 | wapj/justpython | /chapter7/6_lotto_generator.py | 399 | 4.03125 | 4 | # 로또 생성기 만들기
import random
def get_lotto():
lotto = set()
while len(lotto) < 6:
num = random.randrange(1, 47)
lotto.add(num)
lotto_list = list(lotto)
lotto_list.sort()
return tuple(lotto_list)
if __name__ == '__main__':
lotto_set = set()
for x in range(5):
lotto_... |
3dd392c1b9a0e6978cb3729d3d61a92bdd6c5b23 | knutab/INF1100 | /gaussian2.py | 1,137 | 3.5 | 4 | import math
def gauss(x, m=0, s=1):
fx = 1./(math.sqrt(2*math.pi)*s)*math.exp(-0.5*(float(x-m)/s)**2)
return fx
"""
Chooses to create the table for the interval x=-5 to x=5 where x is
increased by one for each itteration.
"""
list1 = [] #list created to hold the x values
list2 = [] #li... |
69dc38355e8a9bb8fa9e9d8f58b125cef7c48e36 | aysegultopkara/Python---celcious-to-fahrenheit-converter | /Celcious to Fahrenheit converter.py | 135 | 3.671875 | 4 | celcious = int(input("Please enter celcious: "))
message = f"{celcious} celcious {(celcious * 9/5) + 32} Fahrenheit"
print(message)
|
45c41e91dd0afa53a76fbe470b763a617d59825c | hankyeolk/PythonStudy | /자료구조/graph.py | 778 | 3.71875 | 4 | #find friends
fr_info = {
'summer': ['john', 'justin', 'mike'],
'john': ['summer', 'justin'],
'justin': ['john', 'summer', 'mike', 'may'],
'mike': ['summer', 'justin'],
'may': ['justin', 'kim'],
'kim': ['may'],
'tom': ['jerry'],
'jerry': ['tom']
}
def print_all_friends(g, start):
qu = [] #앞으로 처리해야 할... |
d3be84b381b4a2961738ed00454f3475d953ecff | crossihuy/MyRepo | /better_calculator.py | 2,352 | 4.28125 | 4 | # tried to make +, -, *, / a variable both ways
# plus = "+"
# minus = "-"
# multiply = "*"
# divide = "/"
def main():
q = "y"
plus = "+"
minus = "-"
multiply = "*"
divide = "/"
def calc():
while True:
try:
print("***Please enter five numbers.***\n ")
num... |
06c9d074c709622b170cb41493734609f7f46a9a | tufts-ml-courses/comp137-dnn-20f-assignments | /assignment1/implementation.py | 1,478 | 4.25 | 4 | import tensorflow as tf
"""
This is a short tutorial of tensorflow. After this tutorial, you should know the following concepts:
1. constant,
2. operations
3. variables
4. gradient calculation
5. optimizer
"""
def regression_func(x, w, b):
"""
The function of a linear regression model
args:
x:... |
af89cffe4a2895db671b282b225e131aeb173296 | Ahed-bahri/Python | /upperReverse.py | 105 | 4 | 4 | # My solution
def uppercase_reverse(word):
return word.upper()
print (uppercase_reverse("banana")) |
4fb9a093a4c21d5c3065a32514f84138e2fbe94d | timsleeper/python_bootcamp | /day00/ex01/exec.py | 207 | 3.640625 | 4 | import sys
full_string = " ".join(sys.argv[1:])
rev_string = ""
for i in range(len(full_string)):
rev_string = rev_string + full_string[-(i + 1)].swapcase()
if rev_string != "":
print(rev_string)
|
8bc23f042af497717fadf582302a9c6301a28d0d | Sciencethebird/Python | /Plotting(Matplotlib)/Basic_Plot.py | 279 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3]
y = [3,4,5]
x1 = np.arange(0,2*np.pi, 0.01)
y1 = np.sin(x1)
plt.plot(x, y, label = 'line')
plt.plot(x1,y1, label = 'sin')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Simple Graph')
plt.legend()#圖例
plt.show() |
f15f4fd593d27bbcdb1d4fcb88ac5f46d4f80ab9 | Mrhairui/leetcode | /22_3.py | 586 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
tmp = head.next
head.next = self.swapPairs(... |
81747e76b2f6863dd0f86fb097305309a01c106c | mitubaEX/one_day_one_ABC | /ABC/001-050/023/B/main.py | 597 | 3.515625 | 4 | # 'a' + str + 'b'
# 'c' + str + 'a'
# 'b' + str + 'b'
n = int(input())
ans = input()
count = 0
turn = 0
s = 'b'
while True:
if len(s) > n:
print(-1)
break
elif ans == 'b':
print(0)
break
else:
if turn == 0:
s = 'a' + s + 'c'
turn += 1
... |
38afe5cbb98e93e8bbd2464479b9452bb2187e06 | LeTailleCrayon/pronote-hooks | /script.py | 806 | 3.515625 | 4 | # coding=utf-8
print("Bienvenue sur PronoteTools ! Version 1.0.0.0")
print("--------------------------------------------")
print("1. Calculer ta moyenne")
select = input("Pour commencer que veux-tu faire ? Saisis le numéro : ")
if(select=="1"):
print("Bienvenue sur le calculateur de moyenne ! Il te suffit... |
fa8af2f92490a3e57743662a01062fff898eba59 | aj-michael/NLP | /NLTKExperiments/mapper.py | 674 | 3.671875 | 4 | #!/usr/bin/env python
import sys from nltk.tokenize
import wordpunct_tokenize
def read_input(file):
for line in file:
# split the line into tokens
yield wordpunct_tokenize(line)
def main(separator='\t'):
# input comes from STDIN (standard input)
data = read_input(sys.stdin)
for tokens... |
2709ef9ecc5996e74482df9901de606c33cb79e0 | rh01/gofiles | /lcode1-99/ex28/generateTrees.py | 976 | 3.75 | 4 | # 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0: return [... |
54ff5c40e922d1763d1b298206f8d285df1de720 | bainco/bainco.github.io | /course-files/lectures/lecture13/conditionals/01_leap_year.py | 235 | 3.578125 | 4 | def print_days_in_february(year):
print('...')
print('February 26')
print('February 27')
print('February 28')
if year % 4 == 0:
print('February 29')
print_days_in_february(2019)
print_days_in_february(2020) |
5d004f112d0115ca33f0bc373f2d973f0e9a9a50 | Bachatero/AKOB | /pyscripts/week6.py | 677 | 3.546875 | 4 | #str1 = "Hello"
#str2 = 'there'
#bob = str1 + str2
#print bob
#x = '40'
#y = int(x) + 2
#print y
#x = 'From marquard@uct.ac.za'
#print x[8]
#x = 'From marquard@uct.ac.za'
#print x[14:17]
#print len('banana')*7
#greet = 'Hello Bob'
#print greet.upper()
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 20... |
4ad5ae44517d7c2fc98682a36a7b2b492b4f7694 | wangzhifengharrison/cs820-csp | /main.py | 4,404 | 3.515625 | 4 | # main.py
#
# AUTHOR
# ---------
# Jhonatan S. Oliveira
# oliveira@uregina.ca
# Department of Computer Science
# University of Regina
# Canada
#
#
# DESCRIPTION
# -----------
# This script is a utility for running all implemented search algorithms.
# After calling the script in a prompt command, the user can input cons... |
e61374feb5c523c3d9e78a15792a7f5f7e67bc88 | hrsh25/Sentiment_Analysis | /main.py | 668 | 3.671875 | 4 | print("<------------------------------Political Tweet Analyser------------------------------>")
print("Have an idea of the political scenario of our country by checking out the sentiments\nof the latest 1000 tweets concerning the three major political parties \n(BJP,Congress,AAP)")
input_ = input("Press 1 for BJP\nPr... |
7894c996e9ddeb8cc376a9382a4d8e0175b0d1d4 | sushovanisalive/python_codes | /testing_file.py | 781 | 3.96875 | 4 | import timeit
# def mean_list(in_list):
# sum=0
# for entry in in_list:
# sum = sum + entry
# return (sum/len(in_list))
# print(mean_list([2,5,8,0,8,7]))
def read_file_text(filename):
with open(filename, "r") as myfile:
data = myfile.read()
return data
def reverse... |
b3f2d1f00bf6c34be93e249e8692a06f02099605 | ccsreenidhin/Practice_Anand_Python_Problems | /Learning_python_AnandPython/Module/problem11.py | 330 | 4.40625 | 4 | #Problem 11: Write a python program zip.py to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.
import zipfile
def zipf(n,f,ft):
zi=zipfile.ZipFile(n, mode = 'w')
zi.write(f)
zi.write(ft)
zi.close()
zipf('zipped','test.txt'... |
0d3c05f56d956e941999951b0f55212cdc6ee13a | 360skyeye/kael | /examples/micro_service/caculate_service/__init__.py | 391 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version:
@author:
@time: 2017/5/25 16:07
"""
def add(a, b):
return t(a) + y(b)
def minus(a, b):
return t(a) - y(b)
def multiply(a, b):
return t(a) * y(b)
def t(a):
return a
def y(b):
return b
class TMP(object):
def __init__(self):
... |
89ed5fd328bc714eefda095559a219f59258b044 | abarson/warm-up-project | /opponentV3.py | 1,279 | 3.609375 | 4 | import random
class Opponent():
def __init__(self, deck, difficulty, laidDown,):
self.deck = deck
self.difficulty = difficulty
self.laidDown = laidDown
self.books = 0
self.recentCard = None
self.lastAskedFor = None
##depending on difficulty, the Opponen... |
02ef78ef290d4fa7815e6cdb7a2ffc321f3cab94 | dPacc/Web_Dev_Practice | /ContextManagers/cm.py | 796 | 3.65625 | 4 | from contextlib import contextmanager
# Context Manager Using Class
# class Open_File():
#
# def __init__(self, filename, mode):
# self.filename = filename
# self.mode = mode
#
# def __enter__(self):
# self.file = open(self.filename, self.mode)
# return self.file
#
# ... |
c0604b70dec7d863602fe6ba930050c0d7c87379 | RodiMd/Python | /FeetToInches.py | 829 | 4.21875 | 4 | #Feet to Inches
#accept argument in feet and return value in inches
argInFeet = int(0)
foot_to_Inch = int (12)
feet = int(0)
def main():
argInFeet = input('Enter a value in feet ')
argInFeet = int(argInFeet)
# totalInches = feet_to_inches(argInFeet)
print(feet_to_inches(argInFeet))
... |
494e15685671bdcafad49af38559132535724204 | gabrysb/210CT | /Question14.py | 1,226 | 3.90625 | 4 | """ Implement BFS and DFS traversals for the above graph. Save the nodes traversed in sequence to a text file."""
def DFS(self, vertex):
""" Uses a stack so it goes all the way down a branch and stores the values that can then be popped once the nodes have all been found. This particular DFS is done pre-order."""
... |
a900abeee21159c7c9c138711a9098738e6b88c7 | spoorthi198/Python_QA | /Linklist/linklistdemo.py | 2,124 | 4 | 4 | class Node:
def __init__(self,data,next):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beggining(self,data):
node = Node(data,self.head)
self.head = node
def print_the_ele(self):
if self.head is... |
b2e2b96eca9dc9bd734f9625c1ee3747d966ecee | tClown11/Python-Student | /test/textday/days13(20180401)/第七章__装饰器.py | 1,427 | 3.734375 | 4 | #装饰器基础知识
'''@decorate
def target():
print('running target()')
'''
'''#把装饰器通常把函数替换成另一个函数
def deco(func):
def inner():
print('running inner()')
return inner # deco返回inner函数对象
@deco
def target(): # 使用deco装饰target
print('running target()')
print(target()) #调用被装饰的target其实会运行inner
print(... |
b12e2a4fc6e2ea3aec431617cf1204e52905e2a0 | LarynQi/LarynQi.github.io | /assets/fa20-csm/mentor09.py | 2,592 | 3.953125 | 4 | class Baller:
all_players = []
def __init__(self, name, has_ball = False):
self.name = name
self.has_ball = has_ball
Baller.all_players.append(self)
def pass_ball(self, other_player):
if self.has_ball:
self.has_ball = False
other_player.has_ball = True
... |
3db5dd4287977329769878095a83e22b04db9984 | CosmicDisorder/web-caesar | /caesar.py | 497 | 3.9375 | 4 | from helpers import alphabet_position, rotate_character
import string
alphabet = string.ascii_lowercase
def encrypt(text, rot):
new_text = ''
for char in text:
new_text += rotate_character(char, rot)
return new_text
def main():
from sys import argv, exit
if argv[1].isdigit():
text ... |
552bc60993c8bf52f8abd3e72e5bb26cefd702d5 | ohbarye/euler | /python/problem0001.py | 348 | 4.46875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def is_multiple_of_3_or_5(n):
return n % 3 == 0 or n % 5 == 0
print sum(filte... |
0cccfd233335d8aad637cf270c520418e594638d | emersonsemidio/python | /Desafio63.py | 352 | 3.90625 | 4 | print('-' * 10)
print('Sequência de Fibonacci: ')
first = 0
second = 1
soma = first + second
cont = 3
a = int(input('Quantos termos você deseja mostrar? '))
print('{} {}'.format(first,second),end=' ')
while cont <= a:
cont = cont +1
soma = first + second
print('{}'.format(soma),end=' ')
first = second
... |
0cdc081608207ee5de462e75153596d96fdd1eb6 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_41/205.py | 3,145 | 3.71875 | 4 | #! /usr/bin/env python
import pprint
import sys
if __name__ == "__main__":
data = open(sys.argv[1])
test_count = int(data.readline().strip())
for count in range(0, test_count):
number = data.readline().strip()
#print number
numbers_used = {}
for char in number:
... |
ab91ad4b6d3de344fb124a176f90f05baad0a11a | karthik4636/practice_problems | /arrays_and_strings/rotate_array.py | 489 | 3.6875 | 4 | #https://leetcode.com/problems/rotate-array/
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
k = k % len(nums)
... |
2f5d44fca06c651bbe6d95fe0d54c68aa99fbcda | phoenix9373/Algorithm | /2020/SWEA_문제/순열_반복문.py | 172 | 4.0625 | 4 | for a in range(3):
for b in range(3):
if a == b:
continue
for c in range(3):
if a == c or c == b:
print(a, b, c) |
10403d2e4058a56fb5a37ea803ae7266d0ae2846 | juneharold/PH526x_UPFR | /hw2sol.py | 2,810 | 3.734375 | 4 | # Ex 1
import numpy as np
import random
def create_board():
board = np.zeros((3,3), dtype = int)
return board
board = create_board()
# Ex 2
def create_board():
board = np.zeros((3,3),dtype=int)
return board
board = create_board()
def place(board,player,position):
if board[position] == 0:
b... |
891650b4106eeab0af928beb32e8b6cfce61ab77 | chabberwock/PlaystoreDownloader | /playstore/util.py | 1,174 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
import itertools
import logging
import time
logger = logging.getLogger(__name__)
def retry(delays=(1, 2, 3, 5), exception=Exception):
"""
Retry decorator.
Retry the execution of the wrapped function/method in case of specific errors, for a specific number
of ti... |
cc2eca507366a487558dd2aec4566f75b037a1e2 | TimRock23/Algorithms | /greedy_algorithms/H.py | 140 | 3.640625 | 4 | def h(string):
word = string[-1]
return len(word)
if __name__ == '__main__':
string = input().split(' ')
print(h(string))
|
884cb2e8c977a466621f6aec0cf2fb0d7ae0ab42 | Pizzabakerz/codingsuperstar | /python-codes/codes/10.conditions_example.py | 463 | 4.15625 | 4 | '''
if
else
else if => elif
SYNTAX:
if condition:
body of if
elif condition:
body of elif
elif condition_2:
boy of elif
.
.
.
elif condition_n:
boy of elif
.
else:
body of else
'''
a = 10
if a< 10:
print(True)
if a>10:
print... |
cf01ff1323204462e2fa67521743293db030d45f | elertan/HR-Minigames | /Minigames/Quinten/Game.py | 1,221 | 3.625 | 4 | from Minigame import Minigame
class QuintenGame(Minigame):
def __init__(self):
super(QuintenGame, self).__init__("QuintenGame", "Quinten", 4)
# When a player starts this minigame
def enter(self):
raise NotImplementedError("You need to override the enter method on your minigame.")
... |
516fba080f10955ba00763bda4cdc4ca289d5530 | LuoJiaji/LeetCode-Demo | /Contest/weekly-contest-153/A.py | 898 | 3.921875 | 4 | class Solution(object):
def distanceBetweenBusStops(self, distance, start, destination):
"""
:type distance: List[int]
:type start: int
:type destination: int
:rtype: int
"""
l = sum(distance)
# print(l)
if start > destination:
... |
4ab3a2adbfb7c552bac33d4f8a6c094fc3fb1f04 | Josmi27/project-3-Destination-Travel-App | /tests/unit_tests.py | 2,633 | 3.546875 | 4 | import unittest
import chatbot
import models
import jokeapi
from chatbot import *
class ChatbotTests(unittest.TestCase):
def test_help(self):
response = chatbot.Chatbot.response(self, "!! help ")
self.assertEqual(response, "Want me to say more? I respond to: !! about, !! say <something>, !! quotes... |
b64b002718fd0fc328c1c06e8c22649a36b0d1ec | saparia-data/data_structure | /geeksforgeeks/greedy/3_Job_Sequencing_Problem.py | 1,956 | 4.125 | 4 | '''
Given a set of N jobs where each job i has a deadline and profit associated to it.
Each job takes 1 unit of time to complete and only one job can be scheduled at a time.
We earn the profit if and only if the job is completed by its deadline. The task is to find the maximum profit and the number of jobs done.
Job... |
58e421fa960f046ecb339c3ae0d8371b3df104db | csany2020c/Demo | /b_csillagok.py | 2,057 | 3.921875 | 4 | from turtle import Turtle
from turtle import Screen
from random import Random
class TurtleOOP:
turtle = Turtle()
screen = Screen()
def hold(self):
self.turtle.speed(200)
self.turtle.penup()
self.turtle.goto(-200, 20)
self.turtle.left(200)
self.turtle.pendown()
... |
cd7a383d467abd38aceb4c57b6a5e4ccf0f4544a | podoynitsyn-va/GEEKBRAINS-Learning | /2.OOP_in_Python/Regular_Expressions/someone/Theme_01/main.py | 4,622 | 4.03125 | 4 | # Тема 1. Регулярные выражения
# ======================================================================================================================
# 1. Получите текст из файла.
# Примечание: Можете взять свой текст или воспользоваться готовым из материалов к уроку.
# Вспомните операции с чтением файлов и не забуд... |
df4814cee56f0c37722b9e998062b9fcd7be795c | RenegaDe1288/pythonProject | /lesson5/mission2.py | 254 | 3.84375 | 4 | temp = int(input('Введите температуру: '))
if 100 >= temp >= 0:
print('Оптимальная температура')
else:
print('Предупреждение: температура вне допустимых границ')
|
bcbd292bc2aaf8298926e2ae3f4a5b5e8ff28420 | seraphbotty/hello-world | /variable examples.py | 648 | 4.1875 | 4 | age = 15 #set the users age
age_in_month = age * 12 #computer the user age in months
age_in_days = age_in_month * 30 #computer the approximate age in days
student_name = 'Jim' #create a string for user name
print("Student", student_name, "is", age, "years old")
#print("Student %s is %d years old" % (student_nam... |
6027715b93c92550637f94a0771f06098d196a0a | jbmilgrom/practical-algorithms-and-data-structures | /dynamic_programming/maximum_sub_array/test.py | 892 | 3.875 | 4 | from dynamic_programming.maximum_sub_array.method import maximum_subarray
print('############################')
print('Testing maximum_sub_array')
print('############################')
max = maximum_subarray([-1, 3,2,6, -3, 4,5])
assert max == 17, "expected {}; received: {}".format(17, max)
max = maximum_subarray([-... |
099ff128c5a78b62ab92c7076995baeb5240bdbf | yamadatarousan/python_training | /03.py | 665 | 3.5625 | 4 | # coding:utf-8
# 日本語出力したいときの呪文
import codecs, sys
sys.stdout = codecs.getwriter('cp932')(sys.stdout)
import string
# "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
# という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
row_str = "Now I need a drink, alcoholic of cours... |
868d3a05dcc63290299fde3411369fa67f490252 | tmu-nlp/NLPtutorial2019 | /kiyuna/tutorial00/word_frequency.py | 2,435 | 3.921875 | 4 | '''
ファイルの中の単語の頻度を数えるプログラムを作成
'''
from collections import defaultdict, Counter
def count_word_freq(path, trans=str):
""" Word Frequency Counter
指定されたファイルについて,単語の分布を返す.
Args:
path: 対象とするファイルのパス
trans: 単語を
大文字と小文字の区別をなくしたいとき ->「lambda x: x.lower()」
Returns:
defaultd... |
c454efbc05cf6d8231e6807312be9d71ccd9cf58 | BruceHi/leetcode | /month12/findNumberIn2DArray.py | 1,823 | 3.84375 | 4 | # 剑指 offer 04. 二维数组中的查找
# 与 240. 搜索二维矩阵 II searchMatrix 一样
from typing import List
class Solution:
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# if not matrix:
# return False
# m, n = len(matrix), len(matrix[0])
# i, j = m-1, 0
# # whi... |
a77a2e519eecd0d3b044eeb23d8260c72a2d7219 | michael-yanov/hillel | /lesson_4/task_3.py | 535 | 3.984375 | 4 | '''
Пользователь вводит, отдельно, строку `s` и один символ `ch`. Необходимо выполнить поиск в строке `s` всех символов `ch`.
Для решения можно использовать только функцию `find`(rfind), операторы `if` и `for`(while).
'''
s = input('Enter the string: ')
ch = input('Enter symbol for searching: ')
l = 0
for i in range(... |
0bc7afa837e73723ca846b077b279b6046421aef | puskarkarki/PythonBeginners | /Pyntive/challenge1.py | 539 | 4.125 | 4 | """ Question 1: Given a two integer numbers return their product and
if the product is greater than 1000, then return their sum"""
""" Solution 1"""
num1 = 20
num2 = 30
product = num1 * num2
sum = num1 + num2
if(product > 1000):
print(product)
else:
print(sum)
""" Another way to do this program """
def mul_o... |
a7c51df52dc968c896d8d8bc47e6ab2282a1bec7 | jilljenn/tryalgo | /tryalgo/knuth_morris_pratt.py | 2,395 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Find the length of maximal borders by Knuth-Morris-Pratt
jill-jênn vie, christoph dürr et louis abraham - 2014-2019
inspired from a practical lesson (TP) from Yves Lemaire
"""
# pylint: disable=undefined-variable, unused-argument
# snip{ maximum_border_length
def m... |
a7387c1ecff82382aa75b75b113e62f318c73d32 | MiguelCF06/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 556 | 4.25 | 4 | #!/usr/bin/python3
"""
Prints a square with "#"
"""
def print_square(size):
"""
An argument size type integer
representing the size of the square
"""
if isinstance(size, bool):
raise TypeError("size must be an integer")
elif not isinstance(size, int):
raise TypeError("size mus... |
7749d78f6d84763c2a3e0818df50f98de794822d | derick-droid/pirple_python | /forloops.py | 810 | 4.3125 | 4 |
# syntax for for loop
words = "hello world"
letters = []
for letter in words:
print(letter)
if letter == "o":
print("what a wonderfull letter")
letters.append(letter)
print(letters)
# looping through the list created
for element in letters:
print(element)
print()
# definig a list containing nu... |
2eafa24a19dcc1628ac6f27169bc1fc880175bd3 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/if-else-demo.py | 3,075 | 4.15625 | 4 | # 1- Kullanıcıdan isim, yaş ve eğitim bilgilerini isteyip ehliyet alabilme
# durumunu kontrol ediniz. Ehliyet alma durumu en az 18 veğitim durumu
# lise ya da üniversite olmalıdır.
# name =input('Ad: ')
# age = int(input('Yaş: '))
# edu = input('Eğitim Durumu: ')
# if (age > 18):
# if (edu == 'lise') or (e... |
d0eeabdd01fcafc4d955d4f264d4378d6c710a40 | maggieyam/LeetCode | /surrounding_regions.py | 1,492 | 3.546875 | 4 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
onEdge = set()
for row in range(m):
for col in range(n):
if board[row][... |
faaa5ade71425044bca736f167d2efd0b36da8d3 | vikki1107/ProjectPy | /academic/caesarCipher.py | 2,686 | 4.625 | 5 | #!/usr/bin/env python
"""
One of the first known examples of encryption was used by Julius Caesar. Caesar needed to provide written instructions to his generals, but he didn't want his enemies to learn his plans if the message slipped into their hands. As a result, he developed what later became known as the Caesar Cip... |
7d49038a4f922cf5ad21960aab9432bcb184e61b | LambdaOvO/alien-invasion | /ship.py | 3,482 | 3.78125 | 4 | """飞船模块"""
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
""""""
def __init__(self, ai_settings, screen):
"""初始化飞船并设置其初始位置"""
super().__init__()
self.screen = screen
self.ai_settings = ai_settings
# 创建图片对象(加载飞船图片)
# 获取图片和屏幕的外接矩形(rect对象/矩形对象... |
c16782569c7ca14943a67e0dcc68a8ee356114ab | brfabri/ALGORITMOS-21.06.17- | /04-loja_tinta.py | 232 | 3.75 | 4 | area=float(input("Insira o tamanho em metros quadrados da área a ser pintada: "))
if area%54==0:
latas=area/54
else:
latas=(area/54)+1
total=latas*80
print("Quantidade de latas: %2.d. Total: R$%2.f"%(latas,total))
|
ee759d393595cfd9b2492054e2094f05c65c8b54 | parulkyadav/python-basic-programs | /fab2.py | 229 | 3.71875 | 4 | def fab(num):
a=0
b=1
print(a)
print(b)
for i in range(num-2):
t=a
a=b
b=t+a
print(b)
if __name__=="__main__":
num=int(input("Enter the number of series : "))
fab(num)
|
bdca9da765f2eef70833708f0995c3c2b0765280 | sunyy3/Using-Python-Plot | /python-plot.py | 5,601 | 4.1875 | 4 | # In the begining, import several useful modules in python
import matplotlib.pyplot as plt
import numpy as np
# Example 1: simple scatter plot
# For start, let's plot a simple line, and customize your figure and axis.
x = [0, 1, 2, 3, 4, 5, 6, 7]
y = [0, 1, 4, 9,16,25,36,49]
z = [0, 1, 2, 3, 4, 5, 6, 7]
# hav... |
9037c013e1d4e235d52e6c587bd38c436cb40985 | Carolyn95/Leetcoding-Journey | /shell_sort.py | 706 | 3.5 | 4 | # shell sort implemeting in python
import pdb
def shell_sort(bef_list):
n = len(bef_list)
# 初始步長
gap = n // 2
while gap > 0:
for i in range(gap, n):
# 每个步長進行插入排序
temp = bef_list[i]
j = i
# 插入排序
while j >= 0 and j - gap >= 0 and bef_li... |
e8c09c9f46546edc58a0dfd959a92ee68dde31ca | CardinisCode/learning-python | /Python_Code_Challenges/movie_collection/main.py | 647 | 3.609375 | 4 | class Solution:
def run(self, n, m, movies):
#
# Write your code below; return type and arguments should be according to the problem's requirements
movie_stack = list(range(n, 0, -1))
books_on_top_list = []
for movie in movies:
movie_index = movie_stack.index(mo... |
c714468db692122bfec0f57b553e2456c6ba0f9e | Zokhira/basics | /files_exceptions/exeptions.py | 942 | 3.921875 | 4 | # Exception Handling - handle situations
filepath = "C:/dev/2020-fall/basics/data1/students.txt"
try:
print('trying block started...')
with open(filepath, 'a') as students:
print("writing to the file..")
students.write(f"\nSergey")
with open(filepath, 'r') as students:
lines = stu... |
b3d2af93aa88d622e912d7bb4b5d060620192c23 | sanchezolivos-unprg/t06_sanchez | /sanchez/multiple18.py | 790 | 3.765625 | 4 | import os
# MOSTRAR VALORES
nombre=""
t_grado_fahrenheit=0.0
# INPUT
nombre=os.sys.argv[1]
t_grado_fahrenheit=float(os.sys.argv[2])
# OUTPUT
print("################################")
print(" TEMPERATURA DE UNA PERSONA ")
print("################################")
print("NOMBRE:", nombre)
print("TEMPERATURA EN GRAD... |
af94d4585ae56941fe3baae5aea3f3b1382fc087 | mmaina48/ProjectManagement | /excrise2.py | 796 | 4.03125 | 4 | tasklist= [23,"jane",["leesso 23",560,{"cureency":"kes"}],987,(76,"john")]
# determin type of tasklist
print(type(tasklist))
# print "kes"
kesl=tasklist[2]
kesl1=kesl[2]
print(kesl1["cureency"])
# print 560
print(tasklist[2][1])
# use fxn to find len of tasklist
print(len(tasklist))
# change 987 to 789 using inbui... |
43fe21581ec0e6aaf7d89f7eb361dffb1ddbe5e1 | CompPhysics/ComputationalPhysics2 | /doc/LectureNotes/_build/jupyter_execute/boltzmannmachines.py | 72,230 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Boltzmann Machines
#
# Why use a generative model rather than the more well known discriminative deep neural networks (DNN)?
#
# * Discriminitave methods have several limitations: They are mainly supervised learning methods, thus requiring labeled data. And there are tasks ... |
2bc0fc20668dba0dcb8cb0d61402a202060f54d7 | bambrow/python-programming-notes | /io_basics/01_io.py | 251 | 3.671875 | 4 | #!/usr/bin/env python
# coding:utf-8
with open('example.txt', 'r', encoding='utf-8', errors='ignore') as f:
for line in f.readlines():
print(line.strip())
with open('example2.txt', 'w', encoding='utf8') as f:
f.write('Hello World!') |
09cce81030257893e2b182f92f768d7e3086ab56 | rhofset/Fizz-Buzz | /FizzBuzz.py | 307 | 4.0625 | 4 | # 1 - 100, if multiple of 3 and 5 print FizzBuzz, if multiple of 5 print Buzz and if multiple of 3 print Fizz
for x in range(1,101):
if x % 3 == 0 and x % 5 == 0:
print('FizzBuzz')
elif x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print('Buzz')
else:
print(x)
|
38b9b7e23f8da67f5f75fa57a0ecfcbb1abcf2ef | HankChou0811/123 | /123.py | 132 | 3.71875 | 4 | N = 10
height = input('請輸入身高:')
weight = input('請輸入體重:')
print('therefore u say that', height, weight)
print(N)
|
c962fddaae1c251f1e94512b49e80b7aa5408aad | mwoinoski/crs1906 | /examples/ch08_examples/subprocesses/encrypt.py | 2,163 | 3.5625 | 4 | """
encrypt.py - uses the subprocess module to encrypt multiple files in parallel.
"""
import getpass
import os
import sys
import subprocess
# The run_openssl function will be the target of the processes that we create
def run_openssl(file, pw):
"""
Use openssl to encrypt some data using AES (Advanced Encryp... |
22f949649423ee94c042f01482d5f7b80a4eefc5 | kaveriumadi/project | /list.py | 775 | 3.875 | 4 | l1 = [1,2,4,3,6,7,8,4,3]
print(l1)
l1[4]
print(l1[4])
print(len(l1))
l1.append(22)
print(l1)
l1.append(25)
print(l1)
l1.insert(2, 45)
print(l1)
l2 = [4,6,2,8]
l1.extend(l2)
print(l1)
l1[2]=20
print(l1)
l1.sort()
print(l1)
l1.reverse()
print(l1)
l1.sort()
print(l1)
l1.pop()
print(l1)
l1.pop(1)
print(l1)
l3... |
62a541185a25a9385a724326133f10e9fbce7d01 | freakraj/python_projects | /for_loop.py | 164 | 3.765625 | 4 | # i=1
# while i<=10:
# print(f"Hello word : {i}")
# i+=1
for i in range(0,11):
print(f"gautam word {i}")
print("\nTHIS YOUR SHOP ") |
0964edb8a9e9a9c07d02a6374f50b06777c9c3a8 | bunshue/vcs | /_4.python/__code/Python GUI 設計活用 tkinter之路/ch3/ch3_35.py | 404 | 3.640625 | 4 | # ch3_35.py
from tkinter import *
root = Tk()
root.title("ch3_35") # 視窗標題
Colors = ["red","orange","yellow","green","blue","purple"]
r = 0 # row編號
for color in Colors:
Label(root,text=color,relief="groove",width=20).grid(row=r,column=0)
Label(root,bg=color,relief="... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.