blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
066e4a8c8cd98e84148b1901c38ab75d60f7fd6f | RobotnikUTFPR/memes | /sPonGebOBmEme.py | 247 | 3.90625 | 4 | def to_weird_case(string):
string = list(string)
ns = []
for i in range(len(string)):
if i%2 == 0:
ns.append(string[i].upper())
elif i%2 == 1:
ns.append(string[i].lower())
return "".join(ns)
|
1149d9452fa4a7754b777d56e27e46d479d67f7f | akashg94/NumOfWordsLetterDigit | /NumOfWordsLetterNum.py | 517 | 4.1875 | 4 | numOfWords = 0
numOfLetters = 0
numOfDigits = 0
# taking input from user
text = input("Enter a text of numbers : ")
for x in text:
x = x.lower()
if x >= 'a' and x <= 'z':
numOfLetters = numOfLetters + 1
elif x >= '0' and x <= '9':
numOfDigits = numOfDigits + 1
elif x == ' ':
... |
9d61b07e771be812bbde45e2ca145ad18f2a11ab | jhwsx/liaoxuefeng_python_tutorial_learning | /python_2/func_args_test.py | 201 | 4.21875 | 4 | # 可接收一个或多个数并计算乘积
def product(*numbers):
result = 1
for number in numbers:
result *= number
return result
print(product(1, 2, 3))
print(product(1, 3, 5)) |
83ef0a7f33a456c687d5eb4df61f1c13252a7052 | DanRyanIrish/tools | /games/prime_numbers.py | 868 | 4.125 | 4 | """
Accepts in int from command line.
Generates list of all prime numbers up to that number.
"""
import argparse
import math
def get_prime_numbers(number):
"""
Generates prime numbers
:param number: Number up to which prime numbers should be produced
:returns: list of prime numbers
:rtype: list
... |
c165193e4793473029a664d18aa6fb0df496a5d6 | Jia35/-Python-Tutorial | /file/code/hw06.py | 211 | 3.875 | 4 | num = int(input('請輸入一個數:'))
x = 0
num_all = 0
while num_all <= num:
x += 1
num_all += x
print(x)
print(num_all)
print('-----')
print('當數值到',x,'時,總和會超過',num)
|
cb0f84e81d218bf8465581a9581430d0d37736af | aparna2345/python--samples | /sample20.py | 380 | 3.96875 | 4 | array = {}
i = 0
a = input("Enter the number of students: ")
while i < int(a) :
i=i+1
print(f"enter the name of student {i}:",end=" ")
student = input()
print(f"enter the mark of student {i}:",end=" ")
mark = input()
array[student] = mark
print(array)
print("enter the name of student to retriv... |
570fdc50459f0b1373d5a3762c96fee4ab7d883f | Keith-Choung/Doubly-Linked-List | /DoublyLinkedList.py | 5,442 | 4.25 | 4 | # A node of the doublly linked list
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Doubly Linked-List class
class DoublyLinkedList:
def __init__(self):
self.head = None
self.... |
4a78be3d0e6e6ac46ef65401dd85f6bc47cbbb13 | Ratatou2/Algorithm_Study | /01. 백준 2562 문제.py | 785 | 3.875 | 4 | #빈 리스트를 하나 만들어줌(여기에다가 저장할 것임)
my_list = []
#아홉개의 숫자를 받는다고 하였으므로 range에 9를 넣는다
#이는 따로 변수로 만들어줘도 깔끔함
#사용자의 input을 9번을 받고 그것을 매번 아까 만든 my_list에 넣어줌
for _ in range(9):
user_input = int(input())
my_list.append(user_input)
#max_v는 my_list내에서 최대값이고
#position은 my_list내에서 max_v의 위치값이다
#position을 따로 만들어준 이유는 인덱스 번호값은... |
303b3c50278921c0d1c0afe970af4a47ca521026 | calvertwong/PythonExercises | /intermediate/text_functions.py | 437 | 4.15625 | 4 | # a) Using .format() function to convert integer to string
def stringify_digit(digit):
return '{}'.format(digit)
# b) Reverse string using a slice that steps backwards
def reverse(text):
return text[::-1]
# c) Since this requirement is the same as (a), I am calling function from (a) to get the result
def stringif... |
f9f56d0f0ba9171a89c4d0d402735bfea73a0e15 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_202/185.py | 4,841 | 3.53125 | 4 | """
Problem D. Fashion Show
Each cell in the grid can be empty (which we represent with a . character) or
can contain one fashion model. The models come in three types, depending on the
clothing style they are wearing: +, x, and the super-trendy o. A cell with
a + or x model in it adds 1 style point to the show... |
85d7e0baeea16d05c3b271a5eadf4c846d893c07 | Aiooon/MyLeetcode | /python/sort_HeapSort.py | 1,924 | 3.890625 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# 堆排序
import random
import time
def heapSort(arr):
if arr == None or len(arr) < 2:
return
for i in range(len(arr)):
heapInsert(arr, i)
size = len(arr)
size -= 1
swap(arr, 0, size)
while size > 0:
heapify(arr, 0, size)
... |
9a97e0516d3a655f899f4fa303fa60c816cd9da1 | ThomasjD/Factpalinime | /Palindrome.py | 562 | 4.09375 | 4 | #Determine if a word is a palindrome
#word input
word = input("Enter a word.")
#w,o,r,d 1 to 4
drow = ""
for x in range(1, len(word) + 1):
drow += word[-x]
drow= str(drow)
print (drow)
if drow == word:
print (f"This {word} is a palindrome!!!")
print (f"{word} == {drow}.")
else:
print (f"{word} != {dr... |
8d535285238d53523e70c741f6076ab07926d75f | Joanne-Cheng/Connect4 | /Project_ConnectFour.py | 2,371 | 3.859375 | 4 | board = []
def makeBoard():
for i in range(6):
row = []
for j in range(7):
row.append(' ')
board.append(row)
def printBoard():
tracker = ['0','1','2','3','4','5','6']
for row in board:
r = " | "
for item in row:
r += item + " ... |
2696fb4289f4db5ac6e967b1bda1f33af8c349a0 | priya006/pythonexcercise | /DocString.py | 263 | 3.609375 | 4 | import pickle
def square(n):
'''Takes in a number n, returns square of n'''
return n*2
#__doc__ attribute prints the documentation
print(square.__doc__)
# prints the pickle module documentation
print(pickle.__doc__)
if __name__ == "__main__":
pass |
65efb238ada2f4e2f91f8efddc67eb5f92e38563 | Utkarsh731/first | /numericdiamond.py | 279 | 3.6875 | 4 | n=int(input("enter the number of rows in diamond"))
q=1
a="1"
l=[]
for i in range(n,1,-1):
print(" "*(i-2),end=" ")
q+=1
print(a,end=" ")
l.append(a)
a=a+str(q)
a=str(q)+a
print()
for j in range(1,n-1):
print(" "*(j+1),end="")
print(l[n-j-2])
|
d2f89d552729b8f46c0e77b0b6aea3b2d841a9e3 | Prime0220/Python | /Challenge/30120이화준_도전문제13.py | 242 | 4 | 4 | # ### [도전문제 13] ###
# 다음과 같이 출력되도록 중첩된 반복문을 사용해 작성하세요
# A
# AA
# AAA
# AAAA
# AAAAA
# AAAAAA
for a in range(7) :
for b in range(1, a+1) :
print('A', end='')
print()
|
fed08b2188a263636fa144c79b477eede2030567 | daniel321/fresaGl | /objects/model/extractor/coordenateValueExtractor.py | 544 | 3.640625 | 4 |
class CoordenateValueExtractor(object):
""" used to extraxt the value of a coordinate from a G-code line
ej: findCoordValue(self,'g00 x23 y35','x') -> 23 """
def findCoordValue(self,line,coord):
""" gets the value of the coordinate from a G-code line """
posCoord = line.find(coord,0,len(line))
... |
86746177ec9a0255621fb8004c2d3e28668d4f11 | audreyemmely/Python-programming | /ListaDeExercícios/EstruturaSequencial/ex08.py | 377 | 3.96875 | 4 | '''
Faça um programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
'''
ganhoHora = float(input('Quanto você ganha por horas? R$ '))
horasTrabalhadas = float(input('Quantas horas você trabalhou neste mês? '))
print('Total salário:... |
838684c5343aa5632b0e2b5775f2f2c653528148 | nathanleiby/advent-of-code-2018 | /6.py | 2,811 | 3.609375 | 4 | with open('6-input', 'r') as f:
data = f.read().strip() # read and remove whitespace
example_input = """1, 1
1, 6
8, 3
3, 4
5, 5
8, 9"""
"""
Your goal is to find the size of the largest area that isn't infinite.
FINITE iff none of its boundaries are at the edge of the map
"""
DEBUG = False
def print_square(s):
... |
a2a5597eac6cfcc1f63e079fc1d4de5d5dc636da | r-kill/python | /passwordAnalysis/passwdTime.py | 4,490 | 3.640625 | 4 | from time import *
# guideline flags
hasEightChar = False # may not need this variable
hasUpperCase = False
hasLowerCase = False
hasNums = False
hasSpecialChar = False # one of these: ? . [ ] { } - _ ! * + ~
# make sure passwd doesn't contain %
# initial assumption is that password does NOT contain a %
noPercent = ... |
570db1a47f2683b0b2ebfef480d53453836baa65 | BishopMcNallyHS/Sample-Text-Game | /main.py | 3,966 | 3.953125 | 4 | """
PLEASE DO NOT EDIT THIS
Final project
text adventure game
...
author : mr Truong
p1 basic scenes
p2 fight
p3 add new scene
"""
from random import randint
name = ""#variable for character name
monster1HP = randint(10,20)
playerHP = 100
inventory = ["cheap sword"]
gold = 0
def startGame():#first scene of the advent... |
89d6bd4d61f9b4622354a705a1f819537c0dc710 | lancenie96/VPN | /util.py | 2,082 | 3.671875 | 4 | from queue import Queue
import threading
MQ = Queue() # queue for talking to main thread
Q = Queue() # queue for talking to network thread
_halt = False
_cond = threading.Condition(threading.Lock())
_halt_thread = None
_auto = False
"""
Message that is placed on the queue to be consumed by network threads
"""
class ... |
2806d05c4b501c63c9848409afd28a00def99da0 | Durgesh15/python- | /list/lst4.py | 134 | 3.625 | 4 | #removing element from 0,4,5:
def remove_ele(word):
print(remove_ele(['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'])) |
f96d541e6eddc74af4dc593b79474df398f7ed0c | abnerrf/cursoPython3 | /2.pythonBasico/aula10/aula10.py | 212 | 4.09375 | 4 | """
CONDIÇÕES IF, ELIF E ELSE - ESTRUTURA
"""
if False:
print('Verdadeiro.')
elif True:
print("Agora é verdadeiro.")
elif False:
print('Mais uma verdadeira')
else:
print('Não é verdadeiro.') |
79279d117ae70aa4b77b9b2c5aae9dec6922c676 | Hariom868/college-review | /college review test/searchaniteminfile.py | 310 | 4.03125 | 4 | fname = input("Enter the file name: ")
try:
fhand = open(fname)
except:
print("File cannot be opened: ", fname)
quit()
search = input("Enter the character you want to search: ")
count = 0
for line in fhand:
if line==search:
count = count + 1
print(search, " appears ",count , "times" )
|
db2121c187d20cc2aa003c54567d3cd45b9d4229 | Romko97/Python | /Softserve/studi_tkinter/LineTK.py | 2,241 | 3.703125 | 4 | from tkinter import *
import time
root = Tk()
canvas = Canvas(root, width = 500, height = 500)
canvas.pack()
# the line
# canvas.create_line(0,0,500,500)
# the rectangle
# x1=10
# y1=10
# x2=50
# y2=50
# for a in range(4):
# x1 = x2+5
# x2 = x1+40
# canvas.create_rectangle(x1,y1,x2,y2)
#canv... |
220397dade1ec26db670458ac3b28a43c5ba0d02 | sanjeevrohila/_ | /codestyles/poll.py | 2,701 | 3.609375 | 4 | def poll(predicate, msg, timeout, sleep, *args, **kwargs):
"""
This method accepts a method which returns True or False
If the expectation is other than True/ False
then expects the expected output for a time given in the timeout.
An extractor method is also passed if the output is required
to ... |
8854937c78ab1cdf7ce556eec00eebbf032ab7c6 | Lucas-Moura-Da-Silva/Python-Estudo | /Exercícios de Python/atv032.py | 884 | 3.90625 | 4 | #valores
valor = float(input('Qual é o valor da casa? R$ '))
salario = float(input('Qual é o seu salário? R$ '))
anos = int(input('Em quantos anos você ira pagar? '))
#prestação
mensal = float(valor/(anos*12))
#cores
cores = {'limpa': '\033[m',
'vermelho': '\033[1;31m',
'amarelo': '\033[1;33;45m',
... |
26d873685e3edee302aa6f75bc7243ad7d28a344 | kemar1997/TSTP_Programs | /Challenges/Ch13_Challenges/Challenge3.py | 885 | 4.3125 | 4 | """
3. Create a class called Shape. Define a method in it called what_am_i that prints "I am a shape" when called. Change
your Square and Rectangle classes from the previous challenges to inherit from Shape, create Square and Rectangle
objects, and call the new method on both of them.
"""
class Shape:
def what_... |
0a146b0f86657de6c2d0b63022f8c7ba6643eb0b | YanpuLi/LeetCode-Practice-and-Algo | /cracking the code interview/C2/2.6.py | 375 | 3.90625 | 4 | def find_beginning(l):
fast, slow = l.head, l.head
# find the meeting point
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
#check if it is a circular list
if fast == None or fast.next == None:
return None
#find the beginning point
fast = l.head
while fast != s... |
a2358f8d5d5341d9295afe640d755a48c6515634 | krskelton/Python-Projects | /Challenges/quizCode.py | 365 | 3.890625 | 4 | def getName(name = ""):
name = askName(name)
print("Thank you, welcome {}!".format(name))
def askName(name):
go = True
while go:
if name == "":
name = input("Please enter your name:\n>>> ")
if name != "":
go = False
return name
... |
a66197455396c14a5f6ce2257f7b44e24424ea3b | brackengracie/CS-1400 | /Budget.py | 430 | 3.921875 | 4 | def main() :
print("Hello, can I help you save?")
print("It is quite easy. Just follow")
print("the steps given.")
fixed=input("Please enter number of fixed expenses -> ")
fixed=int(fixed)
score_list=[]
for i in range(fixed) :
expense=input("Now type what fixed expenses you have.")... |
9a41fb18487565adb1a2593197dcb951265115b0 | AhlemKaabi/holbertonschool-higher_level_programming | /0x0B-python-input_output/5-save_to_json_file.py | 225 | 3.65625 | 4 | #!/usr/bin/python3
'''Save to a Json file
'''
import json
def save_to_json_file(my_obj, filename):
'''Save to a Json file
Returns:
'''
with open(filename, 'w') as file:
json.dump(my_obj, file)
|
d4f824fdedc2fe9a5500cdeaba29ec74be9b9839 | certik/test3 | /tests/basic/vargs.py | 124 | 3.5625 | 4 |
def myfunc(a,b,*c):
print a
print b
for i in c:
print i
myfunc(1,2)
myfunc('a','b','c','d')
myfunc(3,4,5,6,'hello')
|
e753f80697447dc7bd74f0e6a5554571e22b59bd | ArnoBali/book_exercises | /Week 2/Chapter 5/5-7.py | 885 | 4.375 | 4 | '''
5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list .
• Make a list of your three favorite fruits and call it favorite_fruits .
• Write five if statements . Each should check whether a certain kind of fruit is in y... |
25656ad7e9908a861c9b3ea1ada9af9525d9438f | yaHaart/hometasks | /Module16/02_line/main.py | 140 | 3.5 | 4 | line1 = list(range(160, 176 + 1, 2))
line2 = list(range(162, 180 + 1, 3))
line1.extend(line2)
line1.sort()
print(line1)
# зачёт! 🚀
|
ec15b6af70324ca8654594ec71bec89f7e1dd6e8 | kaz101/panda-book | /BGP3D/Chapter08/Examples/MenuClass_01.py | 12,366 | 3.625 | 4 | ''' Menu Class
This class is designed to create a very
versatile, expandable menu structure.
The core concept of the class is to accept
lists of functions and lists of arguments
for them, so that it can use the methods
of other classes to complete the operations
it needs to.
The __init__ method and the init... |
1ea795c29e791b19e282f698db6cbeaa11674929 | scottbing/SB_6000_NLP | /ReverseMadLibs/venv/progressbar.py | 891 | 3.78125 | 4 | # importing tkinter module
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Progress bar widget
progress = Progressbar(root, orient=HORIZONTAL,
length=100, mode='determinate')
# Function responsible for the updation
# of the progress bar value
def bar():... |
5ee563d28b17edd6222fa4d1910935ccc2a5fbd9 | matbc92/learning-python | /functions/function_defualt.py | 311 | 3.59375 | 4 | # é possivel atribuir um valor padrão a um parametro, para o
# caso de o usuario não o especificar,
# isto é feito no momento que o parametro é introduzido,
# por meio da inclusão de (=) adjunto do valor pardão desejado
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5)
|
591881e029ba10f359d7fa3e63a8400cd05fd925 | vrastello/Data-Structures---all | /CS 261/HW1/assignment1.py | 23,091 | 3.890625 | 4 | # Course: CS261 - Data Structures
# Student Name: Vince Rastello
# Assignment: Assignment 1, Python Fundamentals Review
# Description: 14 problems reviewing python fundamentals and emphasizing speed and optimization. Unable
# to use any built in data structures or methods, must use attached class only.
i... |
3f008bef14f768a1f1d5d0cc8ff35eae2c8632e2 | csalerno1/Python5 | /module5.py | 203 | 3.578125 | 4 | mycode = """
def code(x,y,z):
return (x*y*z)+2
print(code(2,4,6))"""
exec(mycode)
def stringinmiddle(string, word):
return string[:6]+word+string[6:]
print(stringinmiddle("small large","medium"))
|
854c653f76f27b65cbfd773c7cae076c884c4603 | Valar207/Bootcamp_PYTHON | /d00/ex09/guess.py | 1,138 | 4.1875 | 4 | import random
rnb = random.randint(1, 99)
print("This is an interactive guessing game!\
\nYou have to enter a number between 1 and 99 to find out the secret number.\
\nType 'exit' to end the game.\nGood luck!")
guess = input("What's your guess between 1 and 99?\n >>")
t = 1
while (guess != "exit"):
if (guess.isnum... |
3a9bd4d5ab1714a4d22c7e228b8a0ff23a70792b | wiky2/mytestproject | /To MAC/CIS 192- Spring 2010 课程/builtin_fun.py | 478 | 4 | 4 | #!/usr/bin/python
print "-"*10
print "zip"
print "-"*10
#zip()
# zip togeather two sequences
for i,j in zip(range(10),range(9,-1,-1)):
print i,j
print "-"*10
print "map"
print "-"*10
#map()
#applys a function across a sequnce
def divide_by2(x):
return float(x)/2
for i in map(divide_by2,range(10)):
p... |
4d8eab4eb0c21995434a1bbd7808ab024a8b6e58 | jaeheeLee17/BOJ_Algorithms | /Level6_1dArray/2577.py | 375 | 3.71875 | 4 | def count_numbers(A, B, C):
num = str(A * B * C)
cnt_array = [0] * 10
for n in num:
cnt_array[int(n)] += 1
return cnt_array
def main():
A = int(input())
B = int(input())
C = int(input())
result_array = count_numbers(A, B, C)
for i in range(len(result_array)):
print(r... |
b42b034c3144e8642d7a2322619bcec6a5dbe97a | MaxLikhachev/StringAlgorythms | /algorythms/PrefixZValues.py | 784 | 3.65625 | 4 | from StrComp import StrComp
def PrefixZValues(s):
n = len(s)
l, r = 0, 0
zp = [0] * n
for i in range(1, n):
# zp.append(0)
if i >= r:
zp[i] = StrComp(s, n, 0, i)
l = i
r = l + zp[i]
else:
j = i - l
if zp[j] < r - i:
... |
48ad46fccd57ee5184b6ed8cf90c3daa3f19fbdb | fandi-peng/Project_Euler | /code/euler35.py | 1,008 | 3.65625 | 4 |
def n_rotation(n):
s = str(n) + str(n)[:-1]
l = len(str(n))
r = []
for i in range(l):
r.append(int(s[i:i+l]))
return r
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def find_candidate():
candidates = [2, 5]
valid_digit =... |
54d9f7ed9cc9b3f0ba90d42ba6d9d26fcbff64eb | AnassBOUIRDI/ENSEEIHT | /1A/PIM/TP1/somme_python.py | 1,319 | 3.828125 | 4 | # Garibal Florian, Groupe A
# Programme permettant de tester la fonction somme
## somme : int*int -> int
## Calculer la somme des entiers compris entre 2 entiers naturels m et n
## Paramètre m : entier naturel, la borne inférieure de l'intervalle
## n : entier naturel, la borne supérieure de l'intervalle
#... |
5f0448ec19b5c4c5bbd3953c1e056ec24b4a0086 | r-azh/TestProject | /TestPython/test_set_list_tuple_dictionary_comprehension/test_del.py | 1,003 | 4.3125 | 4 | __author__ = 'R.Azh'
# Deletion of a name removes the binding of that name from the local or global namespace
# Assigning None to a name does not remove the binding of the name from the namespace
class Foo:
pass
foo = Foo()
del foo # instead of foo = None
print("################### del in lists ###########... |
a89c7d1c381366c1ecd1bb4ecd6b0d656c86a68e | Aasthaengg/IBMdataset | /Python_codes/p03252/s031126471.py | 618 | 3.703125 | 4 | #!/usr/bin/env python3
from collections import defaultdict
def II(): return int(input())
def MII(): return map(int, input().split())
def LII(): return list(map(int, input().split()))
def main():
S = input()
T = input()
s1 = {}
t1 = {}
for i, (s, t) in enumerate(zip(S, T)):
if s in s1 an... |
5a43fe49de7e581ca2c2c1f47c76b87fc5ddd41e | jakobotten/CP1404-Practicals | /Prac02/print_from_file.py | 101 | 3.765625 | 4 | name_file = open("name.txt","r")
for line in name_file:
print("Your name is {}".format(line))
|
c72614c6ba2f2f83b794b6e3dd47b4499c1b64b2 | StepanHoncharov21/Battle-Simulation | /main.py | 1,418 | 3.5625 | 4 | import random
import time
from src.LogicCharecter import Computer,Human
Computer = Computer()
Human = Human()
def game_loop():
"""Игровой цикл.
Случайным образом выбирается игрок который будет совершать действие
"""
inGame = True
while inGame:
randomNumber = random.randint(0,1)
if ra... |
89c8fa79b7db6f19b71b7c1d394dc131495a9ddb | SagarikaNagpal/Python-Practice | /tiny_progress/list/Python program to print all even numbers in a range.py | 355 | 3.921875 | 4 | def listCreate():
l = []
start = int(input('Enter lower number, List starts from: '))
stop = int(input('Enter higher number, List ends here: '))
for i in range (start,stop+1):
if i%2==0:
l.append(i)
return l
def main():
first = listCreate()
print("list: ",first )
if __... |
db512a100db5e02815ab156dafb9aef0f5c6d46b | afcarl/ChangeTracker | /inputChecker.py | 5,207 | 4.09375 | 4 | """
This file creates a checker for all input parameters
"""
import os
class InputChecker():
def __init__(self, args, config):
#settings are stored here
self.settings = {"paper": "", "dir": "", "name": "", "source": ""}
self.args = args
self.config = config
def check_config... |
98aba232a4b082de1e3591cadd50f44285de34bd | SuperQiQi0701/StoneHenge-and-SubtractSquare | /state_of_game.py | 11,303 | 3.875 | 4 | """
State of game module.
classes State, SubstractSquareState and ChopsticsState.
"""
from typing import Any
from typing import List
class State:
"""
To keep track of the game state, or a snapshot of the current
situation in the game.
=== Attributes ===
is_p1_turn - whether it is p1's turn, if n... |
251e6f51a39b44517c1cb4b3e171322ff06fb3fc | erictroebs/nn_quantization_hashing | /locality_sensitive_hash.py | 1,222 | 3.59375 | 4 | from random import uniform
from math import tan, pi
def generate_line():
alpha = uniform(0, pi)
m = tan(alpha)
return m
def generate_lines(count):
return [generate_line() for i in range(0, count)]
def hash(point, lines):
return [point[1] >= point[1] * line for line in lines]
... |
ec54269b54b9a45778b6935249f622e5dc75911d | 33marvil/Is_Prime_TDD_Python | /primes.py | 774 | 4.09375 | 4 | # def is_prime(number):
# """Return True if *number* is prime."""
# # if number < 0: #
# # return False
# #
# # if number in (0, 1):
# # return False
# if number <= 1:
# return False
#
# for element in range(2, number):
# if number % element == 0:
# re... |
aa5121db26d60b1b61f922f2bb5a79bab1d17e5e | Noonjik/Homework-1- | /hw1_p3.py | 186 | 3.75 | 4 | #arithmetic progression
a1=int(input('the 1-st member is: '))
a2=int(input('the 2-nd member is: '))
n=int(input('the index: n= '))
print ("an=", end = " ")
print (a1+(n-1)*(a2-a1)) |
a1c602ded9bd9bedb036cc37074bc75eee5bad44 | syedbasitahmad/260756_daily_commit | /ques_5.py | 416 | 3.984375 | 4 | #price of pizzas problem
error_msg="plz type correct input"
def take_input():
no_of_pizzas=int(input())
return no_of_pizzas
def price(no_of_pizzas):
if (no_of_pizzas<=0):
return error_msg
if (no_of_pizzas%2==0):
return no_of_pizzas*120
else:
return no_of_pizzas*130
i... |
2e98f58d6dfead0093995ec7375f5be84dc78da6 | guolikai/mypython | /day01/count.py | 377 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf8
import re
File = raw_input("请输入要查找的文件:")
Word = raw_input("请输入要查找文件内的单词:")
count = 0
Find = file(File,'r')
for s in Find.readlines():
li = re.findall(Word,s)
# count = 0
if len(li) > 0:
count = count+len(li)
print '你要查找文件的单词总数是:'
print count
Find.close()
|
43936daed6553c76aef7c0f3c8286e60e4fee116 | JangYoungRok/kiwoom_project | /material/basic/section02/unit02/01.py | 173 | 3.953125 | 4 | data = [1, 4, 2, 5, 3]
# 데이터를 직접 정렬
data.sort()
print(data)
# 정렬된 리스트를 리턴
result = sorted(data, reverse=True)
print(result)
print(data)
|
661fe53c1157aa5b8859c7b577f642e0ca8499dc | kk31398/guvi-project | /check_factorial.py | 73 | 3.703125 | 4 | num = int(input())
a=1
while (num>0):
a=a*num
num=num-1
print(a)
|
09e3ddeec9cdbb602717c7101c4ae7bd0ff55e05 | Alzyo/Python-basis-code | /exercise/一元二次方程求解_函数.py | 341 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# math.sqrt() 开方
import math
def quadratic(a, b, c):
d=b**2-4*a*c
if a==0:
x=-c/b
return('%.2f' %(x))
elif d<0:
return('no answer')
else:
m = (-b+math.sqrt(d))/(2*a)
n = (-b-math.sqrt(d))/(2*a)
return(m,n)
print(qu... |
31925b2fc14ca2a290b3c423f79f3cadd2c9d259 | frotein/tree-exercise | /tree.py | 1,166 | 4 | 4 | # takes in a list representation of a treeLevel and returns the list representation of the next level
def computeNextLevel(tree):
lst = [] # the list being returned
if len(tree) == 1 : # if this is the beginning, return the second level
lst.append(tree[0])
lst.append(tree[0])
else:
i = 0
while i < len(tree)... |
04f16ba11e11f1b4c3afc71c62dd203bf8fa8007 | wendreof/pyExercises | /03_usingModules/ex019.py | 409 | 3.84375 | 4 | # [PT-BR] Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele,
# lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
from random import choice
students = []
for item in range(4):
a = str(input('Type the student number {}: '.format(item+1)))
st... |
3a164c62641bd8b5da57940399002a607132ec0e | JohanVikman/advent2017 | /day3.py | 2,299 | 4.375 | 4 | """You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:
17 16 15 14 13
18 5... |
c00bb5ab5c20b73cfdb49caaee2a46f355a4debf | camelkyhn/Tools-For-Text-Files | /toLowerCase.py | 268 | 3.6875 | 4 | #File is in the project directory
def toLowerCase(filename):
with open(filename, 'r') as fileinput:
for line in fileinput:
line = line.lower()
print(line)
if __name__ == '__main__':
filename = input()
toLowerCase(filename)
|
18810ed39d54a0aed41a9d9d9afd388075e8dc2f | RajeshKumar-1998/python-web | /Thlock.py | 1,571 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Rajesh
#
# Created: 31-12-2019
# Copyright: (c) Rajesh 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/... |
1b7eb78fc85f494b19ff40a5d3dddc90fb65c461 | Strix2109/py | /strixbenzene.py | 277 | 3.953125 | 4 | # Drawing Rainbow Benzene
# Python Turtle Programming
# @strix_21
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%6])
t.width (x/100 + 1)
t.forward(x)
t.left(59) |
3605491c6fad44ebbfd6dd8d87efe8633a45cc9f | mangesh-kurambhatti/Python-Programms | /mix_up_string1.py | 320 | 4 | 4 | def mix_up(str1,str2):
first_two_str1=str1[:2:]
first_two_str2=str2[:2:]
print("string is:",first_two_str2+str1[2::])
print("string is:",first_two_str1+str2[2::])
def main():
str1=eval(input("Enter the string1 :"))
str2=eval(input("Enter the string2 :"))
mix_up(str1,str2)
if __name__=='__main__':
main()
|
30f4af02bf8632fc2e7b87a641c115cbc529e5c2 | momacs/pram | /src/sim/xx-dining-phil/sim.py | 4,251 | 3.515625 | 4 | '''
A simulation of the Dining Philosophers problem demonstrating the allocation and release of shared resources. The five
philosophers ('p') and five forks ('f') are distinguished by approximate clock position.
This simulation does not run in a concurrent manner; if it did, the use of synchronization mechanisms woul... |
ef41dfe3de91305b90ce30de36057175993d2dd1 | yelimahn/skku-computing_thinking-2020 | /Midterm Exam in Your Home/2.py | 3,034 | 3.53125 | 4 | #Midterm Exam in Your Home_2_안예림
#각 돌은 순서대로 1~N까지 번호가 붙어 있으며,2차원 배열을 선언
n=int(input("돌의 개수 >> "))
d=[[0 for clo in range(2)] for row in range(n)]
#각 돌에는 점수가 적혀있다.
for i in range(n):
d[i][0]=int(input("돌의 쓰여질 점수 >> "))
#돌을 밟을 때마다 돌에 쓰여진 점수를 누적해서 더해야 되고,
#돌의 합이 최대가 되도록 징검다리를 건너고 싶다.
score=0
def finish_n(i,d,scor... |
2dc21e59a50c0c4c10c6f349e569ad5839a7a3cd | ljia2/leetcode.py | /solutions/dp/357.Count.Numbers.with.Unique.Digits.py | 1,138 | 3.859375 | 4 | class Solution:
def countNumbersWithUniqueDigits(self, n):
"""
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
... |
c5bc584af144e137b6c78f661c54bc2c5b24f603 | pearlselvan/PythonPractise | /DS/DefaultDictionary.py | 1,888 | 4.3125 | 4 | '''
defaultdict
defaultdict is a dictionary like object which provides all methods provided by dictionary
but takes first argument (default_factory) as default data type for the dictionary.
Using defaultdict is faster than doing the same using dict.set_default method.
With respect to initilization :
=============... |
49659f6b971f7eb7f035ca4af52d753a1e25e748 | mengchizhang/MITx-6.00.1x | /Week1/L1test.py | 554 | 4.0625 | 4 | x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("you've enter the same number")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("Done")
name = "Vincent"
greet = "Hello there"
h... |
caaaab342a3e2e1856cfee85c80047fe536bfd38 | bazhydlouskim/Lab6 | /Lab6.py | 4,142 | 3.625 | 4 | # -*- coding: cp1251 -*-
#LAB6 Python starter code
#imports go here
import MySQLdb
import _mysql
#code goes here
buffer = "true"
def oneQuery():
try:
# Open connection to the database
db = MySQLdb.connect(host="localhost",user="root",passwd="GdP31_6#03bbm",db="Wiki")
x = db.curs... |
9a61e043e367204d62c6381a4fb0cacfcc878985 | ricnef2121/python | /Fundamentos/variables.py | 129 | 3.828125 | 4 | x=5
y=3
z=x+y
print(z)
w=z
print(w)
"""con la funcion id(), podemos saber la direccion
de memoria de la variable"""
id(z)
id(w)
|
38cb1bdb3d67cfd63deb4bfd5f532fc0d9c9cb2f | justien/lpthw | /ex33a_WhileDef.py | 1,257 | 4.125 | 4 | # -*- coding: utf8 -*-
# Exercise 33: While Loops
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 33: While Loops"
print
print
# While loops can go on forever, like a droning guest at a... |
43ff58fe12e8f50b5434d7d8504c384974230ec0 | leekyunghun/bit_seoul | /keras2/keras69_lr.py | 1,414 | 3.703125 | 4 | weight = 0.5
input = 0.5
goal_prediction = 0.8
lr = 0.01 # 0.001 # 0.1 / 1 / 0.0001 / 10
for iteration in range(1000):
prediction = input * weight # 목표치에 향해 가는 예측값
error = (prediction - goal_prediction) ** 2 # 예측값과 목표값과의 오차
print(iteration)
print("Error : " + str(e... |
a4e0d2b6120366d74e772f2f2fe4189b4e17e09d | MeztliVal/Python_Codes | /TK_INTER/Gird1.py | 518 | 3.828125 | 4 | from tkinter import *
root = Tk()
label = Label(root,text="Nombre Muy largo")
label.grid(row=0, column=0, sticky="e", padx=5, pady=5)
entry = Entry(root)
entry.grid(row=0, column=1, padx=5, pady=5)
entry.config(justify="right") #state="disabled" para desactivar el campo
label2 = Label(root,text="Apellidos")
label2.... |
d0960cbd6c4e25c07bfea1059beddbb8b2e631ec | khaleefakt/Hangman | /hangman.py | 2,368 | 3.875 | 4 | # hangman.py
import random
def get_secret_word(word_file="/usr/share/dict/words"):
with open(word_file) as f:
good_words = []
for i in f:
i = i.strip()
if len(i) <= 6: # No short words
continue
if not i.isalpha(): # No punctuation
... |
e400b2a17f92ce529c6a3aa4e45d87e2d8398b9b | jungting20/algostudy | /stack/9012.py | 375 | 3.734375 | 4 |
import sys
r = lambda: sys.stdin.readline().strip()
def isValid(s):
n = len(s)
cnt = 0
for x in s:
if x == '(':
cnt += 1
else:
cnt -= 1
if cnt < 0:
return "NO"
if cnt == 0:
return "YES"
else:
return "NO"
n = int(r())
... |
8b6fa9e4626e4723e1c9c160f680740ca319b321 | daviswu/selfteaching-python-camp | /exercises/1901100370/1001S02E04_control_flow.py | 338 | 3.984375 | 4 | print('打印九九乘法表')
for x in range(1,10):
for y in range(1,x+1):
print(x,'*',y,'=',x*y,end='\t')
print()
print()
print('打印奇数行的乘法表')
x=1
while x<10:
if x%2==0:
print()
print()
else:
for y in range(1,x+1):
print(x,'*',y,'=',x*y,end='\t')
x=x+1 |
ab4295e4a9ab1cbc1548cc355791e16e9d193d79 | wwyys/echarts | /echarts/python/作业/05.py | 176 | 3.65625 | 4 | import numpy as np
x=np.matrix([[1,2,3],[4,5,6]])
sum=x.sum()
print(sum)
#逆矩阵
import numpy as np
x=np.matrix([[1,2,3],[4,5,6],[7,8,9]])
print(x)
y=x.transpose()
print(y)
|
69439067202d3e08a52e1143067b1d472d598774 | kindix/luts_traning | /part17_methods.py | 1,179 | 3.515625 | 4 | # global
X = 99
def func(Y):
#local
Z = X + Y
return Z
print(func(1))
def func():
#local
global X
X = 101
func()
print(X)
x,y = 1,2
def all_global():
global z
z = x + y
all_global()
print(z)
var = 99
def local():
var = 0
def glob1():
global var
var += 1
def g... |
88bd6e0c0196b8ac4119d7f1634ce78e43f16271 | LuisCastellanosOviedo/python3 | /my-python-project/day4_randomisation_and_python_list/russian_roulette_bill.py | 292 | 3.9375 | 4 | import random
names_string = input("Give me everybody's names, separated by a comma.")
list_of_people = names_string.split(",")
print(f"{list_of_people[random.randint(0,len(list_of_people)-1)]} should pay the bill MUAHAHAHAHAHA")
print("or easy way ")
print(random.choice(list_of_people)) |
2c772f9efcb0ec3e041993c073bc56fa288710f3 | shen-ee/LC | /code/831.py | 923 | 3.53125 | 4 | class Solution(object):
def maskPII(self, S):
"""
:type S: str
:rtype: str
"""
rstr = ""
if "@"in S:#邮箱
#print("email")
S = S.lower()
name1 = S.split('@')[0]
name2 = S.split('@')[1]
S = name1[0]+"*****"+name... |
bee4bf033fa5f3815a407c324bfbc9660bcbca53 | ZacCui/leetcode | /21_merge_two_sorted_lists/zac_cui_21.py | 1,106 | 3.953125 | 4 | #!/usr/local/bin/python3
'''
Author: Zac Cui
Created Date: 2019-03-24 18:32:26
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ... |
064f1a4df77a05f3b5bbf59a1937cbc20e2442a9 | HongyingLee/leetcode | /otherO/isPerfectSquare.py | 491 | 3.78125 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author: Hongying_Lee
# @Time: 2020/4/30
# @Name: isPerfectSquare
def isPerfectSquare_My(num):
for i in range(num // 2):
if i ** 2 == num:
return True
return False
def isPerfectSquare(num):
l,r = 1, num
mid = (l + r) / 2
while l < r:... |
c8e6df6d14f3a546695c427a0ab27e5553975009 | krisbhei/INF2310 | /Programmering/Python/aritmetikk.py | 213 | 3.8125 | 4 |
a = -2
b = 3
# Addisjon:
print("a + b =", a+b)
# Subtraksjon
print("a - b =", a-b)
# Multiplikasjon
print("a * b =", a*b)
# Divisjon
print("a / b =", a/b)
# Opphøying
print("a opphøyd i b = a**b = ",a**b)
|
3a125f9b6df1fff1e89a21045d75a9b893df6589 | CraigMorris1986/cp1404_practicals | /prac_01/menu sequence generator.py | 1,877 | 4.28125 | 4 | # This is a sequence generator with a menu.
def main():
starting_number = int(input("Please enter a starting number : "))
ending_number = int(input("please enter an ending number : "))
while ending_number < starting_number:
print("Ending number must be greater than the starting number.")
... |
d71e904095037f6452261a1b8d01630129654976 | qmnguyenw/python_py4e | /geeksforgeeks/python/expert/8_1.py | 5,389 | 3.890625 | 4 | Python | Linear Programming in Pulp
Linear Programming (LP), also known as **linear optimization** is a
mathematical programming technique to obtain the best result or outcome, like
maximum profit or least cost, in a mathematical model whose requirements are
represented by linear relationships. Linear program... |
891c0b9a23c26cdde41c7a25cde1d3313a5a54c4 | frycast/allshapley | /generative.py | 2,990 | 4.4375 | 4 | """
This is just me working my way through the keras tutorial
for researchers:
https://keras.io/getting_started/intro_to_keras_for_researchers/
I've read up to the heading 'Layer gradients'
"""
# conda create -n tf tensorflow
# conda activate tf #(or switch to interpreter in env tf)
# %%
import tensorflow as tf
fro... |
85b892cc79f3bde140d797b6c63ec9b559f125be | SahibBir/Python-Journey | /BankAccounts.py | 12,045 | 4.1875 | 4 | """
Submitted By: SAHIB BIR SINGH BHATIA
Student ID: 201547831
COMP 517 - Assignment 3 - 2020-21 - JAN21 - CA Assignment 3 - BANK ACCOUNTS
"""
# Importing Random and Datetime modules
import random
from datetime import datetime
class BasicAccount(object): # Basic Account class
"""acNum – the number of the accoun... |
48682dd9f8fec8d814459122d568be2df3ea2cb2 | matrix-revolution/algorithms | /factorialTrailingZeroes.py | 760 | 3.640625 | 4 | class Solution(object):
def factorial(self, n, val_store):
if len(val_store) <= 0:
val_store.append(0)
if n == 0:
return val_store[n]
if n == 1:
val_store.append(1)
return val_store[n]
return n * self.factorial(n-1, val_store)
def ... |
0555a97abc346720be808bff6629ba83fbc240fd | Hearen/AlgorithmHackers | /TangHongyin/longest_substring_without_repeating_characters.py | 690 | 3.515625 | 4 | class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dict = {}
start = 0
length = 0
for i in range(len(s)):
if s[i] in dict and dict[s[i]] != -1:
length = max(length, i - start)
... |
f3d8039fcbc93753610342b990e09ff37e4646fb | pugong/microblog | /crawler/spider.py | 699 | 3.53125 | 4 | from urllib2 import Request, urlopen, URLError, HTTPError
def samplefirst():
try:
response = urllib2.urlopen('http://www.alibaidu.com/')
html = response.read()
print html
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.co... |
b4a6113719a67fcf438e00992b61c291a280aa7f | mohitraj/mohitcs | /Learntek_code/4_June_18/is1.py | 110 | 3.71875 | 4 | list1 = [1,2,43,'1','2','3','A']
for each in list1:
if isinstance(each,str):
continue
a = each/2
print a |
6c91bef5923b517d5768e5808e6706b538e610b2 | pholtz/terminalia | /terminal.py | 7,495 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------#
# Summary:
# Terminal is a container class for a curses window as well as a character-based world
# and character animation using console graphics. Terminal loads a MAP file and allows
... |
cd41a4424df09d3e48660d3a7b216ac90df3800f | rajeshchinthanippu/upgraded-doodle | /credit_card.py | 1,163 | 4.09375 | 4 | import re
import argparse
PATTERN='^([456][0-9]{3})-?([0-9]{4})-?([0-9]{4})-?([0-9]{4})$'
def is_valid_card_number(sequence):
"""Returns `True' if the sequence is a valid credit card number.
A valid credit card number
- must contain exactly 16 digits,
- must start with a 4, 5 or 6
- m... |
b5945f09f2c9417111a4d2aabad4f29a5ccb84dd | tbrailov/na_utils | /dnatorna.py | 520 | 3.90625 | 4 | def dna_to_rna(seq):
"""Converts DNA sequence to RNA"""
rna_seq = seq[::-1]
rna_seq = rna_seq.upper()
rna_seq = rna_seq.replace('T', 'U')
return rna_seq
def reverse_rna_complement(seq):
"""Computes a reverse complement RNA sequence of a DNA sequence"""
new_seq = seq[::-1]
new_seq = new_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.