blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
af6a5cd04daf1748559b9c75c2a3d48ddf79a8b7 | ExcaliburZero/python-csp-anytime-solutions | /__main__.py | 3,951 | 3.5625 | 4 | from typing import Dict, List
import argparse
import datetime
import multiprocessing
import queue
import sys
import constraint
Solution = Dict[str, int]
def main(argv: List[str]):
parser = argparse.ArgumentParser()
parser.add_argument("method", type=str)
parser.add_argument("--min", type=int, default=... |
a9c533e79ce80ca8d359ea68764dbcddf313eb69 | lettucelu/Algorithm | /Office/pokerArray.py | 1,272 | 3.71875 | 4 | # /usr/bin/python
# -*- coding:utf-8 -*-
import random
global top
top = -1
k = 0
card = [ None ] * 52
card_new = [ None ] * 52
stack = [ 0 ] * 52
print(card)
print(card_new)
print(stack)
for i in range(52):
card[i] = i + 1
print(card)
def pop(stack):
if top < 0:
print("堆疊為空")
else:
... |
aefb76fe6c64aab213cda27b171a777a20997848 | lettucelu/Algorithm | /threeDimensionArray.py | 371 | 4.03125 | 4 | # /usr/bin/python
# -*- coding:utf-8 -*-
#print("尋找最小值")
num = [[ [33, 45, 67], [23, 71, 66], [55, 38, 66] ], [ [21, 9, 15], [38, 69, 18], [90, 101, 89]]]
print(num)
for x in range(2):
for y in range(3):
for z in range(3):
#print("%d") %(num[x][y][z])
if min >= num[x][y][z]:
min = num[x][y][z]
print("... |
2bc6e15c932be59832de9e40960dc14c4de17c4f | AidaQ27/python_katas_training | /loops/vowel_count.py | 777 | 4.21875 | 4 | """
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.
---
We are starting with exercises that require iteration through
the elements of a structure, so it will be good to dedica... |
16a255f1f025cf0c14a8b9405cab48fd5602e28d | villanuevarussell/PythonUdemyCourse | /Python Course Projects/Black Jack/BlackJackPackage/BlackJack.py | 4,799 | 3.578125 | 4 | #Class the manages the game functions
#imports all clases related to game from specified modules
import time
import sys
from Player import Player
from Hand import Hand
from Deck import Deck
#function that takes user input for betting
def bet(player):
print(f"{player.playername} has $ {player.money}")
while True:
... |
eb53e3de52a3446ce03eb1ae1ac1b0f11744a8b5 | Tastingor/PROTAC_ternary | /PROTAC_ternary/Utils.py | 4,526 | 3.546875 | 4 | import argparse
def args():
"""Process input arguments
Returns:
argparse.Namespace: Namespace of arguments
"""
parser = argparse.ArgumentParser(
description="""This script takes protien-protein docking decoy(s),
align with linker conformer(s) and ouputs ternary
... |
a44254b600d78af4d18f5078006b4ec3c2ecfc22 | Nalinswarup123/python | /class 7/common element in list.py | 273 | 3.671875 | 4 | l1=[1,2,5,8,7,4,9,6]
l2=[4,1,8,6,9,7,2,3,11]
l3=[]
def fun():
for i in l1:
for j in l2:
if(i==j):
l3.append(i)
fun()
print(l3)
#sum of elements of a list
s=0
for i in l1: s=s+i
print(s)
del l1[2:5]
print(l1)
|
75da0b0aca51ebd094a91400f221b6e0466e1dce | Nalinswarup123/python | /class 3/printing D.py | 332 | 3.640625 | 4 | l=0
p=4
for i in range(0,10):
while(l!=5):
print('*',end='')
for j in range(0,l):
print(' ',end='')
l+=1
print('*')
while(p!=0):
print('*',end='')
for k in range(1,p):
print(' ',end='')
p=p-1
print('*')... |
6f3e973396108d5827080481658c8cb7b0153967 | Nalinswarup123/python | /class 15/CA dict.py | 97 | 3.5 | 4 | d={}
d[(1,2,3)]=4
d[(3,1,2)]=5
d[(4,3)]=1
c=0
for i in d:
c+=d[i]
print(c)
print(d)
|
42b2eac7097ededd9d87d2746afaeb5f8fc9b240 | Nalinswarup123/python | /class 6/bio.py | 658 | 4.125 | 4 | '''biologists use seq of letter ACTC to model a genome. A gene is a substring
of gnome that starts after triplet ATG and ends before triplet TAG , TAA and
TGA.
the length of Gene string is mul of 3 and Gene doesnot contain any of the triple
TAG , TAA and TGA.
wap to ask user to enter a genone and display all genes... |
ee8b60017ac4abdd8824ff6b8bff2849edf91dad | Nalinswarup123/python | /class 12/exception.py | 496 | 3.65625 | 4 | def main():
while True:
try:
n1,n2=eval(input('enter two nos'))
res=n1/n2
print('result=',res)
except ZeroDivisionError:
print('div by 0 is not allowed')
except SyntaxError:
print('syn error')
except:
... |
470cd5e72d7a9147a6d2fc4835040fb3446f1dcc | Nalinswarup123/python | /calss 1/distance between two points.py | 275 | 4.125 | 4 | #distance between two points
print('enter first point')
x,y=int(input()),int(input())
print('enter second point')
a,b=int(input()),int(input())
x=((x-a)**2+(y-b)**2)**0.5
print('distance between the given points=',x)
#print('{} is the required distance'.format(x))
|
6a30f667bca402aac5fc5fa8fa5695f34d72e588 | Nalinswarup123/python | /class 11/files.py | 441 | 3.5625 | 4 | file1=open('myfile.txt','w')
l=['This is Delhi\n','This is london\n']
file1.write('Hello\n')
file1.writelines(l)
file1.close()
file1=open('myfile.txt','r+')
print('output is')
print(file1.read())
file1.seek(0)
print('output:')
print(file1.readline())
file1.seek(0)
print('output of readline(9) func is')
p... |
d7b302b68a31ef7efd9496795517deffb0b639a7 | Nalinswarup123/python | /class 18/value error when more 2 even nos in an list.py | 257 | 3.546875 | 4 |
def contains(l):
c=0
for i in l:
if (i%2==0):
c+=1
if(c==2):
raise ValueError
try:
contains([1,2,3,4])
except ValueError:
print('abc')
# raise ValueError('value error occured')
|
ddc098c89674d920c0b48d9574ced17fe1ccc54e | Nalinswarup123/python | /calss 1/cw.py | 497 | 4.09375 | 4 | #helo
'''fhjd
hjghjgjh'''
print('hii')
""" i am nalin
cghjhkhkj"""
d,b,c=10,4.5,"hello"
print(d,b,c)
print(b)
print(c)
print("\'python\'")
print("'python'")
print("\"python\" is easy")
print("\"python\" is \teasy")
x=5
y=10
z=6
print("the value of x is {0} and y is {1} and z is {2}".format(x,y,z))
... |
f8dc287adaf8b4c88236a0d1977230096367e9f5 | JasmineGuy/week_4_assessment | /process.py | 749 | 3.953125 | 4 | log_file = open("um-server-01.txt")
# saving the file to a variable called log_file so that we can manipulate the data therein
def sales_reports(log_file):
for line in log_file:
line = line.rstrip()
day = line[0:3]
if day == "Mon":
print(line)
# This function takes in the fil... |
a981e7aaa73eebe9a913d5ced338f04d202c332b | Deveshnie/Computational-Physics | /Tutorials/Tutorial 3.py | 798 | 3.65625 | 4 | import numpy as np
from matplotlib import pyplot as plt
import Gauss_Example as ga
#Tutorial 3
#Question 1
#the number of passes for an fft is the log base 2 of the number of data elements
print "Question 1"
print
print
def conv (array, shift):
if1 = np.fft.fft(ga.gauss(array,x0 = len(array)/2 + shift))
... |
fd60a484b60b1f34dc3e5e2893b2a8ca5102688b | chandan-singh-007/Demo | /second.py | 504 | 4.15625 | 4 | #write a program to check whether a number is prime or not
def prime(n):
if (n>1):
for i in range(2,n):
if(n%i)==0:
print(n ,"is not prime")
break
else:
print(n,"is prime")
# def prime(n):
# if n>1:
# for i in ran5ge(2,n):
# ... |
537eedb8f1106dd37127513990c09165f73bb0a5 | matthannan1/python-lpthw | /ex37.py | 555 | 3.609375 | 4 | # ex37.py is to test out a little of this and a little of that.
# The list is fairly lengthy.
# and, =, if, print, %d
a = 1
b = 1
if a and b:
print "a is %d and b is %d. They are equal." % (a, b)
# with and as are used together...to run parallel commands.
# can be used for more than opening, writing and closing t... |
6692daa627b01842e018d078fac7b64354d9a968 | smritta10/PythonTraining_Smritta | /Task3/Task3_all_answers.py | 1,906 | 4.125 | 4 | Task -3
#Question 1
diff_list= [10,'Smritta', 10.5,'1+2j', 20,'Singh', 113.0, '3+4j', 100, 'Python_learning']
print(diff_list)
-----------------------------------------------------
#Question 2
list1= [10,20,30,40,50]
s1= list1[ :5] #actual list
s2= list1[ : :-1] # lists items in reverse order
s3= list1[1:5:2] # lis... |
273ea626cc383a6976f20e9ee64910a72e587cab | Krisje1973/AdventOfCode | /Day03/code.py | 823 | 3.5625 | 4 |
lines = []
def readinput():
global lines
file = open(r"C:\DevOpps\Playground\AdventOfCode\Day3\input.txt", "r")
lines = [line.strip() for line in file]
def calculate(down,right):
row = 0
pos = 0
trees = 0
global lines
while True:
row += down
pos = (pos+right) % len(lin... |
c91f0044d88593f20382a5dd1122504d9fbf8c1d | sindhupaluri/Python | /count_string_characters.py | 425 | 4.34375 | 4 | # Please write a program which counts and returns the numbers of each character in a string input.
# count_characters( "abcdegabc" )
# { 'a':2, 'c':2, 'b':2, 'e':1, 'd':1, 'g':1 }
def count_characters(string):
char_count = {}
for char in string:
if char in char_count:
char_count[char] +=... |
601e745cffca267949095d662059e49a6bd1d764 | hvinner1/lab6 | /main.py | 864 | 3.609375 | 4 | import multiprocessing
print("yah")
myValue = multiprocessing.Value('i')
myArray = multiprocessing.Array('f',3)
def fn(myArray, myValue):
for (idx,n) in enumerate([3,2,1]):
myArray[idx] = n**2
myValue.value = int(sum(myArray))
print("In the process, iter={}:".format(idx))
print(" Array: {}".format(m... |
95c55be6543c3b76d032cd95daa2826d85bf29a8 | adasky7/Kinect-Skeleton-ROS-publish- | /Multimodal_Features.py | 6,586 | 3.90625 | 4 | """
This program is performs activity classification by applying a clustering algorithm (Fuzzy C-Means clustering)
to find similar patterns in an activity and group the activties for further prediction using an unseen data.
To run the program: a CSV file containing joint coordinates of activities and their correspondi... |
54fc2e73903235f4b7f16359f518e4fb62617546 | jakobj/money-helsinki | /money-helsinki | 3,374 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""money-helsinki
Usage:
money-helsinki <expenses>
money-helsinki -h | --help
Computes the required transactions to achieve identical expenses
across all people appearing in the expenses file. For non-uniform
participation, the "day" column in the expenses file shoul... |
3553f76ab8acb6cc59c5daf446fbb7789022ee71 | achoum/small | /test.py | 1,185 | 3.890625 | 4 | #Example of program for the Small programming language
import small
# Enable the debuging information
small.getGlobalContext().debug = True
# Hello world
small.execString("Hello println")
# Simple expressions
small.execString("10 5 + println")
small.execString("4 5 6 7 8 * / + - 1 + println")
# Simple variables
... |
e0f067409a0234da22bfcfe803df39710d552bb7 | pprzetacznik/competitions | /puzzles/bomb_bfs.py | 3,442 | 3.625 | 4 | from queue import Queue
from typing import Optional, Dict, Set, List, Tuple
from unittest import main, TestCase
State = int
Path = List[State]
States = Set[State]
NeighboursGraph = Dict[State, Set[State]]
VisitedDict = Dict[State, Tuple[str, State]]
class BombSolver:
def __init__(
self,
accepted_... |
40c1b8433db69979f2931d22cbe165e3472f13e1 | betoesquivel/lenguajesDeProgramacion | /scanner.py | 3,471 | 3.5625 | 4 | # Implementacion de un scanner mediante la codificacion de un Automata
# Finito Determinista como una Matriz de Transiciones
# Autor: Dr. Santiago Conant, Agosto 2014
import sys
# Matriz de transiciones: codificacion del AFD
# [renglon, columna] = [estado, transicion]
# Estados > 99 son finales (ACEPTORES)
#... |
d3756dee6eb70311ff85a602aa1d31ede89f6fc1 | Hemangi3598/chap-6_p8 | /p8.py | 324 | 3.609375 | 4 | # wapf to find fact of an integer
def fact(num):
f = 1
for i in range(1, num+1):
f = f * i
return f
n = 12
r = 2
perm = fact(n) / fact(n-r)
comb = fact(n) / (fact(r) * fact(n-r))
print("perm = ", perm)
print("comb = ", comb)
# dev karo ek baar.. call karo baar baar
# DRY ==> dont repeat your... |
8e3e7ed662eca4aba32f34c66dda89f35d7ce69b | raehik/html-line-colourer | /html-line-colourer.py | 5,408 | 3.59375 | 4 | import sys
import os
import argparse
import random
def_colours = ['919AC', '59BCFF', 'CC0000', 'E69316', '8A5C2E', '005200', '33CC33', 'FF9DFF', '84299A', '82829B', ]
def_step = 3
def_output = "out.txt"
def_field_delim = '~'
def print_error(err, line=""):
print("ERROR: " + err)
if line != "":
print("L... |
cc9f5557da6e2a296a670be87749e2cb7ac3c7b3 | Jasjot784/Python | /for.py | 348 | 4.21875 | 4 | primes=[2,3,5,7]
for num in primes:
print(num)
print("Outside the for loop")
list1 = ["Apple","Bananas","Cherries"]
tup1 = (13,12,15)
for item in list1:
print(item)
for item in tup1:
print(item)
for i in range(1,11):
print(i)
for i in range(0,11,2):
print(i)
for i in range(0,5):
for j in ran... |
0dceddedd3709a38f3854b8c92a25cbbd6c996f7 | Xpf123131123/python_study_demo | /checkio/FindSequence/FindSequence5.py | 2,081 | 3.78125 | 4 | def checkio(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
try:
if matrix[i][j] == matrix[i - 1][j + 1] and matrix[i - 1][j + 1] == matrix[i - 2][j + 2] and \
matrix[i - 2][j + 2] == matrix[i - 3][j + 3]:
if (i - ... |
3a4ac7d884b8a597a559c86880569a952411e113 | Xpf123131123/python_study_demo | /checkio/home/TheMostWantedLetter.py | 2,355 | 3.953125 | 4 | """
给你一个其中包含不同的英文字母和标点符号的文本,你要找到其中出现最多的字母,返回的字母必须是小写形式,
当检查最想要的字母时,不区分大小写,所以在你的搜索中 "A" == "a"。 请确保你不计算标点符号,数字和空格,只计算字母。
如果你找到 两个或两个以上的具有相同的频率的字母, 返回那个先出现在字母表中的字母。 例如 -- “one”包含“o”,“n”,“e”每个字母一次,因此我们选择“e”。
输入: 用于分析的文本.
输出: 最常见的字母的小写形式。
如何使用: 对于大多数的解密任务,你需要知道各种字母出现在一段文字的频率。例如:如果我们知道在哪个字母出现的频率,我们可以很容易地破解一个简单的加法密码或替换密码。... |
485db7bf0d06d68e4ece3eea192ccdd447112a2b | Xpf123131123/python_study_demo | /checkio/FindSequence/FindSequence9.py | 1,742 | 3.546875 | 4 | def checkio(matrix):
_len = len(matrix)
verticals = [[m[i] for m in matrix] for i in range(_len)]
diagonals = [[matrix[_len - 1 - i + j][j] for j in range(i + 1)] for i in range(_len)] + \
[[matrix[j][_len - i + j] for j in range(i)] for i in range(_len - 1, 0, -1)] + \
[[m... |
47859753ebcd3aed309939d2d9fbc49f90668133 | Xpf123131123/python_study_demo | /checkio/LongestPalindomic/palindomic_reduce.py | 599 | 3.84375 | 4 | from functools import reduce
def longest_palindromic(text):
is_palindromic = lambda t: reduce(lambda x, y: x and y, [True] + [t[i] == t[-1 - i] for i in range(len(t) // 2)])
lenght = len(text)
for i in range(lenght):
for j in range(i + 1):
subtext = text[j:lenght - i + j]
... |
8481e9764f727ca62824cd86691a537d71c38d3d | Xpf123131123/python_study_demo | /pak/io_input.py | 447 | 4.15625 | 4 | def reverse(text):
return text[::-1]
def isHuiWen(text):
text1 = ''
for item in text:
if item >= 'a' and item <= 'z':
text1 += item
if item >= 'A' and item <= 'Z':
text1 += item
print(text1)
return text1 == reverse(text1)
text = input('输入内容,判断是否回文:')
if i... |
3c42ff27a2516d5eb27c1b1d5d4330799e7bd8c8 | Xpf123131123/python_study_demo | /checkio/LongestPalindomic/palindomic2.py | 6,031 | 4.15625 | 4 | def longest_palindromic(text):
""" A palindrome is
a sequence of characters
which reads the same backward as forward,
such as "madam" or "racecar".
- "aaaa" even case "aa" == "aa" <- halves equality ? no the same element
- "aba" odd case, without center|middle 'b' -> to even case "a" == "a"
... |
939c6006a2b48b3e8e5b60037747665b9058ec3a | Xpf123131123/python_study_demo | /pak/oop_exp.py | 931 | 3.90625 | 4 | class Person:
population = 0
def __init__(self, name):
self.name = name
print("(Initializing {})".format(self.name))
Person.population += 1
def die(self):
print("{} is being destroyed!".format(self.name))
Person.population -= 1
if Person.population == 0:
... |
ff527674d278d0b228861ec3d82c51c7acaa0615 | Xpf123131123/python_study_demo | /checkio/FindSequence/FindSequence12.py | 703 | 3.59375 | 4 | # Returns true if the all elements are the same
def checkline(matrix, x, y, dx, dy):
el = matrix[x][y]
for i in range(1, 4):
if el != matrix[x + i * dx][y + i * dy]:
return False
return True
# Returns true if the square 4x4 has the line with the same elements
def checkSquare(matrix, x... |
a5468d993fa236a8b02340cfedcf41052efc988d | MarcosPX1/Sistema_de_Bolos | /Pedir_bolos.py | 6,215 | 4.03125 | 4 | print(" *** Bem vindo a minha loja *** ")
print("***" * 15)
print("1 - Solicitar um novo bolo")
print("2 - Solicitar uma torta")
print("3 - Verificar itens selecionados")
print("4 - Fechar menu")
print("***" * 15, "\n")
sabor_bolo = ["Chocolate", "Limão", "Morango", "Prestígio", "Nutella"]
sabor_tortas = [... |
f0f84b6d9951841fa21dea0b91bbf24239808cd5 | spiridonovfed/EPAM_Training_Final_Task | /persons_table/models.py | 7,716 | 3.5 | 4 | from random import random
import requests
from persons_table import db
class Person(db.Model):
"""This is a class to represent a Person table in the database
:class: 'SQLAlchemy.Model'
:param id: id and primary key of any entry in the database
:type id: int, optional
:param gender: gender of a ... |
df73dc023f3fd30d2c5d0edad826030d5c2a088e | Nope-X/TaoBao-Reptile | /novels.py | 14,038 | 3.59375 | 4 | """
代码功能:
给定顶点网站一部小说的第一章链接,自动下载全部小说内容,由于爬取速度较快目前还不能实现
完全无人值守。可能由于网站无响应,爬虫死掉,需要重新运行(将上次短的链接喂进程序即可)。
"""
import requests
import time
import random
import numpy as np
from bs4 import BeautifulSoup as bs
URL = 'https://www.x23us.com'
user_agent_list = [
"Mozilla/5.0 (Linux; U; Android 5.1; zh-cn; m1 metal B... |
c986e8e3b7f841a99201f8611f1651052165cfcb | SoCXin/MEGA328P | /src/halibs/examples/misc/evalFix.py | 362 | 3.5 | 4 | #!/bin/env python2.7
from numpy import *
import sys
def eval(filename):
data=recfromcsv(filename)
for (a,b,plus,mult) in data:
print "[%f, %f] +: %f\t*: %f\te(+): %f\te(*): %f"%(a,b,plus, mult, abs(plus-(a+b)), abs(mult-(a*b)))
if __name__=="__main__":
if len(sys.argv) <=1:
print "usage: %s <csv datafile>\n" ... |
d75d6a39c63c421437dcbc64a7f6d0c435d4f274 | lilyycao/plants-vs-plants | /Plants VS Plants/MAIN.py | 1,488 | 3.90625 | 4 | '''
PLANTS VS PLANTS
Programmed by: Lily Cao and Fiona Hila
Programmed on: 2019/05/27
Programmed for: ICS3U1-04
Description: This is a game created using pygame. Users use the left and right arrows to attack and defend against
carnivorous plants. There are two sections to this game: single player and multiplayer.... |
8ce2c3080f736986c08aaa517f54b8a234cedfcb | mad26/computer-vision | /4. BGR_colorspace.py | 516 | 3.671875 | 4 | import cv2
import numpy as np
image = cv2.imread('input.jpg')
B,G,R=image[0,0] #reading B,G,R value for the firstset [0,0] pixel
print(B,G,R) #printing the values stored for BGR at [0,0]
print(image.shape) #printing the size of image
gray_img=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #converting color image to grayscale i... |
bc3e1d28dfb1d15304e4407509f7fa5cdac915e5 | RAmruthaVignesh/PythonHacks | /Foundation/example_def.py | 530 | 3.9375 | 4 | base = 10
exp = 4
# Example of basic def with no parameter
def hello_world():
base = 20
print "inside of hello_world base is" , base
return "Hello World!"
print hello_world()
print "outside of hello_world base is" , base
#Example of def with parameters
def compute_exp(base,exp):
print "inside of compu... |
05b0deda5e25686a6082b289b46594a1b57e7ea3 | RAmruthaVignesh/PythonHacks | /Foundation/example_*args_**kwargs.py | 845 | 4.53125 | 5 | #When the number of arguments is unknown while defining the functions *args and **kwargs are used
import numpy as np
def mean_of_numbers(*args):
'''This function takes any number of numerical inputs and returns the mean'''
args = np.array(args)
mean = np.mean(args)
return mean
print "The mean of the n... |
f24bcde3c27bf62a63df4e2e2d6d76925ac51352 | RAmruthaVignesh/PythonHacks | /Foundation/example_list_comprehension.py | 651 | 4.71875 | 5 | #Example 1 : To make a list of letters in the string
print "This example makes a list of letters in a string"
print [letter for letter in "hello , _world!"]
#Example 2: Add an exclamation point to every letter
print "\nExample 2: Add an exclamation point to every letter"
print [letter+"!" for letter in "hello , world... |
9d4b2995f00b605030a1d763f133a01c83965681 | RAmruthaVignesh/PythonHacks | /MITCourse/MITcourse_hw1.py | 938 | 4.1875 | 4 | # Name: Amrutha
# Date:12.17.2016
# hw1.py
##### Template for Homework 1, exercises 1.2-1.5 ######
print "Hello , World!"
# Do your work for Exercise 1.2 and 1.3 here
tictac = " | |"
toe = "--------"
print "Printing tictactoe board"
print tictac + '\n'+ toe + '\n' + tictac + '\n' + toe + '\n' + tictac
print "***... |
3c4a80a8e071334509511b90306b78f3aa9a2f73 | RAmruthaVignesh/PythonHacks | /MiscPrograms/RPSgame_pythonway.py | 789 | 3.859375 | 4 | #main game rules
# rock and paper - paper wins
#scissors and paper - scissors wins
#check for ties and invalid input
def game_rules(ip_player1,ip_player2):
ip = ["rock", "scissors", "paper"]
winning_combo = [["paper","rock"], ["scissors","paper"], ["rock","scissors"]]
#check if the inputs are valid
if (... |
9095e434cabe1afd4d287c4db9885bbf0d7b4515 | RAmruthaVignesh/PythonHacks | /OOPS/class_inheritance_super()_polygons.py | 1,891 | 4.78125 | 5 | #This example explains the super method and inheritance concept
class polygons(object):
'''This class has functions that has the functionalities of a polygon'''
def __init__(self,number_of_sides):#constructor
self.n = number_of_sides
print "The total number of sides is" , self.n
def interi... |
7e06219cc161ddfb37e3f72d261c9c256ea20414 | RAmruthaVignesh/PythonHacks | /MiscPrograms/number_of_letters_in_word.py | 354 | 4.3125 | 4 | #get the word to be counted
word_to_count = 'hello_world!'
print ("the word is" , word_to_count)
# iniliatize the letter count
letter_count = 0
#loop through the word
for letter in word_to_count:
print("the letter", letter, "#number" , letter_count)
letter_count = letter_count+1
print ("there are", letter_co... |
d7d878c1ab326d8c1af0bd7103af9df476fd1ffc | pantorn47/Exercise-5.1-2 | /Exercise5_1_Panuvit_B.py | 162 | 3.8125 | 4 | a = int(input("Put number :"))
b = int(input("Put number :"))
print(a,"+",b,"=" ,a+b)
print(a,"-",b,"=" ,a-b)
print(a,"*",b,"=" ,a*b)
print(a,"/",b,"=" ,a/b) |
6bd59bae0883e9b6c6d3fae59d0d19273b8c36f6 | emfomy/leetcode | /problems/algorithms/0017.py | 1,367 | 3.828125 | 4 | # Source: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
# Title: Letter Combinations of a Phone Number
# Difficulty: Medium
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# Giv... |
7192261eac7d2a6cdac046879676477a5859c5b9 | emfomy/leetcode | /problems/algorithms/0064.py | 1,601 | 3.53125 | 4 | # Source: https://leetcode.com/problems/minimum-path-sum/
# Title: Minimum Path Sum
# Difficulty: Medium
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# Given a m x n grid filled with non-negative n... |
7185553979eca9526fa4933d7daa3f7d66c6b1d0 | emfomy/leetcode | /problems/algorithms/0008.py | 2,792 | 3.6875 | 4 | # Source: https://leetcode.com/problems/string-to-integer-atoi/
# Title: String to Integer (atoi)
# Difficulty: Medium
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# Implement atoi which converts a... |
07db9dc567eda73a1d174dc2e355c45de2380246 | emfomy/leetcode | /problems/algorithms/0005.py | 1,524 | 3.671875 | 4 | # Source: https://leetcode.com/problems/longest-palindromic-substring/
# Title: Longest Palindromic Substring
# Difficulty: Medium
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# Given a string s, f... |
0fff4ced9ebbb6852543fb009386e49bee3c352a | AlanDTD/Programming-Statistics | /Week 2/Week 2 exercises - 2.py | 909 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 20:05:57 2021
@author: aland
"""
#Loops and input Processing
nums = tuple(input("Enter at least 5 numbers separated by commas!"))
print(len(nums))
print(nums)
sum_num = 0
count = 0
if type(nums) == tuple: #Checks if ithe value is a tuple
while len(nums) < 5: ... |
58b31d6c577cc69f07312143f85b876b1376c5f2 | AlanDTD/Programming-Statistics | /Week 3/Messing around with syntax.py | 155 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 20:51:07 2021
@author: aland
"""
collection = [1,2,3,5]
for i, x in enumerate(collection):
print(x) |
3f0a7b127d85850b6ea050cbb4b10e83825985ea | ShimankDhondiyal/LexicographicWordLadders-CubeTowers | /LexicographicWordLadders.py | 3,556 | 3.765625 | 4 | from collections import defaultdict
import networkx as nx
def makeGraph(text):
graph = nx.DiGraph()
for word in text.split():
graph.add_node(word)
return graph
def isEditStep(firstWord, secondWord):
firstWord = firstWord._data
secondWord = secondWord._data
#if the words are more than ... |
a6d99e9edf7ca67feda09fb1eee078176aac5bb6 | moreyw/Database-Project | /choice.py | 3,368 | 3.5625 | 4 | from database import *
import create
import edit
create = {
'projects' : create.new_project,
'procedures' : create.new_procedure,
'experiments' : create.new_experiment,
'reagents' : create.new_reagent,
'equipment' : create.new_equipment,
'specimens' : create.new_specimen
}
edit = {
'projec... |
5d388de4205cd0a6be7795dab9b4d165fafc016c | GrantMHodgson/pong | /paddle.py | 565 | 3.75 | 4 | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, position):
super().__init__()
self.shape("square")
self.color("white")
self.setheading(90)
self.shapesize(stretch_len=5, stretch_wid=1)
self.penup()
self.goto(position)
def move_up(self... |
fd5f154f5f37bda354935ea17305f567fc5f58e5 | mirunaen/w6-emn | /ej_3.py | 993 | 3.75 | 4 | def count(list,x):
counter=0
for i in list:
if i ==x:
counter +=1
return counter
def index(list,x):
for i in range(len(list)):
if list[i] == x:
return index
elif x not in list:
return -1
def append(list,x):
newList=list + [x]
return newList
def find(list,x):
if x in list:
... |
3ba3810d3f1b51f6ea794fad3c8c4cad8c02688d | jason9075/T-Brain-Policy-Contest | /util.py | 25,437 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 14:13:19 2018
@author: jason9075
"""
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def get_corr(df):
new_corrs = []
# Iterate through the columns
for col in df.columns:
# Calculate co... |
469432e7affd422c94b193a248d18439e7bfd324 | Ddjones001/data_structures | /Binary Search.py | 1,779 | 3.96875 | 4 | def binary_search(search_list, number_to_find):
left_index = 0
right_index = len(search_list) - 1
mid_index = 0
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = search_list[mid_index]
if mid_number == number_to_find:
... |
a3878c9b7b9ee9046c60a1ff3b04399e9407bad9 | bkalcho/python-network-programming | /tweet.py | 906 | 3.71875 | 4 | # Author: Bojan G. Kalicanin
# Date: 04-Feb-2017
# Description: Write a function that accepts as input a subject string
# and maximum number of search results and submits a search request to
# Twitter. Have the function return the raw output.
import urllib.parse
import urllib.request
import json
def tweets(subject, n... |
f056f6b7596c86342c3dfab1e1559e592787a9a1 | salwa19-meet/meet2017y1lab4 | /script_a.py | 135 | 3.890625 | 4 | num1 = 1
num2 = 2
num3 = 3
if num1 > num3:
print('chocolata')
elif num1 > num2:
print('vanilla')
else:
print('strawberry')
|
57695734d8df79de01e27f87c8ac19073f7d2382 | michaellinp/PythonGo | /IO编程/文件读写.py | 4,153 | 3.59375 | 4 | # 文件读写
#
# 阅读: 259372
# 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。
#
# 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)
f = open('/Users/michael/test.txt', 'r')
try:
f = open('/path/to/file', 'r')
print(f.read())
fi... |
0a64c42f58fb6b6454547b5739978aa97712c3fa | michaellinp/PythonGo | /面向对象高级编程/动态绑定属性和slots.py | 2,494 | 3.78125 | 4 | # 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class:
class Student(object):
pass
# 然后,尝试给实例绑定一个属性:
#
s = Student()
s.name = 'Michael' # 动态给实例绑定一个属性
print(s.name)
# Michael
# 还可以尝试给实例绑定一个方法:
def set_age(self, age): # 定义一个函数作为实例方法
self.age = age
from types import MethodType
s.set_age = M... |
94a7248452279ee1528d3cac70402a2349e122ff | danealohabib/research-MP | /convert_to_csv.py | 2,079 | 3.703125 | 4 | import os
import argparse
import pandas as pd
def get_all_files_paths(dir_path):
"""
Returns paths to all files that are in given
directory.
"""
filesnames = list(sorted(os.listdir(dir_path)))
filepaths = [os.path.join(dir_path, f) for f in filesnames]
return filepaths
def parse_args():
... |
2341c133fd74ad908e2d078f7576a895e0c45ce6 | dharalakshmidevi/pythonpracticecode | /if_elif.py | 85 | 4.0625 | 4 | x=5
y=5
if x>y:
print("x is greater than y")
elif x==y:
print("x is equal y") |
6875927be4f22584569cba911bb78080c820c8c8 | dharalakshmidevi/pythonpracticecode | /string_replace.py | 43 | 3.671875 | 4 | x="Hello,World!"
print(x.replace("H", "J")) |
799edb4f713c2425663f6a105f8872f1fe75e7b0 | dannytheninja/advent-2019 | /day1.py | 615 | 3.578125 | 4 | #!/usr/bin/env python3
import math
vectors = []
def calc_fuel(mass):
return math.floor(mass / 3) - 2
def calc_fuel_recursive(mass):
fuel = calc_fuel(mass)
if calc_fuel(fuel) > 0:
fuel = fuel + calc_fuel_recursive(fuel)
return fuel
with open('day1.txt') as fp:
while True:
line =... |
8c73c6467a4bd69a1b51a2acf322c3abe9b4373b | sdpython/pymlbenchmark | /src/pymlbenchmark/datasets/artificial.py | 1,713 | 3.734375 | 4 | """
@file
@brief Artificial datasets.
"""
import numpy
from numpy.random import rand, randn
def random_binary_classification(N, dim):
"""
Returns data for a binary classification problem (linear)
with *N* observations and *dim* features.
@param N number of observations
@param dim ... |
295f3dc02ffce6aa38f011e9c99077e9a723623e | ahmadChaka/Date-Calculator | /datecalculator.py | 3,162 | 4.15625 | 4 | """
Script which finds the number of days between two georgian dates.
Context is for a science project where it is necessary to run experiments and calculate
the number of full days elasped between seperate days. Since partial days are not
helpful to the experiment we only consider 'whole' days.
- We only consider da... |
cf744a761c698e2bdbc6711416aac086311a31a0 | Rodrigo0461/python_scripts | /Script_02/script_02.py | 1,356 | 3.765625 | 4 | # Version of Python 2.7.16
# Function for add 1.0 to list if is minor than 5
def add_note(largo,lista):
while largo < 5 :
lista.append(1.0)
largo += 1
return lista
def main():
# Open file with notes, this file is a .txt and is open read mode "r"
file = open("/Users/rootdrigo/Repositori... |
16519e662013022380d3b160d452ce64066b22ae | nix1947/youtube_games | /tictactoe.py | 3,704 | 4.15625 | 4 | # Let's import necessary module
import sys # Requre to exit the game
# Define some global variables
player_1_choice = 'x'
player_2_choice = 'o'
game_draw = 'DRAW'
# Define grid
# We will use list comprehension to create 3 x 3 grid.
grid = [cell for cell in range(9)]
# Let us create a function that display a grid
... |
6a1d2748f174288c1405562dcbe11e8b2e2e97f5 | Hyo-gyeong/likelion-python-exercise | /second.py | 283 | 3.8125 | 4 | #숫자형
#정수 실수
num1 = int(input("여기에 첫번째 정수를 입력하세요 : "))
num2 = int(input("여기에 두번째 정수를 입력하세요 : "))
print(num1/num2)
#나눗셈
# 몫 : //
# 나머지 : %
#몫&나머지:/
#거듭제곱 및 ** 승수
|
c6ff7f510a9bf425441120172ace1b5c60d2e488 | handevmin/DataStructure-and-Algorithm | /tree_preorder_traversal.py | 566 | 3.75 | 4 | class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Tree:
def __init__(self, root):
self.root = root
def preorder(self, n):
if n != None:
print(n.data, '',end="")
if n.left:... |
3aeb9ef0cebf79225d395fbda5d5c3a0182e3e21 | jason44406/python-projects | /for_while.py | 259 | 3.953125 | 4 | if __name__ == '__main__':
n = int(raw_input())
# Return the square of each non-negative integer until n.
for i in range(0, n):
print i**2
# Print each i for the given range:
for i in range(0, 5):
print i
j = 0
while j < 5:
print j
j += 1
|
9df50fbae3da16034d576e23622845fc931b6213 | hjl2626/stu_manager | /code/test.py | 503 | 3.859375 | 4 | """
Simple demo of a horizontal bar chart.
"""
import matplotlib.pyplot as plt
plt.rcdefaults()
import matplotlib.pyplot as plt
people = ('1-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90', '91-100')
y_pos = range(1, 11)
print(y_pos)
data = [2, 3, 4, 1, 9, 10, 20, 11, 20, 20]
plt.barh(y... |
ed04c33b0bd58feb0e53c7970ee6ec5de1511481 | mvessey/comp110-21f-workspace | /lessons/for_in.py | 382 | 4.46875 | 4 | """An example of for in syntax."""
names: list[str] = ["Madeline", "Emma", "Nia", "Ahmad"]
# example of iterating through names using a while loop
print("While output:")
i: int = 0
while i < len(names):
name: str = names[i]
print(name)
i += 1
print("for ... in output")
# the following for ... in loops is... |
118dedf2171ff51a09dfc335762478d0bcabb0e0 | mvessey/comp110-21f-workspace | /exercises/ex03/tar_heels.py | 553 | 3.890625 | 4 | """An exercise in remainders and boolean logic."""
__author__ = "730409403"
variable: int = int(input("Enter an int: "))
divisible_2: float = variable / 2
whole_divisible_2: int = variable // 2
divisible_7: float = variable / 7
whole_divisible_7: int = variable // 7
if float(divisible_2) == float(whole_divisible_2):... |
6ec689c67c53803fb2a2760cc91e90ec9dffbf7e | mvessey/comp110-21f-workspace | /lessons/ages.py | 178 | 3.796875 | 4 | age: int = int(input("How old are you? "))
year: int = int(input("What year is it? "))
age_in_2041: int = 2041 - year + age
print("In 2041, you'll be " + str(age_in_2041) + ".")
|
5f1d69306d2efca8afb9b95d6cbf53f3b239d724 | JonathanBonnaud/advent_of_code_2017 | /advent_of_code_17/day09/day_9.py | 2,674 | 3.59375 | 4 | """
Day 9: Stream Processing
"""
import abstract_day
OPEN_GARBAGE = '<',
CLOSE_GARBAGE = '>',
IGNORE = '!',
OPEN_GROUP = '{',
CLOSE_GROUP = '}'
class Stack:
"""Stack implementation with a list"""
def __init__(self):
self.stack = ['BEGIN']
def __str__(self):
r = '['
for element ... |
bf95dbe3b4e7aa1a15b5c3e6656981f825526449 | slovb/advent_of_code_2020 | /04/first.py | 908 | 3.640625 | 4 | def validate(obj):
keys = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
for key in keys:
if key not in obj:
return False
return True
def solve(data):
return sum([1 if validate(obj) else 0 for obj in data])
def read(filename):
with open(filename, 'r') as f:
data = ... |
509e7d766868b8976084499bbf1659409515eea0 | slovb/advent_of_code_2020 | /04/second.py | 2,276 | 3.6875 | 4 | def validate_year(year, lower, upper):
if not year.isdigit():
return False
y = int(year)
if lower <= y and y <= upper:
return True
return False
def validate_height(height):
h = height[:-2]
if not h.isdigit():
return False
h = int(h)
if height[-2:] == 'cm':
... |
6f2445426feabff37743195c8d6ffcc94925446d | slovb/advent_of_code_2020 | /07/second.py | 1,213 | 3.53125 | 4 | def solve(data):
counted = {}
def count(color):
if color in counted:
return counted[color]
x = 1
for m, c in data[color]:
x += m * count(c)
counted[color] = x
return x
return count('shiny gold') - 1
def read(filename):
with open(filename,... |
e333ab7f81f7cfc850c9b4b3f36b89f2acde2a38 | IExpo/solution | /Climbing the Leaderboard(draft).py | 600 | 3.703125 | 4 | def climbingLeaderboard(scores, alice):
ans=""
for i in range(len(alice)):
for s in range(len(scores)):
if scores[s] > alice[i]:
pass
else:
scores.insert(s,alice[i])
break
if s+1==len(scores):
scores.append(alic... |
e5f1266fb875f2d61be8ef72c382cf8cfa10b5de | Sam-Coon/Chapter_8 | /challenge2.py | 2,575 | 4.1875 | 4 | #Colaboration on Chapter 8 with Sam Coon and Tyler Kapusniak
#2/10/15
class TV(object):
def __init__(self, channel = 0, volume = 0):
self.__channel = channel
self.__volume = volume
def choose_channel(self):
print(
"""
Channels:
1. Action
2. Comedy
3.... |
f7f9e972a16d3d2834b67d611da03ee8ddddd576 | mihdevel/test_case | /inverting_dict.py | 176 | 3.671875 | 4 | import random
my_dict = { x : random.randrange(1, 1000) for x in range(20) }
inverting_dict = dict(zip(my_dict.values(), my_dict.keys()))
print(my_dict)
print(inverting_dict) |
9e24d760e2dfc8d657a2ee953a0208d1c33f841f | KillTheReptiles/PreInformeFunciones- | /2.py | 447 | 4.09375 | 4 | def exponente():
a1=int(input("Escriba un numero: "))
b1=int(input("Escriba su exponente: "))
operacion1=a1**b1
print("El resultado es: ", operacion1)
a2=int(input("Escriba un numero: "))
b2=int(input("Escriba su exponente: "))
operacion2=a2**b2
print("El resultado es: ", operacion2)
... |
78f53c4a130daf34adc2ef48ec7e37be90c0a3b1 | klcysn/free_time | /climb_staircase.py | 452 | 4.3125 | 4 | # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# ... |
94ebe7be385aa68e463c7cdc89bd1e257b9ecdbe | klcysn/free_time | /fizzbuzz.py | 799 | 4.71875 | 5 | # Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz".
# If the number is a multiple of 3 the output should be "Fizz".
# If the number given is a multiple of 5, the output should be "Buzz".
# If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz".
#... |
ceb99ffeed9b5ea7214f858c3915e8e0e3feac46 | Chetancv19/Python-code-Exp1-55 | /Lab2_1.py | 395 | 3.921875 | 4 | #1.Python Program to Check if a Number is Positive, Negative or 0
#chetan velonde 3019155
a = int(input("Enter the number for check:"))
if a > 0:
print(str(a) + " is positive and lies on right hand side on the number line")
elif a < 0:
print(str(a) + " is negative and lies on left hand side on the number ... |
f82a0f9537ee9ec944bdf9e95ea691a5f06e1bf3 | Chetancv19/Python-code-Exp1-55 | /Lab2_5.py | 701 | 4.125 | 4 | #Python Program to Check Prime Number
#chetan velonde 3019155
a = int(input("Enter the number for checking whether it is prime or not:"))
if a > 1:
for x in range(2, a):
if a % x == 0:
print(str(a) + " is not a prime number.")
break
else:
print(str(a) + " is a ... |
db68815532b75593db14d95d1cc5bfda962102da | jessemcastro/respostas_estrutura_de_decisao | /05.py | 798 | 4.21875 | 4 | #Faça um programa para a leitura de duas notas parciais de um aluno.
# O programa deve calcular a média alcançada por aluno e apresentar:
#A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
#A mensagem "Reprovado", se a média for menor do que sete;
#A mensagem "Aprovado com Distinção", se a médi... |
03beae721fbb935dde4766ef19c43678f79a6c4d | jessemcastro/respostas_estrutura_de_decisao | /02.py | 343 | 4.09375 | 4 | #Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
print("Determinar se um número é positivo ou negativo")
valor = float(input("Digite um valor"))
if valor>0:
print(valor," é um número positivo")
elif valor<0:
print(valor, "é um número negativo")
else:
prin... |
7591ef930b237b555421f0fede7749af7a6d48d8 | CharlotteGenius/python-bible | /python/DFS.py | 1,249 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 22:49:34 2019
@author: xiangyinyu
"""
# DFS Depth-First-Search 深度优选搜索
# 是一条路走到黑,再返回终点前的一个点,找其他未走过的点
Graph = {
'A':['B','C'],
'B':['A','C','D'],
'C':['A','B','D','E'],
'D':['B','C','E','F'],
'E':['C','D'],
... |
bb0992c3f0d6263adf11521b69b6586ac72aacf9 | CharlotteGenius/python-bible | /python/BFS.py | 1,503 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 22:32:10 2019
@author: xiangyinyu
"""
# BFS Breadth-First-Search 广度优先搜索
# 是一层一层的取点
# 每个点的连接点
Graph = {
'A':['B','C'],
'B':['A','C','D'],
'C':['A','B','D','E'],
'D':['B','C','E','F'],
'E':['C','D'],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.