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 |
|---|---|---|---|---|---|---|
a5e3fbbbf1f7b77483df4a76b0dba67e045b1031 | icefoxen/lang | /python/practice/primes2.py | 818 | 3.921875 | 4 | # Primes.py
# Calculates prime numbers. V. nice.
# Good practice.
# 8/30/2002
def main():
import sys # Local namespace -imports only into the function
min, max = 2, 10000
if sys.argv[1:]:
min = int( eval( sys.argv[1] ) ) # Eval turns string to number
if sys.argv[2:]:
max = ... |
332aae64f2cb3db53bda0ec5c24633d227a12614 | icefoxen/lang | /python/lunatic.py | 2,260 | 3.53125 | 4 | # This is a kinda odd idea-test for a programming language,
# vaguely Forth-ish.
# The keys are: Interactive, bottom-up, compiled (later),
# possibly dynamically-typed (tagged), low-level...
import re
ERROR = -1
LPAREN = 0
RPAREN = 1
APPLY = 2
SET = 3
SYMBOL = 10
NUMBER = 20
NUMRE = re.compile( '[0-9]+' )
SYM... |
eb35c579855cf04c054d58f4da7a68fd02350a0d | jihyeonyang/Test | /D-2.py | 1,995 | 3.65625 | 4 | '''
AM = int(input("아메리카노:"))
CL = int(input("카페라떼:"))
CP = int(input("카푸치노:"))
print("총 매출은",(2000*AM+3000*CL+CP*3500),"입니다")
xx = int(input("x:"))
yy = int(input("y:"))
print("두 수의 합:",(xx+yy))
print("두 수의 차:",(xx-yy))
print("두 수의 곱:",(xx*yy))
print("두 수의 평균:",((xx+yy)/2))
print("큰 수:", max(xx,yy))
print("작은 수", min... |
167b3a56792d0be21f40e0e8d2208fd7943ccddc | Vibhutisavaliya123/DSpractice | /DS practicel 6.py | 1,624 | 4.4375 | 4 | P6#WAP to sort a list of elements. Give user the
option to perform sorting using Insertion sort,
Bubble sort or Selection sort.#
Code:Insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..... |
bb3ea015fbf115aa1271a2e36b04333f841aa545 | thomasjk10/Cracking-the-Codking-Interview-Python | /Chapter 1/3_Urlify.py | 372 | 3.625 | 4 | #-----------------------------------------------------------------------
# Strip all spaces at the end of string and then replace spaces with %20
#-----------------------------------------------------------------------
def urlify(s):
new_s = s.rstrip()
url = new_s.replace(" ", "%20")
return url
inp = input... |
6318852459b6392b1dc6a6f267a515ad95a75613 | lexjox777/Inheritance-method | /animal.py | 425 | 3.625 | 4 | class Animal:
def __init__(self,name,age):
self.name = name
self.age = age
def speak(self):
return f"my name is {self.name}"
class Dog(Animal):
def __init__(self,name,age):
# self.name = name
# self.age = age
super().__init__(name,age)
def speak(self):
return "Whoof Whoof"
class Cat(Animal... |
587969265ebd78e2974b0df17a21deda41868f3b | originerd/exercism | /python/word-count/word_count.py | 235 | 3.515625 | 4 | import re
from functools import reduce
def word_count(phrase):
return reduce(lambda count_map, word: count_map.update({ word: count_map.get(word, 0) + 1}) or count_map, re.findall(r"[a-z0-9]+(?:'[a-z0-9]+)?", phrase.lower()), {})
|
93b291367b44aaf275200e8e8ac4fd9e3767de9a | Dual-PyJa/matplotlib_exercise | /Rocco.py | 235 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5])
y=x*2
#x = np.arange(0,5,0.1)
#y = np.square(x)
plt.plot(x,y,"k*")
plt.title("Y=X*2",loc="right")
#plt.plot(x,x,"b_-",x,x**2,"y4",x,x**3,"k*")
plt.show() |
a4d1d730e909599410d60900d328bc2b757c8920 | XPilot/Treehouse-Video-Downloader | /spider/auth.py | 1,960 | 3.71875 | 4 | from requests import Session
from lxml import html
class AuthSession(object):
"""Creates an authenticated session to teamtreehouse.com"""
SIGNIN_URL = "https://teamtreehouse.com/signin"
LOGIN_POST_URL = "https://teamtreehouse.com/person_session"
def __init__(self, user_name, password):
self.user_name = user_nam... |
4a6166fde1ece283712765c589118c37de752f32 | sergady/Eulers-Problems | /Ej7.py | 541 | 4.03125 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
import math
# True if prime
# False if not prime
def isPrime(num):
if(num == 2):
return True
i = 2
while num%i !=0:
if(i >= int(math.sqrt(num))):
... |
5d7d4bc98ca3fc5b18b7206343bc8da663b29543 | sergady/Eulers-Problems | /Ej1.py | 354 | 4.15625 | 4 |
# 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.
listNums = []
for i in range(1000):
if(i%3 == 0 or i%5 == 0):
listNums.append(i)
sum = 0
for s in (listNums... |
99f96abd07ee6979668e7cfb793b0d2a7da07044 | ChloeZPan/Automated-Reasoning | /model_checking.py | 7,298 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import copy
# Basic formula class represents a literal; tree node of a formula tree
# Super class of conjunction, disjunction, implication and biconditional
class Formula:
def __init__(self, sym, neg=False, lc=None, rc=None, val=None):
self.symbol ... |
08f062bd6d8484c42c402b9484bdfe90be5711bd | RyanHiltyAllegheny/blockchain-19 | /src/print_content.py | 2,540 | 3.5625 | 4 | """Prints tables and other program content."""
from prettytable import PrettyTable
class color:
"""Defines different colors and text formatting settings to be used for CML output printing."""
PURPLE = "\033[95m"
CYAN = "\033[96m"
DARKCYAN = "\033[36m"
BLUE = "\033[94m"
GREEN = "\033[92m"
... |
78c5ddb44b3aac0d56622ba951ee9234a2051db5 | savourylie/coding_tests | /microsoft/num_island_in_matrix.py | 2,846 | 3.71875 | 4 | # Consider a matrix of 0s and 1s.
# If two 1s are adjacent to each other, they are considered connected.
# Find out the number of connected components there are in the matrix
def num_island_in_matrix(m):
"""
(2D-list) -> int
"""
num_row = len(m)
num_col = len(m[0])
island_list = []
# Identify islands and put ... |
d254a329b5c93fdd4d96acaf29dbc9ad12d51a6a | alfredolozano/cosa | /cosa/utils.py | 4,318 | 3.640625 | 4 | import random
from typing import Tuple, List
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d
from PIL import ImageDraw, Image
def random_color() -> Tuple[int, ...]:
"""Return a random color
Args:
None
Returns:
Tuple[int,...]: A random RGB colour.
"""
red = r... |
6b34f3248a91fd2b4decbf329d46798e9d3524e2 | junu126/TIL_JS | /python/class.py | 1,321 | 3.796875 | 4 | class Calculator:
def __init__(self):
self.result = 0
def add(self, num):
self.result += num
return self.result
def sub(self, num):
self.result -= num
return self.result
cal1 = Calculator()
cal2 = Calculator()
#print(cal1.add(10))
#print(cal1.add(34))
#print(cal2.... |
a6b5afea50bfb95264937b9a79cb2cd4677d0d45 | aofrigerio/ordenacoes | /heapsort.py | 821 | 4.21875 | 4 | def heapify(A, n, i):
print(A)
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and A[i] < A[l]:
largest = l
# See if right child of root exists ... |
076a1ff1556bf140d838529270121ebd99ecc86f | halljm/murach_python | /exercises/ch02/test_scores.py | 660 | 4.375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")
# get scores from the user
score1 = int(input("Enter test score: "))
score2 = int(input("Enter test score: "))
score3 = int(input("Enter test score: "))
total_score ... |
58eab49e37390a126595c08d9e564a3b779009a5 | anonranger/k10math | /Algebra/algebra_left_equal.py | 532 | 3.84375 | 4 | import random
list1 = ['+','-']
txt = input("Enter the number of questions you want to generate : ")
try:
val = int(txt)
C = 'X = '+'Y'+random.choice(list1)+str(random.choice([i for i in range(1,11)]))
class C():
def __str__(self):
return 'X = '+'Y'+random.choice(list1)+str(random.choice([i for i in range(1,11)... |
6367f8af1f52dbc6847cd3d8f42d88cd90996d1f | anonranger/k10math | /fractions-money/source.py | 2,105 | 4 | 4 | import random
def FatFraction(x):
a = random.randint(1, 9) * x
b = random.randint(1, 9) * x
if a > b:
print(str(b) + "/" + str(a), end=" ")
else:
print(str(a) + "/" + str(b), end=" ")
def FatMultiplication():
k = random.randint(2, 100)
x = random.randint(2, 9)
... |
3ddac47fb3caaefd39bf359cf25aa81b6a9bd20f | anonranger/k10math | /ninjamath_mt.py | 305 | 4 | 4 | i = 1
j = 1
mr = 1
while i <= 12:
print ("Multiplication Table :"+str(i))
while j <= 12:
mr = i * j
#print(i)
#print(j)
#print(mr)
print(str(i)+"*"+str(j)+"="+str(mr))
j = j + 1
print("\n")
i = i + 1
j = 1
|
57434aaee8a6acf40f9b8d5185a39b9fc6783f9d | AkashGandhare/python_pract | /if_loop_pract.py | 138 | 3.9375 | 4 | name = "Tranky"
if name == "sammy":
print("Hi sammy")
elif name == "Franky":
print("Hi Franky")
else:
print("Please tell your name") |
c2c2bf4bcf47b7a4bc15bbf0b333ff6fe52eda3b | jhertzberg1/bmi_calculator | /bmi_calculator.py | 1,364 | 4.375 | 4 | '''
TODO
Greeting
Create commandline prompt for height
Create commandline prompt for weight
Run calculation
Look up BMI chart
Print results
'''
def welcome():
print('Hi welcome to the BMI calculator.')
def request_height():
height = 0
return height
def request_weight():
'''Commandline user input fo... |
8cb7e358ef8c158eb55c9d7b88919f956e6d7c3a | nealebanagale/python-training | /16_OOP/04_data_classes/post_init.py | 608 | 3.921875 | 4 | from dataclasses import dataclass
@dataclass # decorator to set data class > 3.7
class Book:
title: str # typehints > 3.5
author: str
pages: int
price: float
# post_init function
# - after object has been initialized via built-in __init__
# - add additional attributes that depen... |
46e74ba066e9b5420087fe112ab9aede6697aa13 | nealebanagale/python-training | /16_OOP/03_magic_methods/string_representation.py | 794 | 3.90625 | 4 | class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
# provide a user-friendly string description of the object
# used for display
def __str__(self): # override
return f"{self.title} by {self.author}, costs {se... |
11c293b47524b69be1796dfc3c74f2a993c86a83 | nealebanagale/python-training | /16_OOP/04_data_classes/data_classes_start.py | 644 | 3.734375 | 4 | from dataclasses import dataclass
@dataclass # decorator to set data class > 3.7
class Book:
title: str # typehints > 3.5
author: str
pages: int
price: float
# regular method
def bookinfo(self):
return f"{self.title}, by {self.author}"
b1 = Book("War and Peace", "Leo Tolst... |
c0fe75e5d642b371bcc1e17a83c25ab5d7fac18a | nealebanagale/python-training | /13_Built-in_Functions/types.py | 525 | 3.796875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = '47' # literal string
y = int(x) # int - returns int from another type
print(f'x is {type(x)}')
print(f'x is {x}')
print(f'y is {type(y)}')
print(f'y is {y}')
x2 = -47.3
y2 = abs(x2) # absolute
print(f'y2 is {type(y2)}')
print(f'y2 is {y2}')
... |
a45dc8e608aa095066e98b405fdc4c1719da823a | nealebanagale/python-training | /08_Structured_Data/lists.py | 948 | 4.15625 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# [] - list are imutable
# () - tuple are not mutable
def main():
game = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock']
print(game[1]) # access list elements
print(game[1:5:2]) # same with range's start,stop,step\
i = game.index('Paper... |
77f7cdd4abda9575a31977a5d31045174ae0560b | deepakbeatz/DataStructures-Algorithm | /strings/q3.py | 136 | 3.671875 | 4 | def substring(s):
for i in range(len(s)):
for j in range(i+1,len(s)+1):
print(s[i:j])
substring('snb')
|
4d10ea90a0a9c4bcea72d6bd550ce6a9a975ff98 | deepakbeatz/DataStructures-Algorithm | /graph/bfa.py | 593 | 3.625 | 4 | vertices=['a','b','c','d']
edges=[('a','b'),('b','c'),('c','d'),('c','a'),('a','d')]
def bfs(vertices,edges):
g={}
visited={}
for i in vertices:
g[i]=[]
visited[i]=False
for e in edges:
v1,v2=e
if(v2 not in g[v1]):
g[v1].append(v2)
... |
21e2f38385cb80f7aa32eb472b0c34cf9def747d | deepakbeatz/DataStructures-Algorithm | /practice/stack.py | 321 | 3.765625 | 4 | class stack:
def __init__(self):
self.stack=list()
def push(self,k):
self.stack.append(k)
def pop(self):
temp=self.stack.pop()
return temp
def print(self):
print(self.stack)
s=stack()
s.push(10)
s.push(20)
s.push(40)
s.pop()
s.print(... |
7df861ce3467cb871fce042f17a4b839f2193379 | Liam-Hearty/ICS3U-Unit5-05-Python | /mailing_address.py | 1,981 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: October 2019
# This program finds your mailing address.
def find_mailing_address(street, city, province, postal_code, apt=None):
# returns mailing_address
# process
mailing_address = street
if apt is not None:
mailing_address = ... |
457af79f7bb9e912f1c1880086c3688200c5b7b2 | dKosarevsky/clipy | /wcCliPy_f.py | 724 | 3.640625 | 4 |
# filename = '/etc/passwd'
def countCli(fname):
try:
f = open(fname, 'r')
text = f.read()
f.close()
except IOError:
print(f'File {fname} not found')
raise SystemExit
num_lines = text.count('\n')
list_words = text.split(None)
num_words = len(list_words)
... |
c011516e09ef637e72e52bb32c6c124692a3c5f7 | jamesqiao1993/Hacking-Secret-Ciphers | /ReverseCipher/reverseCipher.py | 429 | 3.859375 | 4 | #Reverse Cipher反转加密
#加密
message = 'Three can keep a secret, if two of them are dead.'
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print(translated)
#解密
#message = 'Three can keep a secret, if two of them are dead.'
translated2 = ''
i = len(message) - 1
... |
a46c45d6950463dc4eec2ba1e38300065b17e947 | MannParutthi/CompetitiveProgramming | /ANewPassword.py | 967 | 3.5 | 4 | # https://codeforces.com/contest/770/problem/A
lengthOfPassword, noOfDistinctSymbols = [int(x) for x in input().split(' ')]
password = ''
possibleChars = ' abcdefghijklmnopqrstuvwxyz' # It starts from 1 so ' ' in added in the start
noOfDistinctSymbolsInPassword = 0
for i in range(lengthOfPassword):
if ... |
5919f06f9337b58e5eb614cf935b0ee5d447562e | MannParutthi/CompetitiveProgramming | /ADieRoll.py | 338 | 3.65625 | 4 | # https://codeforces.com/contest/9/problem/A
points = [int(x) for x in input().split(' ')]
minPointDotNeedsToWin = max(points[0], points[1])
dictOfDiceProbability = {1: '1/1', 2: '5/6', 3: '2/3', 4: '1/2', 5: '1/3', 6: '1/6'}
probabilityOfDotToWin = dictOfDiceProbability[minPointDotNeedsToWin]
print(probab... |
abb16b68b1f2de5bcd49ca94f7429f283536949b | Bosslv0/146P3 | /src/mcts_modified.py | 5,604 | 3.640625 | 4 |
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
num_nodes = 200
explore_faction = 2.
def traverse_nodes(node, board, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from which the search is traversing.
... |
7ceafdd5fbb66740bd0a4a479c54dfe0d54149ae | ImHouses/Modelado-y-Programaci-n | /Proyectos/proyecto02/lib/listaArchivos.py | 1,029 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import dirname, abspath
class ListaArchivos(object):
"""Clase para lista de archivos"""
def __init__(self):
"""Constructor."""
d = dirname(dirname(abspath(__file__)))
l = open(str(d) + "/files/FILES.dat", "r").readlines()
self.lista = []
for linea ... |
6722c395fb98da6845c373545dc7cb1b1c5bbd01 | ImHouses/Modelado-y-Programaci-n | /Practicas/practica3/pokemon.py | 6,040 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import random
# Clase para representar ataques.
# Los ataques tienen puntos de daño y un nombre para identificarlos.
class Ataque:
#Constructor
def __init__(self, nombre):
self.nombre = nombre
self.dano = random.randint(25,50)
# Clase para representar pokemon.
#
# Lo... |
05d0b456a2d7e53975d1fbd9187623548b056211 | DanielMevs/python_generators_map | /p1.py | 465 | 3.921875 | 4 | def mapflatlst(lst, fun):
if len(lst) == 0:
return []
else:
return [fun(lst[0])] + mapflatlst(lst[1:], fun)
def times2(x):
return x*2
def maplst(lst, fun):
if len(lst) == 0:
return []
elif type(lst[0]) == list:
return maplst(lst[0] + lst[1:], fun)
else:
... |
c672cbad5d975d681989ed8fda89ca4c844609c7 | kartiknagpal/sandbox | /py-sandbox/OOD/food.py | 5,391 | 4.28125 | 4 | class Fridge:
"""
This class implements a fridge where ingredients can be added and removed individually,
or in groups.
The fridge will retain a count of every ingredient added or removed, and will raise an error
if a sufficient quantity of ingredient isn't present.
Methods:
has(food_name[, quantity]) - checks i... |
f5095b8f30050808cadf567a0c8534d24c6ed3fc | navinchandak/bookParser | /g05_bookactors.py | 11,770 | 3.734375 | 4 | from fileparser import lineread
def title_author(f):
while(1):
line=f.readline()
if(line.startswith('Title:')):
words=line.split()
title=""
for i in range(1,len(words)):
title+=words[i]+" "
print "Title of Author: ",title
if(line.startswith('Author:')):
words=line.split()
author=""
for ... |
63d22f1aa1b8dbb3eba550cce8cbc1d52e41d0e3 | Rnalter/calculate-pi-archimedes | /calculate_pi.py | 274 | 3.546875 | 4 | import math
N = float(6)
S = float(1)
#Iterating uptil N is 96 sides
for i in range(2,7):
d = math.sqrt(1 - pow(S/2,2))
a = 1 - d
NewS = math.sqrt(pow(a,2) + pow(S/2,2))
Perimeter = float(N * S)
Pi = Perimeter/2
print(Pi)
S = NewS
N = N*2.0
|
298999c27e99891052fc112c0a163498878d46f3 | yungo1846/Algorithm_Python | /그리디/그리디_1_뒤집기.py | 494 | 3.609375 | 4 | string = input()
zero_count = 0
one_count = 0
for index, letter in enumerate(string):
if index == 0: # 첫 글자
pre_letter = letter
continue
if pre_letter != letter:
if pre_letter == '0':
zero_count += 1
else:
one_count += 1
if index == len(string) - 1: ... |
42e7f35009398df65613ff16c51235bbf40ab3aa | abdullah-alnahas/polynomials-classification | /generatePolys.py | 5,301 | 3.984375 | 4 | """
This module generates polynomials of degrees 1 to d.
The generated polynomials are saved to a .csv file.
"""
import argparse
import numpy as np
from numpy.random import choice
def generatePoly(degree, numOfComplexRoots, numOfSquareRoots, rootsRange):
"""
This function generates a polynomial of degree 'de... |
49991f5faf70c66c80386217a71b22401896e7fe | bestarewa/practical | /duplication.py | 569 | 4.03125 | 4 | #/usr/bin/env python3
'''
__author__ = ' abba y abdullahi, abbayabdullahi@gmail.com'
'''
import turtle
def draw_lines(color, y):
""" Draws 10 horizontal lines of a given color stacked
on top of each other with the lowest line appearing
at position y on the y axis."""
turtle.color(color)
for x in range(10... |
e932902186cef0ca666f76f175c58ea71fb405a7 | bestarewa/practical | /practical/mtrack.py | 268 | 3.8125 | 4 | #!usr/bin/env python3
'''
__author__ = 'abba y abdullahi , abbayabdullahi68@gmail.com'
'''
import turtle
def report_position(x, y):
'''Simply prints the values of x and y.'''
print("x =", x, " y =", y, flush=True)
turtle.onscreenclick(report_position)
turtle.mainloop()
|
23c9d14ecf2d3140551c1967fd41d065c9fae935 | ThrallOtaku/LeetCode | /sortedArrayToBST.py | 877 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
... |
65b7c4bf7c3f7e8c749ca89e79fa447b3734b3e2 | ThrallOtaku/LeetCode | /pass/easy/2018-06-28/peakIndexInMountainArray.py | 940 | 3.828125 | 4 | # 我们把符合下列属性的数组
# A
# 称作山脉:
#
# A.length >= 3
# 存在
# 0 < i < A.length - 1
# 使得A[0] < A[1] < ...
# A[i - 1] < A[i] > A[i + 1] > ... > A[A.length - 1]
# 给定一个确定为山脉的数组,返回任何满足
# A[0] < A[1] < ...
# A[i - 1] < A[i] > A[i + 1] > ... > A[A.length - 1]
# 的
# i
# 的值。
#
#
#
# 示例 1:
# 输入:[0, 1, 0]
# 输出:1
# 示例2:
# 输入:[0, 2, 1, 0]
# ... |
c0419cb08a0c98b1c918d77a84cd077d58f195f1 | frekkanzer2/PythonTests | /Exercises/ListPermutation.py | 357 | 3.78125 | 4 | from itertools import permutations
from FunctionsModules.CheckTypes import checkIfInt
def listPermutation(myList: list) -> list:
for element in myList:
checkIfInt(element)
listToReturn = permutations(myList)
return list(listToReturn)
aList = [1, 2, 3]
print(aList)
newList = listPermutation(aList... |
a1477fc623272287bc07d5fcf689f619a4b8b34f | frekkanzer2/PythonTests | /Exercises/ChildrenState.py | 1,590 | 3.59375 | 4 | class Bambino:
PRIMOANNO, SECONDOANNO, TERZOANNO, DIPLOMATO = [1, 2, 3, 4]
def __init__(self):
self.status = Bambino.PRIMOANNO
def succ(self):
if self.status == Bambino.PRIMOANNO:
self.status = Bambino.SECONDOANNO
elif self.status == Bambino.SECONDOANNO:
sel... |
197680e8cc89de194dff95be1b47892bc38e5b4d | frekkanzer2/PythonTests | /Exercises/AddMethodToClass.py | 382 | 3.75 | 4 | # Scrivere la classe MyClass il cui metodo statico addMethod prende in input un parametro funzione e se e' diverso
# da None inserisce nella classe un metodo f uguale alla funzione
class MyClass:
@staticmethod
def addMethod(method):
if method is not None:
MyClass.f = method
def myHello()... |
db90eb37c99439b03af09a3dbc082dad684f65f8 | frekkanzer2/PythonTests | /Exercises/InstancesCounter.py | 431 | 3.625 | 4 | # Create a script that counts the instances of a Class
class Counter:
numberOfInstances = 0
@classmethod
def newInstance(cls):
cls.numberOfInstances += 1
@classmethod
def getNumberOfInstances(cls):
return cls.numberOfInstances
def __init__(self):
self.newInstance()
... |
d5edf80bed870101c7da0e3f9c9f70b59783fe46 | dudueasy/Python-Practice | /Python basic/购物车_函数.py | 1,799 | 3.921875 | 4 | class Product:
def __init__(self, id: object, name: object, price: object) -> object:
self.id = id
self.name = name
self.price = price
def get_money():
salary = input("please input your salary: ")
if salary.isdigit():
return int(salary)
else:
print('请输入正确的格式\n')
... |
5ced90450a9abe670c84ba9a9e2519eed0b8255d | anuchakradhar/python_projects | /beginner-projects/quiz_game.py | 884 | 4.0625 | 4 | print("Welcome to my quiz game !!!")
playing = input("Do you want to play?? ")
if playing.lower() != "yes":
quit()
print("Let's play")
score = 0
answer = input("What does CPU stands for? ")
if answer.lower() == "central processing unit":
print("Correct!")
score += 1
else:
print("Wrong A... |
f14694d94a28b3ab37f774f4b3f39c9ab7170400 | pfierros/computer_science_150 | /montecarlo.py | 944 | 4.03125 | 4 | #Author: <name>
#Date: <date>
#Language: Python3
#Assignment: Lab 1, montecarlo.py
#Class: CSCI150
###########################################################################
#DEPENDENCIES
import random
import picture as p
###########################################################################
#Create ... |
1e3f1927787e257817dc04842cfa2bc3a99cb564 | keroido/Self_Taught_Programmer | /0805-C12.py | 633 | 3.734375 | 4 | #Challenge12
#1
class Apple:
def __init__(self,w,c,t,s):
self.weight = w
self.color = c
self.taste = t
self.smell = s
#2
class Circle:
def area(self,r):
import math
self.r = r
return math.pi * self.r**2
maru = Circle()
print(maru.area(3))
#3
class Tria... |
88c99dfe4f48939682df9ac6703c3ce26e81684a | tmdtlr7031/AlgorismRepo | /python/Programmers/정렬구현하기/BubbleSort.py | 931 | 3.765625 | 4 | '''
버블정렬
- 서로 인접한 두 원소를 검사하여 정렬하는 알고리즘 (선택정렬과 기본개념 유사)
- 일반적으로 자료의 교환 작업(SWAP)이 자료의 이동 작업(MOVE)보다 더 복잡하기 때문에 버블 정렬은 단순성에도 불구하고 거의 쓰이지 않는다.
- O(n^2)
1. (7,4), (4,5) ... (1,3) => 4번만 돌면됨.
2. 안에 값들은 1회차 : 3까지, 2회차는 1까지, 3회차는 5까지 --> 1회차 : range(4)까지만. 왜냐면 n, n+1로 바로 다음 값 찾아야하니까 idx 0~3까지하면 (0,1)(1... |
00d34e3bf001cc83a7ad80c5b51492c5206d5974 | tmdtlr7031/AlgorismRepo | /python/Programmers/시저암호.py | 589 | 3.5625 | 4 | # 시저암호 (https://programmers.co.kr/learn/courses/30/lessons/12926)
def solution(s, n):
answer = ''
alphLow = 'abcdefghijklmnopqrstuvwxyz'
alphUp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in s:
if i == ' ':
answer += ' '
continue
elif i in alphLow:
answer +=... |
819e67a17b051cb1176902506ff7070713c97ce3 | tmdtlr7031/AlgorismRepo | /python/Programmers/PairDelete.py | 1,834 | 3.671875 | 4 | # 짝지어 제거하기
# def solution(s):
# '''
# 접근
# 1) 앞에서부터 비교
# 2) 연속되면 연속된거 이전 + 이후 합쳐서 리스트 만들고 반복
# 3) 효율성 실패.. 일부 테스트 실패
# '''
# flag = False
# lists = list(s)
# while 1:
# if len(lists) == 0:
# return 1
# for i in range(len(lists)-1)... |
667f39915d173c51c3a2777555d9db7e2f6659da | tmdtlr7031/AlgorismRepo | /python/Programmers/TargetNumber.py | 1,896 | 3.578125 | 4 | # 타겟넘버
'''
접근 방법
1) 기존 '소수 만들기'에서 사용했던 combinations 에서 착안해 카디션프로덕트가 가능한 itertools의 product 이용
2) 제시된 리스트의 요소마다 -1,1을 곱한 값을 별도의 list로 만들고 ex) [1,1,1] => [[-1,1],[-1,1],[-1,1]]
3) 카디션프로덕트 진행
'''
from itertools import product
def solution(numbers, target):
# data = [[1,1,1,1,1],[-1,-1,-1,-1,-1], [1,1,1... |
5ed81b695361edbf93d91b639d13b54dd7d938ba | salymk/rps.py | /rps.py | 4,602 | 4.375 | 4 | # !/usr/bin/env python3
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
import random
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 in response:
... |
80d6c12e189908c5145ecf9d438dc586178bfa2e | usrfrndly/ChordBuilder | /EvenTempermentTest.py | 1,371 | 3.640625 | 4 | """
Jaclyn Horowitz
Music Software 2014
"""
import csv
import this
csv_list = []
# Change csv file to be compared to here
with open('even_temperment_sheet_phase4.csv', 'rU') as my_file:
reader = csv.reader(my_file, skipinitialspace=True, delimiter=',', quoting=csv.QUOTE_NONE)
# Skip all empty rows
# for ... |
95095f250d06008b88c46c651dc1c4ee631a77e7 | ZNNNNZ/pratice_code | /code40.py | 989 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
ret... |
a853ceec1af93ed105d665ab3c43b9c440c64a1e | ZNNNNZ/pratice_code | /code28.py | 5,586 | 3.546875 | 4 | '''
给定一个字符串
{xxx[xxx{xxx}]xx{x[xxx]xxx{xxx}xx}x}
判断其中的 {}[]() 是否成对出现
成对出现输出True,未成对出现输出False
在这里我们用栈的方法来实现
'''
class Stack():
def __init__(self):
self._data=[]
def push(self,data):
self._data.append(data)
def pop(self):
return self._data.pop()
def get_size(self):
retur... |
91070a31796df9ccaa90435de0ae14cdc26b394c | ZNNNNZ/pratice_code | /code37.py | 678 | 3.796875 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def helper(left,right):
if left >= r... |
4084d2c7a45e8921a0d54449871afde44e734235 | ZNNNNZ/pratice_code | /code11.py | 564 | 3.5 | 4 | # 一只青蛙一次可以跳上1级台阶,也可以跳上2级。
# 求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
class Solution:
def jumpFloor(self, number):
# write code here
if number==0:
return 0
if number==1:
return 1
A = [1, 2]
for i in range(3,number+1):
tmp=A[0]+A[1]
A... |
74a7c41bd386d33b820cfc3a6a8fc1c98075b3b2 | cllmsbrn/HackerRankSolutionsInPython | /src/plus_minus.py | 594 | 4.09375 | 4 | def plus_minus(arr):
positives = 0
negatives = 0
zeros = 0
for element in arr:
if element > 0:
positives += 1
elif element < 0:
negatives += 1
else:
zeros += 1
positive_fractions = "{0:.6f}".format(positives / len(arr))
negative_fract... |
19081ca514d8b03a94e9132cd4cd00ba71692aad | zhangtongds/code-challenges | /IC-code-challenges/shuffle.py | 405 | 3.78125 | 4 | import random
def shuffle(the_list):
rest = len(the_list)
while rest != 0:
rand_i = random.randint(0, rest-1)
the_list[len(the_list)-rest],the_list[rand_i] = the_list[rand_i], the_list[len(the_list)-rest]
rest -= 1
return the_list
sample_list = [1, 2, 3, 4, 5]
print 'Sample list:',... |
cb7e966781a96121035c9489b410fcc1ace84537 | yashaswid/Programs | /LinkedList/MoveLastToFirst.py | 1,325 | 4.28125 | 4 | # Write a function that moves the last element to the front in a given Singly Linked List.
# For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4
class Node:
def __init__(self,val):
self.data=val
self.next=None
class Linkedli... |
5b1a2d7f3f5f2c338d17c63bdece24512e2af0ba | yashaswid/Programs | /LinkedList/CountElement.py | 1,092 | 4.03125 | 4 | # Write a function that counts the number of times a given int occurs in a Linked List
# Given a singly linked list and a key, count number of occurrences of given key in linked list.
# For example, if given linked list is 1->2->1->2->1->3->1 and given key is 1, then output should be 4.
class Node:
def... |
2f1e3233890e47760670bd37dde308fa3f2cabd8 | yashaswid/Programs | /Sorting/InsertionSort.py | 446 | 3.921875 | 4 | def InsertionSort():
a=[19,8,4,0,91,26,1,100,35]
print("Elements before sorting",a)
for i in range(len(a)):
for j in range(i+1,len(a)):
k=i
yash=j
while(k>=0 and a[k]>a[yash] ):
temp=a[k]
a[k]=a[yash]
a[yas... |
1f6f05827e1d2b523250e4c226d6320920d2adb1 | TaroNguyen/Programming | /PythonTutorial/3 Test.py | 347 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 11 12:34:09 2017
@author: dito-maf
"""
# Counting the number of lines in the file
print("Number of lines: " + str(len(lines)))
# Counting the keys in the dictionary; should equal the number of lines in the file
print("Number of dictionary keys: " ... |
a2f20732a517f70e6601a9dbd96abe13ee3cf71b | leegengzhao/python_crash_course | /chap4/one_million.py | 838 | 4.0625 | 4 | # List of numbers from 1 to 1 million
million_numbers = list(range(1,1000001))
#print(million_numbers)
print(min(million_numbers))
print(max(million_numbers))
print(sum(million_numbers))
# Odd numbers from 1 to 20
odd_numbers = list(range(1,20,2))
print(odd_numbers)
# Multiple of 3 from 3 to 30
multi_3_numbers = []
for... |
4e35112282fbaccdf62d4aea0ae67bd9446e6117 | Viole-Grace/Python_Sem_IV | /3a.py | 1,688 | 4.28125 | 4 | phones=dict()
def addentry():
global phones
name=raw_input("Enter name of the phone:")
price=raw_input("Enter price:")
phones.update({name:price})
def namesearch(name1):
global phones
for key,value in phones.items():
if name1==key:
print "Found, its price is ",value
def price... |
b51bd5715381c2a8f6032781e7703369ef8a77d3 | Viole-Grace/Python_Sem_IV | /8b.py | 934 | 4.03125 | 4 | class QEmpty(Exception):
pass
class QFull(Exception):
pass
class QUEUE():
q=[]
def __init__(self,size):
self.size=size
def insert(self,data):
if len(QUEUE.q) > size:
raise QFull
else:
self.data=data;
QUEUE.q.append(self.data)
def delete(self):
if len(QUEUE.q) == 0:
ra... |
952424697df0de1fec627210be82d887186e52f4 | Viole-Grace/Python_Sem_IV | /3b.py | 1,144 | 3.75 | 4 | class bank:
def __init__(self):
print('Enter A/c no, Balance, Rate of Interest, Overdraft Limit, Overdraft Fee Rate ')
self.acno,self.bal,self.rate,self.olim,self.ofee=[int(x) for x in raw_input().split()]
self.overdraft=0
def withdraw(self,amt):
if amt + self.overdraft < self.ol... |
571c1db047fd45cf9a73414eb1b246f15ce3f3e3 | hickmanjv/hickmanjv | /CS_4085 Python/Book Examples/coin_toss_demo.py | 401 | 4.25 | 4 | import coin
def main():
# create an object of the Coin class
my_coin = coin.Coin()
# Display the side of the coin that is facing up
print('This side is up: ', my_coin.get_sideup())
# Toss the coin 10 times:
print('I am going to toss the coin 10 times:')
for count in range(10):
my_... |
b6c76c4ea947f744ec6e82126005b3e788a1349a | hickmanjv/hickmanjv | /CS_4085 Python/ObjectPosnCalc/objectposncalc.py | 3,140 | 4.4375 | 4 | #************************************************************
# Name: Joshua Hickman *
# Pawprint: hickmanjv *
# Assignment: Object Position Calculation *
# Date: Feb 2, 2020 *
#*********... |
b24491f72fe92e6e3b621858211a85234b045865 | TurusovMaxim/newrepository | /Fibonacci number.py | 150 | 3.8125 | 4 | fib1 = 1
fib2 = 1
n = input()
n = int(n)
i = 2
while i < n:
fib_sum = fib2 + fib1
fib1 = fib2
fib2 = fib_sum
i += 1
print (fib_sum) |
11ad3f037833066a686ca64d794c315d44706399 | TurusovMaxim/newrepository | /Coin counting.py | 1,677 | 3.921875 | 4 | element = input('Please enter some amount of money to get the optimal change: ')
if element.isdigit():
while int(element) <= 0:
element = input('Please enter a number greater than zero: ')
if int(element) > 0:
coin_fifty = int(element) // 50
coin_test = int(element) - 50 * coin_fifty
... |
00fd6a05e7ebc46b62ff21fe5b07ba715f7866ea | TurusovMaxim/newrepository | /Trapezoidal rule.py | 172 | 3.640625 | 4 | def trapezoidal(f, a, b, n):
h = float(b - a)/n
result = 0.5*(f(a) + f(b))
for i in range(1, n):
result += f(a + i*h)
result *= h
return result |
4cf4346e42004ac617e5275bfcac9098439bbee1 | jinwenmao/FoxLite | /src/tokens.py | 2,156 | 3.625 | 4 | """
Clase Token: representa la unidad más pequeña en la construcción del lenguaje. Será utilizado por el lexer
para descomponer el código fuente y por el parser para validar la gramática y crear el AST.
"""
from enum import Enum
class TokenType(Enum):
# Fin del código fuente
EOF = 'EOF'
# Nueva l... |
930823a3a660181523051ea026e28d71912105af | anastasts/Exercises | /apple.py | 509 | 3.78125 | 4 | print('Enter the number of people:')
n = int(input())
print('Enter the amount of apple:')
k = int(input())
if (n <= 0 or k <= 0) or (n > 1000 or k > 1000):
print('Error')
exit(0)
else:
if n == k: #если кол-во яблок совпадает с кол-во студентами
print('Everyone has ' + str(n // k) + ' apple')
eli... |
1ae3c46fb837674c703c634198f90d70f44c8a4f | anastasts/Exercises | /str (2).py | 104 | 3.515625 | 4 | a = input()
print(len(a))
b = input()
while a != b:
print(len(b))
a = b
b = input()
|
790117c07f7aa5a52cf0e2d82c6da96feb7e9034 | ElizavetaBar/Homework-1q | /5.1.py | 276 | 3.703125 | 4 | text = input('Введите слова: ')
with open('my_file_new.txt', 'a+', encoding='utf-8') as loly:
while text:
loly.write('\n' + text)
text = input('Введите слова: ')
if not text:
break
print(loly.read())
|
4b077a551d293efb0916692b247e2176efe6f0ff | ElizavetaBar/Homework-1q | /3.4.py | 296 | 3.5625 | 4 | def my_func(x, y):
return 1 / (x ** y)
print(my_func(int(input('Введите число, которое возведем в степень: ')),
abs(int(input('Введите отрицательное число, в которое бцдем возводить')))))
|
697ca59718ce9082565cbdad3266ea84d2d6169e | ElizavetaBar/Homework-1q | /5.py | 1,187 | 3.625 | 4 | n = int(input('Введите вашу выручку за год: '))
while n < 0:
n = int(input('Выручка не может быть отрицательной. Введите положительное число: '))
if n > 0:
continue
m = int(input('Введите ваши издержки за год: '))
while m < 0:
m = int(input('Ихдержки не могут быть отрицательными. Вы же потр... |
a4edac5c3c2f4ceca8a9e7aac06e8e4922b4f669 | ElizavetaBar/Homework-1q | /2.3.py | 683 | 3.71875 | 4 | # n = int(input('Введите значение месяца в формате 1 -12: '))
#
# if n in (1, 2, 3):
# print('Это зима!')
# else:
# n = int(input('Введите значение месяца в формате 1 -12: '))
w = [1, 2, 3]
sp = [4, 5, 6]
su = [7, 8, 9]
au = [10, 11, 12]
n = int(input('Введите значение месяца в формате 1 -12: '))
... |
47911b2f9bfccb2d38b442b0bd3680f7200a97a2 | sergey-jr/InfoSecurity | /cipher/squares.py | 492 | 3.5625 | 4 | import random
from numpy import array
random.seed()
russian = ''.join([chr(i).lower() for i in range(ord('а'), ord('я') + 1)])
alphabet = [[[], []], [[], []]]
for i in range(2):
for j in range(2):
random.seed()
tmp = "".join(random.sample(russian, 25))
for k in range(5):
tmp_arr... |
3eaae148c6cbaffe1878a065d9e831b70c1c31a0 | serenityd/Python | /06studentinfo.py | 2,285 | 3.953125 | 4 | side='='*48
print(side)
print('学生成绩管理系统'.center(len(side)-5))
print(side)
print('输入1:添加学生信息')
print('输入2:查找学生信息')
print('输入3:删除学生信息')
print('输入4:修改学生信息')
print('输入5:显示所有学生信息')
print('输入6:按成绩排序')
print('输入7:退出')
print(side)
totalstudeninfo=[]
while True:
key=input('请输入操作代码:')
if key == '1':
stu={}
... |
9147bd78ebf81e9064564f6e172f4a84fea8a491 | Nowshin021/Python | /N_queen_algo.py | 1,313 | 3.984375 | 4 | # takes a location i , j in the matrix:
def is_danger(rowNo, colNo):
# check the rows cols if there is any queen present (queen==1)
for i in range(0, n):
if board[rowNo][i] == 1 or board[i][colNo] == 1:
return True # queen present here
# check diagonal:
for i in range(0, n):
... |
6ba29d8e8505d896bded106677a7f0661e7b80e4 | csummers77/objects | /in.py | 641 | 3.796875 | 4 | class Car(object):
def __init__(self,make,model,mpg):
self.make = make
self.model = model
self.mpg = mpg
def startCar(self):
print "%s goes Vroom" % self.make
myCar = Car('ford','focus', 40)
myCar.startCar()
class ElectricCar(Car):
# call this object constructor
def __in... |
aabebdb84e10f2ef4a37756005f0313ae8f8a5bb | farisachugthai/instapy | /hello_world_tweepy.py | 6,392 | 3.5 | 4 | #!/usr/bin/env python
"""A basic script show casing how to use tweepy.
====================
Tweepy functionality
====================
Over time, the names of various Twitter concepts have evolved, some old names are still used in Tweepy. So keep in mind that, in the context of this article, these equivalences hold:
... |
1a4109dab56f6f6ff3b95dc43c45083365f361fb | RubenBranco/AD2018 | /net_client.py | 1,758 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Aplicações distribuídas - Projeto 2 - net_client.py
Grupo: ad007
Números de aluno: 50006, 50013, 50019
"""
# zona para fazer importação
from sock_utils import create_tcp_client_socket, receive_all
import socket as s
import struct
import pickle
# definição da classe serv... |
62a1072f01c4c59f8b50af358a9623766a7eb280 | rickhysis/grpc-binary-gap-example | /binary_gap.py | 401 | 3.65625 | 4 | def count_gap(number):
try:
binary = bin(number)
finalMax = 0
currentMax = 0
for i in range(len(binary)) :
currentMax = 0
while binary[i] == '0':
currentMax += 1
i += 1
finalMax = max(finalMax, currentMax)
... |
314fd15f4a21543476e16d2a56d3e5d3c775a3f4 | woodfishman/NogiGuess | /nogiguess.py | 1,837 | 3.953125 | 4 | #!usr/bin/env/python
#-*- coding=utf 8 -*-
#This is a very simple guess game.
#I may add hints to it sometime.
import pandas as pd
import sys
import random
import csv
def prepare(df):
name=random.sample(list(df.index.values),1)
qlist=list(df.columns.values)
qs=random.sample(qlist,6)
return name,qs
d... |
46b12e0ddfbffaa99f081c2d3eb0de16932fea45 | Vinit43/Python_Programs | /Arithmetic_Package/Main.py | 440 | 3.984375 | 4 | import Arithmetic
def main():
value1=int(input("Enter the first number"))
value2=int(input("Enter the second number"))
ret=Arithmetic.Add(value1,value2)
print("Addition is:",ret)
ret=Arithmetic.Sub(value1,value2)
print("Substraction is:",ret)
ret=Arithmetic.Mul(value1,value2)
print("Multiplic... |
ba637b94468363d36ca356d99864269802567b76 | Vinit43/Python_Programs | /MultiThreading(MUTEX)/Main.py | 932 | 3.828125 | 4 | #This program is known as MUTEX
import threading
import os
Amount = 1000
def ATM(func ,lock):
func(lock)
def Deposit(lock):
lock.acquire()
value=int(input("Enter the amount to Deposit\n"))
global Amount
Amount = Amount + value
print("Dposit successful\nBalance-:",Amount)
lock.relea... |
c767088cf3f17a5948ec8cfacf814015b8c2bbd3 | Vinit43/Python_Programs | /OOP_in_Py/Main.py | 468 | 4.0625 | 4 |
class Demo:
x=10
y=20
def __init__(self):
print("inside special function")
self.i = 30
self.j = 40
def __del__(self):
print("Inside destructor like function")
def fun(self):
print("Inside function")
def main():
obj1 = Demo()
obj2 = Demo()
obj1.fun()
obj2.fun()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.