blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
661f72b8fad2cc169be81442c4a823c448933b35 | jedzej/tietopythontraining-basic | /students/stachowska_agata/lesson_02_flow_control/number_of_zeros.py | 127 | 3.765625 | 4 | zeroes = 0
N = int(input())
for i in range(N):
number = int(input())
if number == 0:
zeroes += 1
print(zeroes)
|
5e506b64252cdd2a0c3d0a3e1f886b4bd02422e5 | jedzej/tietopythontraining-basic | /students/chylak_malgorzata/lesson_02_flow_control/the_number_of_elements_equal_to_maximum.py | 229 | 3.78125 | 4 | maximum = 0
last_number = 0
element = -1
while element != 0:
element = int(input())
if element > maximum:
maximum, last_number = element, 1
elif element == maximum:
last_number += 1
print(last_number)
|
878f0faf7a7ab7caa19c504133b058008e02645b | jedzej/tietopythontraining-basic | /students/arkadiusz_kasprzyk/lesson_03_functions/badly_organized_calculator.py | 1,316 | 4.15625 | 4 | # functions
def help():
"""help
"""
print("a - add")
print("s - subtract")
print("m - multiply")
print("d - divide")
print("p - power")
print("h,? - help")
print("q - QUIT")
def inputs(message):
"""data input
message : str
"""
print(message)
var_1 = int(input(... |
2a56ee6aeeca78e4314ccdcecf5306d047e8d5a0 | jedzej/tietopythontraining-basic | /students/slupek_bartosz/lesson_01_python_basic/Sum_of_digits.py | 81 | 3.546875 | 4 | a = int(input())
d1 = a // 100
d2 = a // 10 % 10
d3 = a % 10
print(d1 + d2 + d3)
|
cfb9b535ab88678bc0a3b9b27ae34c460cb1d82c | jedzej/tietopythontraining-basic | /students/swietczak_monika/lesson_01_basics/total_cost.py | 316 | 3.953125 | 4 | # Read an integer:
dollars = int(input("How many dollars a cupcake costs: "))
cents = int(input("How many cents a cupcake costs: "))
n = int(input("How many cupcakes you buy: "))
sum_of_dollars = dollars * n + (cents * n) // 100
sum_of_cents = (cents * n) % 100
print(str(sum_of_dollars) + " " + str(sum_of_cents))
|
18a5428df0b30823a128701f9634e21ecc2e585f | gaurav324/interviews | /42_add_Expression_solver+palantir+interview+recursion+telephonic.py | 2,832 | 3.5625 | 4 | # This is the text editor interface.
# Anything you type or change here will be seen by the other person in real time.
"""
ONE 231
+ONE +231
---- ----
TWO 462
FOUR 5239
+FOUR +5239
----- -----
EIGHT 10478
FOUR 8140
+ONE +139
---- ----
FIVE 8279
"""
class Expression(object):
# Gets a se... |
7ec3b8787509e3998b2f05e8f296bcb2e4b5c4f9 | sjpark-dev/python-practice | /problems/etc/problem3.py | 191 | 4.0625 | 4 | word = input()
res = ''
for char in word:
a = ord(char)
if 97 <= a <= 122:
a = 122 - (a - 97)
elif 65 <= a <= 90:
a = 90 - (a - 65)
res += chr(a)
print(res)
|
8e704fa757dae3f4f249bfec3e07ac43719771cd | sjpark-dev/python-practice | /problems/programmers/level_1_to_2/p12.py | 321 | 3.78125 | 4 | # N개의 최소공배수
import math
def solution(arr):
while len(arr) >= 2:
a = arr.pop()
b = arr.pop()
arr.append(lcm(a, b))
answer = arr[0]
return answer
def lcm(a, b):
gcd = math.gcd(a, b)
return a * b // gcd
if __name__ == '__main__':
print(solution([1,2,3]))
|
2317db3bc82a2fd50afc7be9c67a7e226a6272da | sjpark-dev/python-practice | /problems/programmers/level_1_to_2/p11.py | 419 | 3.53125 | 4 | # 행렬의 곱셈
def solution(arr1, arr2):
m = len(arr1)
n = len(arr2[0])
a = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
sum = 0
for k in range(len(arr1[0])):
sum += arr1[i][k] * arr2[k][j]
a[i][j] = sum
return a
if __name... |
c8c1963bad864b383a77727973232b4e3b7c392b | danserboi/Marketplace | /tema/consumer.py | 2,594 | 4.34375 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
import time
from threading import Thread
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
... |
2efc8e679b5e3fd1448aecc9f5b055f48f8dc734 | akramkrimo/ecommerce | /accounts/utils.py | 206 | 3.625 | 4 | import random, string
def generate_token(length=10):
sequence = string.ascii_letters + string.digits
token = ''
for _ in range(length):
token += random.choice(sequence)
return token |
35d8e0f70cfd155ab513ed9b405903a140164f19 | rkp872/Python | /6)Functions/TypesOfArgument.py | 2,926 | 4.65625 | 5 | # Information can be passed into functions as arguments.
# Arguments are specified after the function name, inside
# the parentheses.
#In python we have different types of agruments:
# 1 : Position Argument
# 2 : Keyword Argument
# 3 : Default Argument
# 4 : Variable length Argument
# 5 : Keyworded Variable... |
e87320897e3f5dfaf10564b9f79b6487649dfcc4 | rkp872/Python | /3)Conditional/SquareCheck.py | 272 | 4.34375 | 4 | #Take values of length and breadth of a rectangle from user and check if it is square or not.
len=int(input("Enter length : "))
bre=int(input("Enter breadth : "))
if(len==bre):
print("Given rectangle is square")
else:
print("Given rectangle is not a square") |
ac0091ebda2a4599eac69b2467b398a984942c5f | rkp872/Python | /1)Basics/Basic.py | 444 | 4.125 | 4 | print("Hello World")#printing Hello World
#we dont need to declare variable type as python is dyamically typed language
x=10 #aiigning value to any variable
y=20
print(x)
#basic arithmetic operator
z=x+y
print(z)
z=x-y
print(z)
z=x*y
print(z)
z=x/y # will give float result
print(z)
... |
20535fe3021a2de1f37885dc082e664bd07220b2 | rkp872/Python | /5)Arrays/InputFromUserForArray.py | 462 | 4.0625 | 4 | from array import *
val=array('i',[])
n=int(input("Enter number of elements to take : "))
for i in range(n):
x=int(input("Enter a value : "))
val.append(x) #We can use append() to insert an element to the array
#print(val)
item=int(input("Enter the value to serach : "))
for i in range(len(val)):
if... |
1af02fa80c544f52c1f2e4a2f0c767c96b14a4b6 | rkp872/Python | /2)Data Types/Set.py | 726 | 4.21875 | 4 | # Set: Set are the collection of hetrogeneous elements enclosed within {}
# Sets does not allows duplicates and insertion order is not preserved
#Elements are inserted according to the order of their hash value
set1={10,20,20,30,50,40,60}
print(set1)
print(type(set1))
set1.add(36)
print(set1)
s... |
78ebc2aa33a5ee95d600584ebdba9275d0f030fb | rkp872/Python | /5)Arrays/Demo.py | 1,050 | 4.03125 | 4 | #Arrays are collection of similar type elements.
#Arrays can be used after importing array module
from array import *
# since array can contain only homogeneous data so , for declaring the type of array we have to use typecode
#TYPECODE TYPE
#---------------------
# 'b' : signed char
# 'B' : unsigned cha... |
3f234cfdc355952c9fd67a1dbffcb6f9ca85818c | KMR-86/udacity-ML-course-mini-projects | /outliers/outlier_cleaner.py | 824 | 3.8125 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the ... |
80c4a72ef77ba140dc61aa8c5801b8da51430c55 | DogancanULUTAS/MontyHall | /Three.py | 2,639 | 3.640625 | 4 | """
Created on Mon Nov 30 14:07:27 2020
@author: dcu
"""
import random
import numpy as np
import matplotlib.pyplot as plt
switching=[]
stay=[]
def play_monty_hall(choice):
prizes = ['Keçi', 'Araba', 'Keçi'] #Kapının arkasındaki ödüller Ve
#Bunlar randomlanacak.
... |
7832d27d9ebbe495e8cb46b1ec3843adfd6da16d | Pawel762/Class-7_homework | /5-sklearn_log_reg.py | 1,065 | 3.609375 | 4 | from sklearn.datasets import load_wine
import pandas as pd
wine = load_wine()
columns_names = wine.feature_names
y = wine.target
X = wine.data
# Splitting features and target datasets into: train and test
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, t... |
ea7e550c6e8f7d47c0288f8e1a36b0b542faa84d | joonas-yoon/ps4ct | /jlogkim/Season1/060.py | 1,042 | 3.71875 | 4 | def diff_height(lh, rh, tg):
left=lh
right=rh
if lh<=0:
left+=11
if rh<=1:
right+=11
lshare=(left-1)/3
lmod=(left-1)%3
rshare=(right-1)/3
rmod=(right-1)%3
tshare=(target-1)/3
tmod=(target-1)%3
l=abs(tshare-lshare)+abs(tmod-lmod)
r=a... |
a3ab049a8ec64108d2df4ae6b18629d7aeab7cd6 | MethodsofRadish/genehunter | /genehunting.py | 1,437 | 3.78125 | 4 | #! usr/bin/env python3.7
import sys
import fileinput
# Gene_Hunting Python3.7 Script that takes a file from command line arguments
# Prints the output to Standard Out.
# Written by Marcus W. on April 30, 2020
# Welcome to Gene Hunting in DNA Python 3.7 Program
# This program takes a .txt file of Gene Names, a muilt... |
1b68c27fae8d4e2381b6cdba98008d710e779ffb | xliang01/AlgoExpertChallenges | /Easy/dfs.py | 1,515 | 3.6875 | 4 | from collections import deque
# Do not edit the class below except
# for the depthFirstSearch method.
# Feel free to add new properties
# and methods to the class.
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(N... |
3af7fc5b41d85a8842c9f282810fd37c10de6075 | UWSEDS/homework-3-4-testing-exceptions-and-coding-style-JM88888 | /dataframe.py | 1,034 | 3.96875 | 4 | """This module gets a dataframe of seattle building permits checks column names"""
import pandas as pd
import collections
def get_permits(data_frame=pd.read_csv("https://data.seattle.gov/api/views/76t5-zqzr/rows.csv?accessType=DOWNLOAD",
usecols=["PermitClass", "PermitTypeDesc",... |
ba8c39aeb61d09f18cc4139ee50327f207a77632 | Alpenglow88/Useful_Code_stuff | /Languages/Python/strings.py | 4,418 | 4.625 | 5 | # https://www.codingem.com/python-all-string-methods/
# ----------------------------------------
# Strings should be declared with single quotations
string = "Hello"
print(string)
# Output "Hello"
# Variables can be used within strings but must be called using the .format() function
variable = "world"
string_with_... |
0d82962f3218c1cc21ad7b0d4ecf26199a6baf25 | SharhadBashar/ECSE-543-Numericals | /Assignment 1/Q2/generateMesh.py | 4,194 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Sharhad Bashar
ECSE 543
Assignment 1
OCt 17th, 2016
generateMesh.py
"""
##########################################################################################
#Generates the incident matrix
def genMesh(meshDim):
N = (meshDim + 1) #N is the number of nodes in one line of the mesh
... |
e31afa64f87dd2d15e0337cbae7f79e9a60f4ff5 | SharhadBashar/ECSE-543-Numericals | /Assignment 1/Q3/basicDefinitions.py | 5,754 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Sharhad Bashar
260519664
ECSE 543
Assignment 1
Question 1
Solve Ax = b using Cholesky
Step 1 : A = LL^T
Step 2 : Ly = b
Step 3 : L^Tx = y
"""
import math
from scipy import random
import numpy as np
import csv
###############################################################################... |
eba230258fc333724da85402679a6665cb63eae4 | Gavin-GKW/Projects | /Tetris/test_random_generator.py | 591 | 3.75 | 4 | import unittest
from random_generator import RandomGenerator
class RandomGeneratorMethods(unittest.TestCase):
def setUp(self):
self.generator = RandomGenerator()
def test_next(self):
# Ensure that a sequence of seven tetriminoes produced by the
# generator has one of each kind of... |
d85c3e867c8d10f6b71231e9c581d0f4274ec9c3 | Randy760/Dice-rolling-sim | /Dicerollingsimulator.py | 694 | 4.1875 | 4 | import random
# making a dice rolling simulator
youranswer = ' '
print('Would you like to roll the dice?') #asks if they want to roll the dice
while True:
youranswer = input()
if youranswer == 'yes':
diceroll = random.randint(1,6) #picks a random number between 1 and 6
print(... |
ea99bf8a9e9378dd07cfbd1cde43a0df7eda4451 | LukeBrazil/fs-imm-2021 | /python_week_1/day4/vowels.py | 184 | 3.984375 | 4 | vowels = ['a', 'e', 'i', 'o', 'u']
word = input('Enter a word: ')
vowel_count = 0
for i in range(0, len(word)):
if word[i] in vowels:
vowel_count += 1
print(vowel_count)
|
aef5f9145a18abcbf9a72fdcec4ce3d1ecfd4a57 | LukeBrazil/fs-imm-2021 | /python_week_2/day2/test.py | 2,864 | 4.09375 | 4 | stores = []
class Store:
def __init__(self, name):
self.name = name
self.list = []
class Item:
def __init__(self, name):
self.name = name
def menu():
choice = input("Press 1 to add a store \nPress 2 to build a list \nPress 3 to view lists \nPress 4 to delete a store \nPress 5 to d... |
7e52cf50f97a380fd642400ed77ac5c0e6e9706a | LukeBrazil/fs-imm-2021 | /python_week_1/day1/fizzBuzz.py | 324 | 4.15625 | 4 | number = int(input('Please enter a number: '))
def fizzBuzz(number):
if number % 3 == 0 and number % 5 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(f'Number does not fit requirements: {number}')
fizzBuzz(num... |
c249796d94188c71e9794c6938d0712deaaa92c0 | dmc0001/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python | /graphs/kosarajus-algorithm/graph.py | 1,982 | 3.671875 | 4 | from stack import Stack
class Graph:
def __init__(self):
self.vertices: list = []
self.adjacency_list: dict = {}
self.adjacency_list_reversed: dict = {}
self.time = 0
self.visited: dict = {}
self.entry: dict = {}
self.exit: dict = {}
self.stack: Stac... |
d32fcd686253b32ad1f2fc5bea2a90cbec8694e2 | Gluchowski137/warcaby | /main.py | 10,707 | 3.609375 | 4 | import pygame
import random
pygame.init()
win = pygame.display.set_mode((400, 400))
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)
red = (255, 0, 0)
run = True
pawns = []
runda = 0
closedpawns = []
class Pawn():
def __init__(self, x, y, colour, clicked=False):
self.x = x
self.y = y
... |
1de5cfab4b2269dd54a2da627dc842341dbff049 | ekolodenets/2020_1_homework_4 | /Tasks/MoleculeToAtoms.py | 9,004 | 3.59375 | 4 | '''
Из молекулы в атомы
Напишите функцию, которая, принимая как параметр строку - формулу молекулы, возвращала бы атомы из этой молекулы и их количество в виде Dict[str, int]:
def parse_molecule(molecule: str) -> dict:
pass
Примеры:¶
H2O -> {H: 2, O: 1}
Mg(OH)2 -> {Mg: 1, O: 2, H: 2}
K4[ON(SO3)2]2 -> {K: 4, O: 14,... |
d385bb61ec1eaf766666c24f71f472a4138cf98e | mahadev-sharma/Python | /biggest among three.py | 490 | 4.125 | 4 | #find the biggest numbr among three numbers
def biggestGuy (num1,num2,num3):
if ((num1 > num2) and (num1 > num3)) :
print('number 1 is the biggest number among them')
elif ((num2 > num1) and (num2 > num3)) :
print('number 2 is the biggest number among them')
elif ((num3 > num2) and (nu... |
76a8183dc85081ecce1a1f948c901b271a1ce90a | mahadev-sharma/Python | /turtleCircle.py | 673 | 3.8125 | 4 | import turtle
myTurtle = turtle.Turtle()
def circles(velocity,size ):
myTurtle.speed(velocity)
myTurtle.circle(size)
myTurtle.pencolor("red")
circles(1,100)
myTurtle.pencolor("blue")
circles(2,100)
myTurtle.pencolor("green")
circles(3,100)
myTurtle.pencolor("yellow")
circles(4,100)
m... |
3dbf1946e02926fdc155d05d239add53574e5b0a | mahadev-sharma/Python | /pyhon practice/square with circle.py | 472 | 4 | 4 | import turtle
silly = turtle.Turtle()
silly.pencolor("red")
def square(size = 100 ,angle = 110):
silly.forward(size)
silly.right(angle) # Rotate clockwise by 90 degrees
silly.forward(size)
silly.right(angle)
silly.forward(size)
silly.right(angle)
silly... |
234c094967e1a77314d4ac8cebe0d39833ce8d38 | isharajan/my_python_program | /avarage no in list.py | 259 | 3.921875 | 4 | n=int(input("enter n no:"))
list1=[]
for i in range(n):
n=int(input("enter the no:"))
list1.append(n)
print(list1)
sum=0
for a in list1:
# print(a)
sum=sum+a
print("sum is",sum)
avarage=sum/len(list1)
print("the avarage is",avarage)
|
2ab5a92961b62198e46f3676913ba82699bb8b2b | isharajan/my_python_program | /area of circle.py | 152 | 4.15625 | 4 | def area():
area=3.14*r*r
return area
r=int(input("enter the radius value:"))
area=area()
print("area of the circle is:",area)
|
6f67c66026a8e0c366685a7b99c1ed60dbee1a39 | isharajan/my_python_program | /count_letter.py | 547 | 3.671875 | 4 | mystr =raw_input("enter string : ")
print("====")
di = {}
def count_letter(mystr):
for k in mystr:
try:
di[k] = di[k]+1
except KeyError:
di[k] = 1
print di
count_letter(mystr)
fruits = {1:"apple",2:"orange",3:"banana"}
def update_dict():
for k in fruits:
if(fruits[k]=="pine"):
fruits[k] = 'mango'
... |
82aae3c8c3c78808d26682b00d5e88c06399b6e6 | isharajan/my_python_program | /maximum no.py | 224 | 4 | 4 | n=int(input("enter n no:"))
list1=[]
for i in range(n):
n=int(input("enter the no:"))
list1.append(n)
print(list1)
max=list1[0]
for i in list1:
if (i>list1[0]):
max=i
print("The maximum no is",max)
|
b05254c312473e607f3d5fde01986d2a8982e078 | isharajan/my_python_program | /pattern2.py | 123 | 3.59375 | 4 | a = '**************'
b = '* * *'
for i in range(1,20,10):
print (a)
for i in range(1,5):
print(b)
print(a)
|
e60ff9f207f5308841920087b97e9bf348f06d30 | isharajan/my_python_program | /sum of digits.py | 124 | 3.71875 | 4 | n=int(input("enter a no:"))
total=0
while(n>0):
rem=n%10
total=total+rem
n=n/10
print("the sum is" ,total)
|
28d24f4d22de4436d5a3a0357fb3a000d7a98c95 | arcadecoder/Learning_collab | /adventure_game/main.py | 4,820 | 3.859375 | 4 | import time
import random
from Ellen_input import valid_input
from Joe_input import Y
from Joe_input import N
random_creatures = ["gorgon", "vampire", "gruffalo", "zombie", "minatour"]
creatures_dictionary = {"gorgon" : 10, "vampire": 30}
items = ["lollipop", "rock"]
def print_pause(string):
'''
function ... |
ae79f5e95a6eef42525f5ff1e6c777b2536ec6de | katiemdelany/undergraduate_csci | /othello.py | 8,586 | 3.875 | 4 | # Kathleen Delany
import turtle
import random
def make_Board():
#creates game board grid
m = []
for i in range(64):
m.append([0]*64)
turtle.setup(500,500)
turtle.speed('fastest')
turtle.setworldcoordinates(0,0,50,50)
turtle.shapesize(2,2)
turtle.penup()
turtle.hideturtle()
turtle.color("seagr... |
e239c7f8fb806f6738c444d5f05e7a951ec20ba6 | Batmanly/PythonUnitTestExamples | /test_name_funciton.py | 963 | 3.9375 | 4 | import unittest
from name_function import get_formatted_name
"""Common Funciton That we can use
assertEqual(a, b) Verify that a == b
assertNotEqual(a, b) Verify that a != b
assertTrue(x) Verify that x is True
assertFalse(x) Verify that x is False
assertIn(item, list) Verify that item is in list
assertNotIn(item, list)... |
989efb6974bc4557dd61e34e7ca11222e516edd3 | spctravis/Get-Better | /advent_calender_2015.py | 524 | 3.6875 | 4 | """
https://adventofcode.com/2015
"""
#Day 1
"""
puzzle_input="C:\\Users\\dukes\\Documents\\AdventCal\\1puzzle.txt"
puzzle=open(puzzle_input, "r")
puzzle_input=puzzle.readline()
floors_up=puzzle_input.count("(")
floors_down=puzzle_input.count(")")
total_floors=floors_up - floors_down
puzzle.close()
print(total_floors)... |
46c5b994a3404d1befb16b8088167b16dd893f93 | kamineechouhan/RpISE-Statgine | /Swati/mean.py | 107 | 3.546875 | 4 | def Mean(list):
sum=0
for i in list:
sum=sum+i
avg= sum/len(list)
return avg
|
87e180d25b18786c3a198814c5097ea64cb684ee | eddieatkinson/Algorithms | /my_hash_table.py | 1,407 | 3.765625 | 4 | class LinkedListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.right = None
self.left = None
class LinkedList:
def __init__(self):
self.start = None
self.end = None
def append(self, key, value):
new_node = LinkedListNode(ke... |
a927f2e8df3e7e9a7eba871273a60e02f9442e79 | eddieatkinson/Algorithms | /my_stack.py | 1,100 | 4.0625 | 4 | class MyQueue:
def __init__(self):
self.queue = []
def enqueue(self, new_element):
# Adds the new element to the end of the array.
self.queue.append(new_element)
def dequeue(self):
# Removes the first element from the array and return it.
element = self.queue[0]
del self.queue[0]
return element
clas... |
0b664ca8b1e047c9c0ce1202aebd716240fbe428 | eddieatkinson/Algorithms | /find_minimum.py | 165 | 3.875 | 4 | def find_minimum(a):
minimum = a[0]
for i in range (1, len(a)):
if a[i] < minimum:
minimum = a[i]
return minimum
a = [12, 3, 5, -3, 20]
print find_minimum(a) |
1a8bb6859d201f4bb98617985a65c3684b0822d9 | itcyrichy/lesson2_homework | /lesson2_homework.py | 2,912 | 4.09375 | 4 | '''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
# Не указано сколько нулей
null_num=input('Введите количество нулей в строке: ')
for n,i in enumerate(range(5)):
print(n,(str(0)*5))
'''
Задача 2
Пользователь в цикле вводит 10 цифр. Найти количество введе... |
5c9d36857c3165540fccb68ddc13e01b290ec5b7 | neeraj1909/automate-the-boring-stuff-with-python | /automating_tasks/ch_7/is_phone_number_regex.py | 166 | 4.03125 | 4 | import re
phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phone_num_regex.search('My number is 415-555-4242.')
print('Phone number found: ' + str(mo))
|
c0e93f26f6abf822f27e4c8b8f343fc06952057d | FdelMazo/7540rw-Algo1 | /Ejercicios de guia/ej710.py | 373 | 3.75 | 4 | def suma_matrices(lista1, lista2):
"""Recibe dos matrices en formas de lista de listas y suma lugar a lugar"""
if len(lista1) != len(lista2):
return False
suma = []
for f in range(len(lista1)):
if len(lista1[f]) != len(lista2[f]):
return False
fila = []
for c in range(len(lista1)):
fila.append(lista1[... |
923de5239c53b518fdf8777b5ec2db07d4158094 | FdelMazo/7540rw-Algo1 | /Ejercicios de guia/ej32.py | 562 | 3.671875 | 4 | #Pide dos intervalos en horas minutos y segundos y devuelve su suma
import ej31
string = input("Ingrese 3 numeros separados por una coma")
tuplestring = tuple(string)
a = tuplestring[0]
b = tuplestring[3]
c = tuplestring[6]
a = int(a)
b = int(b)
c = int(c)
n1 = ej31.seg(a, b, c)
string2 = input("Ingrese otros 3 numero... |
d681d5339fd0445c9a60328afdaba5a87d49bcca | FdelMazo/7540rw-Algo1 | /TPs/TP3/Trabajo Practico 3/Ciclo.py | 1,924 | 3.9375 | 4 | class _IteradorCiclo:
"""Modelo de un iterador de una ronda de jugadores. Pensado como objeto privado del objeto Ciclo"""
def __init__(self, prim, length):
"""Constructor"""
self.actual = prim
self.sentidoderecha = True
def __next__(self):
"""Llama al siguiente iterable, dependiendo del sentido de l... |
c6817e023e3af7ddd3a1157dc1fc181f699f68b2 | FdelMazo/7540rw-Algo1 | /Ejercicios de guia/ej44.py | 590 | 3.9375 | 4 | import math
def max_min(a,b,c):
"""Devuelve el maximo o minimo de un polinomio de 2do grado"""
if a>0:
m = "Maximo"
elif a<0:
m = "Minimo"
vx = -b / 2 * a
vy = a *(vx **2) + b*vx + c
print ("Su {} es:".format(m), vx, vy)
def raices(a,b,c):
"""Devuelve las raices de un polinomio de segundo grado"""
raiz = b... |
38611f668686c832c7d1fe7e3c671d54d2f9ecf1 | FdelMazo/7540rw-Algo1 | /Ejercicios de guia/ej34.py | 1,388 | 4.15625 | 4 | import math
def calcular_norma(x,y):
"""Calcula la norma de un punto"""
return math.sqrt(x**2+y**2)
def restar_puntos(punto1,punto2):
"""Resta dos puntos"""
x1 = punto1[0]
y1 = punto1[1]
x2 = punto2[0]
y2 = punto2[1]
return x2-x1, y2-y1
def distancia(punto1, punto2):
"""Calcula la distancia entre dos ... |
f6b4bb1aff6e2c8a495f04ae256d68d252e3babf | Rhalith/gaih-students-repo-example | /Homeworks/Hw2-day1.py | 248 | 4.21875 | 4 | n = int(input("Please enter an single digit integer: "))
while (n > 9 or n < 0):
n = int(input("Your number is not a single digit. Please enter an single digit integer: "))
for num in range(n+1):
if num % 2 == 0:
print(num)
|
e682a67bdd8da7175d4021d845b496bfb0dcf9f2 | rayan-roy/OOP-project | /linked.py | 3,669 | 3.984375 | 4 | ## Last version: 24 September 2019
## Classes implementing different types of nodes for linked data structures
class Single:
"""
Fields: _value stores any value
_next stores the next node or None, if none
"""
## Single(value, next) produces a newly constructed singly-linked
## nod... |
5a4eb313ed1fb6f0679000b62edb236a07790b32 | likeand/ml | /models/perceptron.py | 914 | 3.640625 | 4 | import numpy as np
class Perceptron:
"""
Perceptron classifier(感知机分类器)
"""
def __init__(self, input_dim: int, lr: float):
"""
:param input_dim: 输入特征维度
:param lr: 学习率
"""
self.weights = np.random.randn(input_dim + 1) # 权重
self.input_dim, self.lr = input... |
0eec6dd370ba16954c7b25a4976aaa33cd51a2dc | SenithShre/rock-paper-scissors-game | /rock-paper-scissors.py | 5,155 | 4.09375 | 4 | # Made by SenithShre
# Git hub: https://github.com/SenithShre
import random
def game():
print('Welcome to Rock, Paper, Scissors Game')
print('To play, type "Play"')
user_input = input(': ')
if user_input == 'Play':
print('Rock, Paper, Scissors, Shoot!')
user_input2 = input(': ')
... |
8a2ccb4c4ae87cdef2e1048e5135f4541da31b1f | keshav1245/Learn-Python-The-Hard-Way | /exercise19/self.py | 379 | 3.625 | 4 | def somefunction(arg1):
print "This is some arg of some function %s"%arg1
somefunction(10)
somefunction(10+10)
somefunction(10*10)
somefunction(10-20)
somefunction(10.0/4)
somefunction("String Args")
prompt = raw_input("Some input for arg ?")
somefunction(prompt)
prompt = 10
somefunction(prompt+10)
somefunction(... |
3591366d9968bf42380c2f40c55f8db2ae34052a | keshav1245/Learn-Python-The-Hard-Way | /exercise11/ex11.py | 729 | 4.40625 | 4 | print "How old are you ?",
age = raw_input()
print "How tall are you ?",
height = raw_input()
print "How much do you weight ? ",
weight = raw_input()
#raw_input([prompt])
#If the prompt argument is present, it is written to standard output without a trailing newline. The
#function then reads a line from input, conver... |
ba564d1a42fc4a8d42a06ea5683a2023a3ef4abd | marcusshepp/gravity_game | /biological_model.py | 933 | 3.578125 | 4 | import random as r
def select_partner(fits, pop):
"""
Mimics weighted selection with replacement.
"""
totals = []
running_total = 0
for f in fits:
running_total += f
totals.append(running_total)
rnd = r.random() * running_total
for i, t in enumerate(totals):
if r... |
06f72d9e47d47a31ee25688a8ce0b9c5a092f057 | PROgram52bc/COS350_P04_Animation | /animations/pycommon/maths.py | 3,488 | 4.125 | 4 | import math
class Point(object):
"""A point or vector in 3D"""
def __init__(self, x, y, z):
"""TODO: to be defined.
:x: TODO
:y: TODO
:z: TODO
"""
try:
int(x)
int(y)
int(z)
except ValueError as e:
raise ... |
e0541d68b598a39112ce9320deb7538fb0ce29e8 | KIRUS-sudo/KIrus_test | /alexey.py | 1,416 | 3.796875 | 4 | import time # импортировали время
from datetime import datetime # из дат (datetime) импортировали некоторые даты (datetime)
from random import randint # из любых (random) чисел импортировали случайные целые числа (randint)
# для удобства
odds = [] # чётные числа равны списку
... |
fc115f3b5c27d396fe4d515b482ea1845ad3fd29 | TenTwentyThree/NatureInspiredAlgorithms | /Genetic algorithms/makespan_ga_bm1.py | 7,227 | 3.84375 | 4 | import numpy as np
import random
# Benchmark Problem 1: Uniformly Randomized
# For testing
pop = [[2, 3, 4, 6], [1, 2, 3, 6], [3, 4, 5, 7]]
def generate_machines(number_of_machines):
# Generate 20 machines with random speed values in seconds
"""Args:
number_of_machines(int) - Number og machin... |
644206146280e5bf1bcf725cd7dde5678309bc24 | johnhickok/CalStreetLookup | /legacy_code/streetzip.py | 1,926 | 3.921875 | 4 | # streetzip.py queries sqlite database streetz.db and appends a list of zipcodes
# and street names into streetlist.txt. The streetz.db file contains an indexed list
# of street names and zipcodes extracted from OpenStreetMap data for California.
import webbrowser, sqlite3
# Ask for user input in the CMD Console
prin... |
1f39795b7719af506164b48da51370bd90c397ca | a-tran95/PasswordGenerator | /app.py | 2,059 | 4.125 | 4 | import random
letterbank_lower = 'abcdefghijklmnopqrstuvwxyz'
letterbank_upper = letterbank_lower.upper()
numberbank = '1234567890'
symbolbank = '!@#$%^&*()-=_+`~{}|[];:<>,./?'
thebank = [letterbank_lower,letterbank_upper,numberbank,symbolbank]
password = []
def charcheck(check):
try:
if check.... |
03c3de98365bb3ad451e341be400ed65d0193dee | hyunjoonam/wk1sat | /odd_numbers.py | 197 | 3.984375 | 4 | # $ python odd_numbers.py
# 13579
# you will need to use the modulus operator % to determine whether a number is odd or even
for number in range(1,10):
if number % 2 == 1:
print number |
eb0c688c66e5d447ff833ec3730b8e58246e7a61 | Nyyen8/Module3 | /Tests/test_operators_practice.py | 735 | 3.6875 | 4 | import unittest
class OperatorsTest(unittest.TestCase):
def test_equal(self):
varA = 1
varB = 2
self.assertFalse(varA == varB)
def test_not_equals(self):
varA = 1
varB = 2
self.assertTrue(varA != varB)
def test_greater_than(self):
varA = 1
... |
2f1bd009c20a51bab241ad3c31528b0f0664ed93 | rohan-khurana/MyProgs-1 | /SockMerchantHR.py | 1,687 | 4.625 | 5 | """
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of c... |
0a47ead1f61b1ab1ffe627e55a08f31ebed03c5e | rohan-khurana/MyProgs-1 | /basic8.py | 225 | 4.15625 | 4 | num = input("enter a number to be checked for prime number")
num = int(num)
i = num
j=1
c=0
while j<=i :
if i%j==0 :
c+=1
j+=1
if c==2 :
print("entered number is prime")
else :
print("not prime")
|
34a9397a0c7652028e46c2cb1d93cede171ff1e0 | rohan-khurana/MyProgs-1 | /test1.py | 339 | 3.53125 | 4 | # with http://py4e-data.dr-chuck.net/comments_244952.xml used as count.txt
url = input('Enter - ')
xml = open(url)
sum=0
for line in xml :
if line.startswith("<count>") :
pos=line.find("<count>")
pos2=line.find("</count")
num = line[pos+7 : pos2]
num = int(num)
sum... |
9f6ee9426e3bd6c017e82c317f0800236cd2dc13 | rohan-khurana/MyProgs-1 | /TestingHR.py | 2,987 | 4.28125 | 4 | """
This problem is all about unit testing.
Your company needs a function that meets the following requirements:
For a given array of integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the... |
5f5491670033ed0c15c07b7c340148c24ee895b1 | rohan-khurana/MyProgs-1 | /basic4.py | 239 | 3.84375 | 4 | p = input("enter the principle amount")
p = int(p)
r = input("enter the rate of interest")
r = float(r)
t = input("enter the time period")
t = int(t)
ci = p*pow((1 + (r/100)),t)
ci = float(ci)
print("the compound interest is",ci)
|
8e07f7fdba8ee6adae646070615b9b8d756462bc | rohan-khurana/MyProgs-1 | /TheXORProblemHR.py | 1,865 | 4.25 | 4 | """
Given an integer, your task is to find another integer such that their bitwise XOR is maximum.
More specifically, given the binary representation of an integer of length , your task is to find another binary number of length with at most set bits such that their bitwise XOR is maximum.
For example, let's say ... |
f7e30fb9549c6e8c88792ac40d5c59ef0a86edf6 | tonyvillegas91/python-deployment-example | /Python Statements/list_comprehension2.py | 205 | 4.34375 | 4 | # Use a List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
[word[0] for word in st.split()]
|
1a87e48e3c3debf4b1226cd6d68884d1e5378088 | tonyvillegas91/python-deployment-example | /Functions and Methods Homework/radius.py | 122 | 3.609375 | 4 | # Write a function that computes the volume of a sphere given its radius.
def vol(rad):
return (4/3)*(3.14)*(rad**3)
|
04569044f002093f06d2314f5b055c318b43a051 | RodolfoOsorio/dijkstras-algorithm-python | /Graph.py | 723 | 3.578125 | 4 |
from Vertex import *
class Graph(): #el grafo en esencia es un diccionario
def __init__(self):
self.G = {}
self.num_vertices = 0
def add_vertex(self, name):
new_vertex = Vertex(name)
self.G[name] = new_vertex
self.num_vertices = self.num_vertices + 1
def add_edge(self, start, end, weight = 0, diagraph... |
b6c39e4a1bca5cc80df84d75d8cb09bebc3bc6f2 | pierrout/ExerciciosFixacao | /lista3.py | 3,616 | 4.21875 | 4 |
# Exercício 1 - Crie uma função que imprima a sequência de números pares entre 1 e 20 (a função não recebe parâmetro) e
# depois faça uma chamada à função para listar os números
def numPar ():
for i in range (0,21,2):
print (i)
return
numPar()
# Exercício 2 - Crie uam função que receba uma string com... |
6b2d2b79e9df2c0d11d38fa6f90ccd0194b5fbc8 | RomanPolishchenko/Python-practice | /Inheritance/14.9 (sorting)/main14_9.py | 244 | 3.953125 | 4 | from collections import deque
sequence = deque()
numbers = list(input('Enter your numbers: ').split())
for i in range(len(numbers)):
sequence.appendleft(max(numbers))
numbers.remove(max(numbers))
print('Sorted:', " ".join(sequence))
|
edb4c4b816a522b228e00afb626b78c63fd73bbf | RomanPolishchenko/Python-practice | /Ex/7_153.py | 3,269 | 3.609375 | 4 |
def search1(filename, char):
"""
функция подсчета количества строк, первый символ которых равный заданному
:param filename: имя файла
:param char: символ
:return: количетво
"""
file = open(filename, 'r', encoding='utf-8')
count = 0
for line in file: # считываем строчки файла и ... |
7f9fa478881a940e3ab5d1ddce41540d5616fa7b | ggaltar/leccion-08-python-archivos | /hemis_occidental.py | 420 | 3.609375 | 4 | import csv
# Recorrido e impresión de las líneas de un archivo de texto
with open("maravillas_nuevas.csv") as archivo:
# Se crea el objeto reader
lector = csv.reader(archivo)
# Se recorren las líneas
for linea in lector:
i = 0
for linea in lector:
if (i != 0) :
... |
c9bf8626a56c76ce954185f0dbddc33f95acba50 | nicolagulmini/balls_and_bins | /balls_and_bins.py | 2,324 | 3.796875 | 4 | '''
Suppose that we toss balls into b bins until some bin contains two balls. Each toss
is independent, and each ball is equally likely to end up in any bin. What is the
expected number of ball tosses?
'''
# A solution: https://sites.math.rutgers.edu/~ajl213/CLRS/Ch5.pdf
import random as rnd
from matplotlib ... |
e978368f68608263f2e7900e63dd57165c3fd8da | scperkins/martyr2_Mega_Project_List | /inventory/product.py | 749 | 3.703125 | 4 | #import inventory
class Product:
def __init__(self, pid, name, price, qty, weight):
self.pid = pid
self.name = name
self.price = price
self.qty = qty
self.weight = weight
def update_price(self, new_price):
if new_price < 0:
print "The price cannot be a negative value!"
else:
... |
b32998b7c565add38f25d18c6c8ed40f1248f221 | akhildraju/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 670 | 3.75 | 4 | def intersection(arrays):
map = {}
for a in arrays:
for n in a:
value = map.get(n)
if value is None:
map[n] = 1
else:
map[n] = value+1
count = len(arrays)
result = []
for n in map.keys():
value = map[n]
... |
5c215043ab9037af29d424702104802c4abc4bb4 | mobiusklein/msms_feature_learning | /src/glycopeptide_feature_learning/approximation.py | 3,992 | 3.71875 | 4 | import pkg_resources
import numpy as np
from matplotlib import pyplot as plt
# derived from statsmodels
class StepFunction(object):
"""
A basic step function.
Values at the ends are handled in the simplest way possible:
everything to the left of x[0] is set to ival; everything
to the right of ... |
fe198f4eb4746cefa5aefc5111cc451562121a73 | bolducp/algorithms_design_and_analysis | /count_split_inversions.py | 913 | 3.859375 | 4 | split_invs = 0
def mergeSort(a_list):
if len(a_list) <= 1:
return a_list
mid = len(a_list) // 2
left = a_list[:mid]
right = a_list[mid:]
return merge_and_count(mergeSort(left), mergeSort(right));
def merge_and_count(left, right):
global split_invs
merged_list = []
l_index = ... |
acd147541a870f6db4539715cdf3e2d67e1aa0a4 | Butteryfinger/Datalogi | /Lab7.py | 2,232 | 3.515625 | 4 | # Base done, kolla för eventuella krav
def lexer(inp):
inp = list(inp)
while True:
if "[" in inp:
t1 = inp.index("[")
if "]" in inp:
t2 = inp.index("]")
inp = inp[:t1] + inp[t2+1:]
else:
break
startpar = 0
endpar = 0
... |
ded50d0b02adacc929ec2052434dcd70695d1b57 | ssalpawuni/python_beginner | /guest_list.py | 1,253 | 3.953125 | 4 | # 3-4 (guest list)
guests = ['azumi', 'tunteiya', 'salpawuni', 'fusey', 'bushra']
for fam in guests:
print(f"{fam.title()}\n")
print(f"Hello {guests[0].title()}, you are invited to dinner at 6.30pm")
print(f"Hello {guests[1].title()}, you are invited to dinner at 6.30pm")
print(f"Hello {guests[2].title()}, you are i... |
c4a4db0a293c59dd1b509d897a155c05a98cb991 | 25-ADUP/Capstone_Attitude_Determination | /python/tools.py | 455 | 3.65625 | 4 | import sys
def percentage(iter: int, total: int):
"""
A handy percent bar for visualization
:param iter: number you're on
:param total: total number of iterations
:return: None
"""
# percentage of 20 bars
num = int((iter / total) * 20) + 1
# carriage return, loading bar, write
... |
7d8b5d4da539faf86f63c5031178d2fb258e5595 | hagai-helman/jsop | /jsop.py | 20,089 | 3.625 | 4 | """A dbm-based persistence for JSON-style data.
It allows you to store a large amount of JSON-style data on disk, but to access it quickly and efficiently.
To initialize a new JSOP database:
from jsop import JSOP
# 'data' can be any JSON-serializable object
JSOP("/path/to/jsop").init(data)
To access ... |
c623373bc82a2d9c83d28515cc32bfddc2585143 | UCHMS19-20/final-project-choose-your-own-adventure | /src/game.py | 59,518 | 3.984375 | 4 | # Spaces out portions of the storyline and choices, makes it easier to read
import time
# Used at the end of the game to calculate probability of winning
import random
# Used to play music at the end of the game
import pygame
from pygame import mixer
pygame.mixer.init()
import sys
# Setting variables for friendshi... |
ce6df98ddf05b2862da25fbc00d70ec7dcc276fa | KaloyanVD/Python-NumpyBasics | /05.Mathematics.py | 379 | 3.6875 | 4 | import numpy as np
a = np.array([1, 2, 3, 4, 5])
# We can add, subtract, multiply and divide the elements of the array
# a += 2
# a -= 2
# a *= 2
# a /= 2
# Take the sin/cos
# np.sin(a)
# np.cos(a)
print(a)
# Multiply two matrices
b = np.ones((2, 3))
c = np.full((3, 2), 2)
result = np.matmul(b, c)
print(result)
... |
7d998559c70427342653727330dcd29cf31c8f63 | piyush2040/LeetCode-Problems-Solution-Book | /Python/51.n-queen.py | 2,092 | 3.84375 | 4 | # Link to problem: https://leetcode.com/problems/n-queens/
# Problem :The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
#Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
#Each solu... |
a655c1fbb0a06ace930f45fef964328b88c5901e | nskadam02/Python-Basic-Programs | /positiveNegative.py | 214 | 3.9375 | 4 | def Check():
no=float(input("please Enter Number:"));
if no>0:
print("positive number");
elif no==0:
print("zero");
else:
print("negative number");
Check();
|
420dc0c8d97e56b4fb94dd5ea72f6bff4a8cec0b | jdstikman/PythonSessions | /AcuteObtuseAndRight.py | 226 | 4.125 | 4 | a = input("Enter number here")
a = int(a)
if a < 90:
print("number is acute")
elif a == 90:
print("right angle")
elif a > 90 and a < 180:
print("obtuce")
else:
print("i have no idea what you are talking about") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.