blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
64d4488f81af7543a6906991af8d564992b89e5d | XuyingLiu/crabs | /craps.py | 1,367 | 4.1875 | 4 | """This is the main module of our craps game
usage: python3 craps.py number_of_gmaes
"""
import sys
from random import randint
print("craps game")
# num_of_games = int(sys.argv[1])
num_of_games = int(input("How many times do you want to play craps? "))
print(f"Playing {num_of_games} games...")
def craps():
"""r... |
3866e07a8721b67ff44fb2ee0aa2ffacef53c192 | amit19-meet/meet2017y1lab6 | /funturtle.py | 1,624 | 4.65625 | 5 | import turtle #python needs this to use all the turtle functions
#turtle.shape("turtle") #changes the shape to a turtle
#square = turtle.clone() #creates new turtle and saves it in square
#square.shape("square") # changes the shape of the second turtle to a square
#square.goto(100, 100) # moves square to ( x= 100, y= 1... |
77ba709d8947b89c6fecae29aa39c1fa5ddf6fce | samli6479/PythonLearn | /BinaryTree.py | 1,728 | 4.21875 | 4 | # Binary Tree
# A Binary Tree is a tree that has a left branch and a right branch
# Fill the missing with an empty tree # An instance of tree must have two branches
# Binanry Search Tree
# Each entry larger than all entries on left and smaller than the rights
class Tree:
def __init__(self, entry, branches = (... |
e54ab71102a107a7110e0f7dcb246389216fb3aa | xzjia/lifeline-scraper | /Movies/main.py | 4,414 | 3.640625 | 4 | #!/usr/bin/env python3
import argparse
import datetime
import json
from requests_html import HTMLSession
def parse_args():
"""Parse and return the command-line arguments.
"""
parser = argparse.ArgumentParser(
description='Retrieve movie box office sales figures for fridays within the given range.'... |
2372c2e8a3fe69f23ef31cb231d3b56af4e7fa6f | pjot/world-clock | /world-clock.py | 700 | 3.765625 | 4 | import sys
import pytz
import re
from datetime import datetime
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
def get_timezones(partial):
regex = re.compile(re.escape(partial.lower()))
for timezone in pytz.all_timezones:
if re.search(regex, timezone.lower()):
yield timezone
def run(partial):
for... |
5f97043e4534bc4149b071e92f41fc06247a4eeb | kragniz/WindRunner | /Together-versions/Forebrain.py | 7,433 | 3.546875 | 4 | import math
import bank #delete when final
class Forebrain:
## sail setting!
def setSails(self):
# '''Sets the sails to the correct location for the wind data coming in. '''
currentWindHeading=bank.bank('currentWindHeading')
currentHeading=bank.bank('currentHeading')
print 'current wind heading is: ', cur... |
58fa91e7dbe03df272358568ec50a4d9b4e832ab | pnads/advent-of-code-2020 | /day_08.py | 5,888 | 3.671875 | 4 | """--- Day 8: Handheld Halting ---
Your flight to the major airline hub reaches cruising altitude without incident.
While you consider checking the in-flight menu for one of those drinks that come
with a little umbrella, you are interrupted by the kid sitting next to you.
Their handheld game console won't turn on! Th... |
3c076f7848ffa0bcd5446e4c329e636947d9b825 | munishdeora/python_training_2019 | /Day 4/centered.py | 1,014 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 18:52:28 2019
@author: de
"""
"""
Code Challenge
Name:
Centered Average
Filename:
centered.py
Problem Statement:
Return the "centered" average of an array of integers, which we'll say is the
mean average of the values, except ignoring the lar... |
56900ec1db4cb878628d4567e6f2874614ef6978 | Artur-Aghajanyan/VSU_ITC | /Lusine_Shahbazyan/python/fibonacci.py | 406 | 3.9375 | 4 | n = int(input("n = "))
FibonacciArray = [0,1]
def findFibonacciNumber(n):
if n < 0:
print("Incorrect input")
elif n == 1:
return FibonacciArray[0]
elif n == 2:
return FibonacciArray[1]
else:
fibNumber = findFibonacciNumber(n-1)+findFibonacciNumber(n-2)
Fibonacc... |
44ccb8a3cf11a39b326454e0a1cecfa453c4e732 | Leziak/Leetcode | /Python/PalindromeLinkedList.py | 682 | 3.9375 | 4 | # Used a list because I wasn't explicitly asked to reverse the linked list (which I did in another problem, only to verify if the linked list is a palindrome or not.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solu... |
a7612079570049eeb7e6004b7ac0755421696913 | janellecueto/HackerRank | /Python/Strings/StringValidators.py | 323 | 3.734375 | 4 | import re
if __name__ == '__main__':
s = input()
print(bool(re.search(r'\w', s))) #alphanumeric
print(bool(re.search("[A-Za-z]", s))) #has letters
print(bool(re.search(r'\d', s))) #has numbers
print(bool(re.search("[a-z]", s))) #has lowercase
print(bool(re.search("[A-Z]", s))) #has upperca... |
103faacdfdf8238ec3b83556953f0fcf2db8af60 | grzegorz-rogalski/pythonGrogal | /zaj1/script6.py | 302 | 3.96875 | 4 | '''
listy(edytownalne) i krotki[tuple](niezmienne)
'''
l=[1,2,'element',3.14]
'''print l
k=(1,2,'element', 3.14)
print k
print l[1]
print k[1]
print l[1:3]
print k[:-2]
'''
print 3 in l #sprawdza czy istnieje
l[0]=3
print l
#k[0]=3 NIE MOZNA ZMIENIAC WARTOSCI
#print k
l[1:3]=['a', 'b']
print l |
cb447f084119f5c16b99f7e54a9fd1990c1af90b | manjot-baj/My_Python_Django | /Python Programs/oop_inheritance_3.py | 2,738 | 3.8125 | 4 | # method overriding
class Phone: # base / parent class
def __init__(self,brand,model,price):
self.brand = brand
self.model = model
self.price = max(price,0)
@property
def specification(self):
return f"{self.brand} {self.model} {self.price}"
def make_call(self,phone_no):
... |
50c5887593d61baa9342ff4b493735d1e974ba9c | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/tsnvho001/question3.py | 756 | 4.09375 | 4 | #Program to calculate permutations
#Tsanwani Vhonani
#15 APRIL 2014
import mymath
def fact():
#get number 'n' from user
n=input("Enter n: \n")
while not n.isdigit():
n=input("Enter n: \n")
n=eval(n)
#findng the factorial of n
n_fact=1
... |
f68758607c2448e334b351caf17664b7988bf8bf | meliezer124/pythonWorkbook | /E1-E33/E5.py | 529 | 3.859375 | 4 | ## Bottle Deposits ##
# Get amount of each type
liter_or_less = float(input("How many containers do you have that hold a liter or less?"))
more_than_liter = float(input("How many containers do you have that hold more than a liter?"))
#Calculate invididual typed deposits
amt_less = liter_or_less * 0.10
amt_more = more... |
79dbf87cc7f5563cf24ef0ceeded6be5a27317c4 | renchao7060/studynotebook | /基础学习/p26.py | 2,803 | 3.890625 | 4 | #_*_coding:UTF-8_*_
# 形参 def test(x,y)
# 实参test(1,2)
# 位置参数def test(x,y)
# 关键字参数 def test(x,y=1) or test(x,y=1)
# 默认参数 def test(x,y=1)
# 可选参数 def (x,y,*args,**kwargs)
def test1():
print('in the test1')
def test2():
print('in the test2')
return 0
x=test1()
y=test2()
print(x,y)
print('*'*60)
# in the test1
# in ... |
0ef181fc65ef4d9507291281727156896440e8d7 | antaramunshi/GUIwithTkinter | /script1.py | 764 | 3.90625 | 4 | from tkinter import *
window = Tk()
def km_to_miles():
miles = float(e1_value.get())*.6
t1.insert(END, miles)
def kg_conversion():
grams = float(e1_value.get())*1000
t1.insert(END, grams)
pounds = float(e1_value.get())*2.20462
t2.insert(END,pounds)
ounces = float(e1_value.get())*35.274
t... |
d29289c3ca31ce6d5ffc28140dca4c0f27577ab3 | waltlrutherfordgmailcom/CTI110 | /P4T1C_Rutherford.py | 566 | 3.796875 | 4 | # This program draws a snowflake using a nested loop.
# 3/14/2019
# CTI-110 Bonus Lab:P4T1C - Snowflake
# Walter Rutherford
import turtle
t = turtle.Turtle()
def stick ():
for x in range (3):
for x in range (1):
t.forward (30)
t.right(45)
t.forward(30)
... |
19ebac2f2c38ccfa9750249519cfdcd4916deec8 | jpog99/ITE_1014 | /190327_w4/190327_w4_1-2.py | 118 | 3.796875 | 4 | print('Input a number: ')
num=input()
n=1
while (n<int(num)+1):
if (n%2!=0)or(n%4==0):
print(n)
n+=1 |
77298c4216549654c7306e6b0905fa508aea4388 | acbarnett/advent-of-code-2020 | /02/a.py | 261 | 3.625 | 4 | from lib import count_valid
filename = "input-a.txt"
def check_validity(low, high, character, password):
c = password.count(character)
return c >= low and c <= high
count_of_valid_rules = count_valid(filename, check_validity)
print(count_of_valid_rules)
|
25974294dcda1fbf5035e609cb1455c83831b534 | yuannan/python | /yuannan/pizzashop/start.py | 22,223 | 3.671875 | 4 | #!/usr/bin/env python
#
# V0.1.0 Alpha, Functional, but missing some value checking ext.
# "fully functional"
#
# Importing modules and defining essentails
import csv
import operator
import sys
from time import gmtime, strftime, sleep
#debug=True
# Defining all the functions
def start():
print("Welcome to Big... |
2b9ae74fa9aef8c558ddfc1f657082d85103fec8 | shreyakapadia10/PythonProjects | /Python to Exe/print_n_numbers.py | 83 | 3.890625 | 4 | n = int(input("Enter any number: "))
for i in range(1, n+1):
print(i, end=' ') |
aa4729309fe3422ae317da824401e296a441cfb0 | nickradford/advent-of-code | /03/03-toboggan-trajectory.py | 842 | 4.21875 | 4 | #!/usr/bin/env python3
# https://adventofcode.com/2020/day/3
# With the map repeating to the right infinitely, calculate the number of trees encountered for a given slope (3, 1) (right, down)
import math
def calculate_trees_for_slope(slope, grid):
x, y = slope
width = len(grid[0]) - 1
posX, posY = 0, 0
t... |
4177b3ca3ecc39a028d92a67688a31b0fd27fd3a | zncepup/web2 | /tttttttt.py | 426 | 3.8125 | 4 | def month2year(string):
strnyr=''
m=float(string)
year=m//12.0
print(year)
if year!=0:
strnyr=str(int(year))+'年'
month=m%12.0
if int(month)!=0:
strnyr = strnyr + str(int(month)) + '个月'
day=month-int(month)
day=day*30
day=round(day)
if day!=0:
strnyr=st... |
fc8374e69809d637f80de4068bd8194ef775d5ed | abmish/pyprograms | /100Py/Ex7.py | 663 | 4.15625 | 4 | """
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th
row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1..,Y-1.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0,... |
bd7defe02ca713c351cb45058ca3294f0dcbef69 | goblinbat/CodeWars_comp | /02.py | 3,001 | 4.125 | 4 |
def tribonacci(signature, n):
'''
input: set of starting numbers, how many numbers you want returned\n
output: the original sequence (unless n < len(signature)),
plus continuation in which the last 3 numbers in sequence
are added together and added to sequence (repeat until
len(sequence) = n... |
55b53247b265b721e3ef845978ed1df679cc2278 | Meimoorthi/Python_Basic | /sum_of_digits.py | 196 | 3.90625 | 4 | count = 0
def countdigit(n):
if n<10 :
return n;
else:
count=n%10+countdigit(n/10)
return count
a=input("Enter the number \t")
print "output is :\n",countdigit(a)
|
63ba567d8a5a46b96e6d18eb223285cb6ee48ec6 | hansini-ruparel/learning.progress | /concept-inputs1.py | 84 | 3.5 | 4 | print("Hello World")
name = input("Enter your name ")
print ("Welcome " ,name)
|
dbeaa855ba4f0ce46d424206811e990358b5bec7 | len1028/python | /long.py | 324 | 3.578125 | 4 | # _*_coding:utf-8_*_
# Author:len liu
name = ["zs","ls","we","mz"]
name.insert(1,"xx")
name[1] = "hh"
name2 = ["zz","yy","xx"]
#del name[1]
#name.remove("we")
#name.pop(0)
#print(name.index("ls"))
name.append("ls")
#print(name.count("ls"))
#name.extend(name2)
name.insert(2,name2)
print(name)
#print(name[name.index("hh... |
6abc4bc16105e4f9798e845b6bef12749dc19af4 | lalapapauhuh/Python | /CursoEmVideo/pythonProject/ex064.py | 407 | 3.765625 | 4 | # tratamento de valores
numero = 0
cont = 0
resultado = 0
saida = False
while not saida:
if numero != 999:
numero = int(input('Digite um número [999 para parar]: '))
resultado += numero
cont += 1
saida = False
else:
cont -= 1
resultado -=999
saida = True
... |
aaacd1d2d1e3cf1ad5392b95dda2ebf1bc8f9e6d | zerghua/leetcode-python | /N1957_DeleteCharacterstoMakeFancyString.py | 2,148 | 4.03125 | 4 | #
# Create by Hua on 3/21/22.
#
"""
A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s
to make it fancy.
Return the final string after the deletion. It can be shown that the answer
will always be unique.
Example 1:
... |
3654ca976bf7228ab21d5b946f4a6bb7df5add72 | liamcarroll/python-programming-2 | /Lab_2.1/unique_count_021.py | 464 | 3.796875 | 4 | #!/usr/bin/env python3
import sys
def unique_words(l):
unique_words = []
for word in l:
if word not in unique_words:
unique_words.append(word)
return len(unique_words)
def main():
text = sys.stdin.read().strip().casefold()
for c in text:
if not c.isalnum() and not c.i... |
7e18c9060956993080ee3ccd9c6442da61941ec2 | HannanehGhanbarnejad/IntroductionToPythonProgramming | /ex2/prog2.py | 741 | 4.25 | 4 | a=int(input("Please enter the first number:"))
b=int(input("Please enter the second number:"))
def prog2(a, b):
""" (int, int)-> list
Return all the even numbers between two given values.
The function works even if the first given value is
bigger than the second one numerically .
>>> prog2(23, 3) ... |
514f2084f12124104d8498a156a7d6c1e7a0fe75 | mannerslee/leetcode | /138.py | 2,051 | 3.734375 | 4 | # Definition for a Node.
'''
思路:
两次两次遍历 目标表
第一次遍历: 会略random, 拷贝next和val。
字典 p_add2index 记录目标表p 指针->索引
字典 q_index2add 记录目标表q 索引->指针
第二次遍历:
从 p_add2index表知道 当前p.random->索引->q表指正,赋值给q.random
从而赋值random关系
注意点:
空指针的在 map中的处理
头结点 尾插法简历链表
'''
class Node:
def __init__(self, x: int, next=None, rand... |
ff0dec31ed8f37c33080c513acade032677032d8 | VictorPuglieseManotas/DataScience | /HML_Chap03_01.py | 13,234 | 3.5 | 4 | from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
mnist
X,y=mnist['data'],mnist['target']
X.shape #Rows are intances, Columns are features (784 features=28x28pixeles). Each pixel (0:white -> 255:black)
y.shape #70,000 numbers betw... |
2a4df919817a9888dcd686a8e780601418efd73e | RickyUC/Probando | /Tareas/Tarea 1/operaciones.py | 3,417 | 3.59375 | 4 | def negativo (numero):
resultado = ""
for digito in numero:
if digito == "1":
resultado += "0"
elif digito == "0":
resultado += "1"
return resultado
def rotar_izq (numero):
inicial = numero[:1]
resultado = numero[1:] + inicial
return resultado
def rotar_... |
42a76b40be3ff54e8f449ed6eb64ee6adbe70896 | klimova00/Python_4_les | /4_les/4_les_2_ex.py | 229 | 3.78125 | 4 | my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
print(f"my_list: {my_list}")
new_list = []
el1 = my_list[0]
for el in my_list:
if (el1 < el):
new_list.append(el)
el1 = el
print(f"new_list: {new_list}")
|
8f8e9e41172d9f3cb8c886216c3ef9d065b476a1 | suryansh2020/chapter_codes | /codes_ch4/chap4_code_2.py | 239 | 3.609375 | 4 | class Example:
pass
x = Example()
print(hasattr(x, 'attr'))
Example.attr = 33
y = Example()
print(y.attr)
Example.attr2 = 54
print(y.attr2)
Example.method = lambda self: "Calling Method..."
print(y.method())
print(hasattr(x, 'attr'))
|
c147403fb4c3bdd2f3f64d508cffa16939b81307 | sung3r/ctfcode | /exp/2017/tmctf/ao200.py | 946 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def is_prime(n):
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
def odd_sum(n):
i = 1
while True:
n -= i
if n == 0:
return True
elif n < 0:
return False
... |
fb576d70f8f3cae4ab4e3a001db708fec010035f | chloeward00/CA117-Computer-Programming-2 | /labs/geometry_072.py | 1,304 | 4 | 4 | class Point(object):
def __init__(self, x=0, y=0):
self.x = int(x)
self.y = int(y)
def distance(self, other):
x = self.x - other.x
y = self.y - other.y
d = (x ** 2 + y ** 2) ** 0.5
return d
def __str__(self):
return "({:.1f}, {:.1f})".format(self.x, self.y)
class S... |
8dd75042260c47d01e8cf808c7e5b072739be2f7 | mohamma548/python_API | /url_XML.py | 440 | 3.84375 | 4 | #!/usr/bin/python
# retriving XML data using python from the web
import urllib
import xml.etree.ElementTree as ET
url = raw_input("Please enter the url:")
total=0
xml_data=urllib.urlopen(url).read()
tree= ET.fromstring(xml_data)
lst=tree.findall('comments/comment')
# retriving all the numbers inside count tag
for item... |
0f1cb86327c542fec46fceedbd1af17dae2a1651 | apoorvaanwekar/python-challenge | /PyPoll/main.py | 2,479 | 3.921875 | 4 | ##################################################################################
# Author: Apoorva Anwekar
# Solution for Homework #3 PyPoll.
##################################################################################
import csv
#creating an empty dictionary
mydict = {}
#initializing a counter for counting to... |
174f435d046ba8843973a73cd9f1c1c7c688d58e | lukabombala/adventofcode2019 | /task1/task1_solution.py | 556 | 3.53125 | 4 | import math
# solution for 1st part
output1 = 0
with open('task1/input1.txt', 'r') as file:
for line in file:
line = int(line)
output1 += math.floor(line/3) - 2
# printing answer
print(output1)
# solution for 2nd part
output2 = 0
with open('task1/input2.txt', 'r') as file:
for line in file:... |
3eed1f413dc2e6dd6c8dbcfded6e911b99741916 | zoomjuice/CodeCademy_Learn_Python_3 | /Unit 10 - Classes/10_02_01-Inheritance.py | 1,019 | 4.5 | 4 | """
Classes are designed to allow for more code reuse, but what if we need a class that looks a lot like a class we
already have? If the bulk of a class’s definition is useful, but we have a new use case that is distinct from how the
original class was used, we can inherit from the original class. Think of inheritance ... |
9bf7e1deb26b057a24380371c1f9f023a2a14e62 | rangermx/Git_Project | /Python/tools/get_cs.py | 1,750 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'get 376.2 cs sum'
__author__ = 'Mingxin Liu'
import sys
def start_working(param = 1):
print('please enter your 376.2 string without starting code "68", strlen, and the ending code "16"')
while True:
# 第一步,输入字符串
source_str = sys.stdin.readline(... |
feb7084e1b113beb4b274feb520a6769f4d5e2f2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/5965153ffbfd46b19869bc424d49b67d.py | 198 | 3.59375 | 4 | def sieve(n):
result = range(2, n + 1)
i = 0
p = result[i]
while p * p <= n:
result = [res for res in result if res == p or res % p != 0]
i += 1
p = result[i]
return result
|
05dbaa88671d5d794827814a3d570e244ac0e9d0 | distractedpen/datastructures | /SearchOperations.py | 871 | 4 | 4 | def linearSearch(array, value):
i = 0
for i in range(len(array)):
if array[i] == value:
return "Found {0} at index {1}.".format(value, i)
i += 1
return "{0} not found.".format(value)
def binarySearch(array, value):
low = 0
mid = len(array) // 2
high = len(array) - 1
... |
de84c306cd3602685f0aaeca1dd386c16216d79a | patrenaud/Python | /CoursPython/Len.py | 268 | 3.921875 | 4 | # Message Analyser
# Demonstrates the len() function and the in operator
message = input("Enter a message: ")
print("\nThe lenght of this message is: ", len(message))
if "e" in message.lower():
print(" 'e' is in this message")
input("\n\nPress enter to quit")
|
287621f37fa39e25f40a39c8f3bec018994946f6 | wanwanaa/Leetcode | /数学/7.整数反转.py | 384 | 3.765625 | 4 | # 7.整数反转
# 负数取模下取整
def reverse(self, x: int) -> int:
while x != 0:
pop = x % 10
if (temp > sys.maxsize/10) or (temp == sys.maxsize/10 and pop > 7):
return 0
if (temp < (-sys.maxsize-1)/10 0r (temp == (-sys.maxsize-1)/10 and pop < -8):
return 0
temp = temp * 10... |
4727e16923735122db2d496a0749e25160dc4ab8 | folsomjenna/pythons | /1-3 deliverables/year.py | 570 | 3.671875 | 4 | # year.py
# Created on 12/11/18 by Jenna Folsom
# A program that prompts the user for a 4-digit year and then outputs the value of the epact
def main():
import math
# This is an introduction
print("This is a program that prompts you for a 4-digit year and then outputs the value of the epact.")
# Thi... |
b1f1276512a78d2f671a0a90812a43f6c6149751 | dslap0/Universite-Python | /PHY1234/Laboratoire2-codesQ3alt.py | 1,021 | 3.890625 | 4 | # -*- coding: latin-1 -*-
#@author: Nicolas
"""
Code incomplet visant à passer par une boucle for au lieu de while pour
trouver la somme de contrôle de l'algorithme de Luhn.
"""
liste = list(((input('Entrez un code à vérifier:')).\
replace(' ','')).replace('-',''))
i = 0
for x in (0,len(liste)): #On chang... |
95fa89bb021493b6e6b05293435093d52783a14d | yilinanyu/Leetcode-with-Python | /test10.py | 146 | 3.90625 | 4 | def excel(num):
# number to title
ans = ''
while num:
ans = ans + chr(ord('A')+ (num-1)%26)
num = (num - 1)/26
return ans
print excel(27) |
6fa8a1331880e8369f2c5b383ecef0a45c221ec9 | gautam-dwivedi/Python-Basics-Arithmetic | /06 arithmetic2.py | 255 | 3.96875 | 4 |
# Python Basics
print("enter no a")
a= input()
#a= int (input("enter the value of a\n"))
print("enter no b")
b= input()
#b= int(input("enter the value of b\n"))
addition = a + b
print("Addition is:", addition)
print("type",type(addition)) |
68cfb3b8e6fc75ce43751a4263b9166558f14cec | southpawgeek/perlweeklychallenge-club | /challenge-159/lubos-kolouch/python/ch-1.py | 600 | 4.0625 | 4 | """ Challenge 159 Task 1"""
def farey_sequence(n: int, descending: bool = False) -> str:
"""Print the n'th Farey sequence. Allow for either ascending or descending."""
(a, b, c, d) = (0, 1, 1, n)
solution = []
if descending:
(a, c) = (1, n - 1)
solution.append(f"{a}/{b}")
while (c <= ... |
a66884e2c3cb289ce78d632d092737cdc82643c5 | jasperthegeo/Python_1 | /PyPoll/main.py | 1,540 | 3.6875 | 4 | import os
import csv
vote_dict ={}
votes_per_candidate={}
csvpath = ("Resources\election_data.csv")
with open (csvpath, 'r', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
next (csvreader)
for row in csvreader:
vote_dict[int(row[0])]=row[2]
votes_cast = len(vote_dict) #num... |
fb54d77051a80ba9fff92347248298da2432d1f0 | nelsonripoll/portfolio | /python/general/classes.py | 1,020 | 4.375 | 4 | class Rectangle():
"""A simple shape class"""
def __init__(self, length, width):
"""Initialize a rectangle with length and width"""
self.length = length
self.width = width
def get_area(self):
return self.length * self.width
def get_parameter(self):
return (sel... |
787db5a9244a5836705d542c1f9328081694d2f3 | kmiozan/arSerial | /sp_recognition.py | 4,233 | 3.640625 | 4 | #!/usr/bin/env python3
# NOTE: this example requires PyAudio because it uses the Microphone class
import speech_recognition as sr
# this is called from the background thread
def callback(recognizer, audio):
# received audio data, now we'll recognize it using Google Speech Recognition
try:
print("Reco... |
ede1296a5fe69e34a00f6ffb145bdc54f01e7674 | dmironov1993/hackerRank | /interview_prep_kit/Sorting/Sorting: Bubble Sort.py | 774 | 3.8125 | 4 | # https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countSwaps function below.
def countSwaps(n,a):
cnt = 0
for i in ran... |
aeab0d086481ab904204fb39c9780a33cca6f3ca | flash-drive/Python-First-Go | /Homework 2 Distance Between Two Points.py | 862 | 4.25 | 4 | # Homework 2 Distance Between Two Points
# Mark Tenorio 5/10/2018
# Write a program that finds the distance between two points
# on the cartesian plane
# Function to find distance between two points
def distance(x1,y1,x2,y2):
distance = ((((float(x2)-float(x1)) ** 2) + ((float(y2)-float(y1)) ** 2)) ** (... |
300e6b11d6f1a923b62722e8d112bae60a261956 | archerImagine/myNewJunk | /my2015Code/myGithubCode/6.00SC/Lec_22/src/example03.py | 5,049 | 3.5 | 4 | import random
class Node(object):
"""The base class for node"""
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
"""docstring for Edge"""
def __init__(self, src,dest,weight=... |
b9b4a570c69545d84b06d685385c1a0f3e5091b5 | ledbagholberton/holbertonschool-machine_learning | /math/0x00-linear_algebra/9-let_the_butcher_slice_it.py | 476 | 4.21875 | 4 | #!/usr/bin/env python3
"""FUnction which slice matrix
"""
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]])
mat1 = matrix[1:3]
mat2 = matrix[0:, 2:4]
mat3 = matrix[1:, 3:]
print("The middle two rows of the matrix are... |
93659380cf303b40c95a940cb38fbbff98251244 | chinmay81098/interview-coding-questions | /matrix_multiply.py | 906 | 3.953125 | 4 | def product_of_mtx(r1,c1,r2,c2):
mtx3 = []
if c1 != r2:
return "Product not possible"
else:
for i in range(r1):
row = []
for k in range(c2):
s = 0
for j in range(c1):
s = s+ mtx1[i][j]*mtx2[j][k]
row.... |
57a1479f78f4145a9d47f7b100266a7c64f475de | jayesh580/my_python | /chapter7/14_star.py | 111 | 3.96875 | 4 | star = int(input("Enter the number of star you want to print: "))
for i in range(star):
print("*" * (i+1))
|
def5415e9671a357a5d7a54c56dc3a89bf2d86e5 | HankerZheng/LeetCode-Problems | /python/213_House_Robber_II.py | 1,403 | 3.90625 | 4 | # After robbing those houses on that street,
# the thief has found himself a new place for his thievery so that he will not get too much attention.
# This time, all houses at this place are arranged in a circle.
# That means the first house is the neighbor of the last one.
# Meanwhile, the security system for these h... |
2d7b031efe2ffde9ce92d2826da5a179dc02e6b9 | HymEric/LeetCode | /python/207-课程表/207.py | 3,460 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/6 0006 10:02
# @Author : Erichym
# @Email : 951523291@qq.com
# @File : 207.py
# @Software: PyCharm
"""
现在你总共有 n 门课需要选,记为 0 到 n-1。
在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?
示例 1:
输入: 2, [[1,0]]
输出... |
e8f2a4a83c6680fe5798568d0f13d08065fca8c4 | gentov/RBE550-SearchAlgorithms | /Graph.py | 3,637 | 3.859375 | 4 | from Node import *
from tkinter import *
"""
the graph class handles all of the methods related to the grid. That includes: making it,
finding node neighbors, and finding node indexes and coordinates.
"""
class Graph():
def __init__(self, nodesTall = 4 ,nodesWide = 4):
self.nodesTall = nodesTall
sel... |
3917810b7eb2cae6c6c04a9c73e648d36f5c8514 | marcluettecke/programming_challenges | /python_scripts/string_difference.py | 3,354 | 4.1875 | 4 | """
Function to solve the following quiz, interesting for repeated sorting methods.
Given two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account
the lowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.
s1 = "A aaaa ... |
cc7c8831ee0c2ad6c8fa35a806284227ef135809 | DanielHowe/DanielHowe | /codeExamples/GraphicsProgramming/Games/calendar.py | 504 | 4.15625 | 4 | import calendar
from datetime import *
def mainCalendar():
#month = requestInteger("What month were you born?")
month = 2
#day = requestInteger("What day were you born?")
day = 9
#year = requestInteger("What year were you born?")
year = 1984
# Character formatting
lengthSpacing = 0
widthSpacing = ... |
0c4b8ca249da2ea1193a31f56adcb2292f5f3dc6 | tszreder/python_day2 | /Day2/conditionals.py | 2,410 | 3.75 | 4 | # Wyrażenie trójargumentowe
a = 25
b = 30
print(b) if a<b else print(a)
'''
P48
Napisz program, który wczyta od użytkownika liczbę całkowitą i bez użycia instrukcji if
wyświetli informację, czy jest to liczba parzysta, czy nieparzysta
'''
#print("PARZYSTA" if int(input("Podaj liczbę: ")) % 2 == 0 else "NIEPARZYSTA"... |
b00a0c46600231d9bed736b656c9f97e919edb7a | ssmmchoi/python1 | /workspace/chap03_DataStructure/exam/exam02.py | 858 | 3.625 | 4 | '''
step02 문제
문1) message에서 'spam' 원소는 1 'ham' 원소는 0으로 dummy 변수를 생성하시오.
<조건> list + for 형식1) 적용
<출력결과>
[1, 0, 1, 0, 1]
문2) message에서 'spam' 원소만 추출하여 spam_list에 추가하시오.
<조건> list + for + if 형식2) 적용
<출력결과>
['spam', 'spam', 'spam']
'''
message = ['spam', 'ham', 'sp... |
3a8d21c2d294927e93804da6a79ac19b04c3b369 | ljia2/leetcode.py | /solutions/range/253.Meeting.Room.II.py | 4,947 | 4 | 4 | from heapq import heappop, heappush
class Solution:
def minMeetingRooms(self, intervals):
"""
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
find the minimum number of conference rooms required.
Example 1:
Input:... |
6570c97c43af3dddb06fc0ddfa16e906e541f969 | caozongliang/1805 | /11day/2列表循环练习.py | 273 | 3.515625 | 4 | a = []
for i in range(1,101,2):
a.append(i)
#print(a)
a.pop()
#print("删除最后一个",a)
a.pop(0)#删除索引上的值
print(a)
a.remove(3)#删除指定值
print(a)
del a[0]#索引
print(a)#系统提供删除方法
#number = a[18]
#print(number,'laowang')
|
2a6e4a7b0e7ca8ca134419372afa4a881eb46c13 | qian316/Python_demo | /第9章 魔法方法、特性和迭代器/init_demo.py | 1,178 | 3.828125 | 4 | # _*_ coding:utf-8 _*_
# 构造函数__init__
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
print(f.somevar)
# 继承时候对构造函数的处理方法
## 第一种是调用未关联的超类构造函数
# class Brid:
# def __init__(self):
# self.hungry = True
# def eat(self):
# if self.hungry:
# print('Aaaah...')
#... |
de1b44d8403319daff4a882a72f31a04240d1828 | RoastedTurkey/ECTTP | /Class_Code/Les_10_Example/Les_10_Example.pyde | 1,015 | 3.515625 | 4 |
scramble("Kip", "kaars")
def scramble(word1, word2):
lengthWord = max(len(word1), len(word2))
result = ""
for i in range(0,lengthWord):
if (len(word1) < i):
result+= word1[i]
else:
if(i != lengthWord -1):
result+='0'
if (len(word2) ... |
982f08c89e239fc8ce4bdb90a81b0cde8d26fd05 | Shnobs/PythonOzonNS | /Lesson7/insert_sort.py | 560 | 3.84375 | 4 | import random
def insert_sort(arr):
result = arr.copy()
for i in range(1, len(result)):
currentValue = result[i]
currentPosition = i
while currentPosition > 0 and result[currentPosition - 1] > currentValue:
result[currentPosition] = result[currentPosition -1]
cu... |
c55153906343a57464290f20672082ffb82911eb | alekswatts/python | /p4u/3_dz/cycle.py | 381 | 3.890625 | 4 | keywords ="""
netflix ukraine
netflix сериалы
netflix українською
netflix это
netflix фильмы
netflix ru
netflix на русском
netflix movies
""".strip().split("\n")
print(keywords)
word = "netflix"
for keyword in enumerate(keywords):
print("Word: ", keyword, i)
if word in keyword:
print("Word in: ", ke... |
35178a2f86a45d4acb431e8c0649abd6dfffe42b | zhao-staff-officer/python-code | /Python_/day34.获取列表元素/ex34.py | 448 | 3.546875 | 4 | list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print("正序访问list1元素")
print(list1[0],list1[1],list1[2])
print("反序访问list1元素")
print(list1[-1],list1[-2],list1[-3])
print("截取list2字符")
print("list2[0:4]",list2[0:4]... |
5f9aa388dc0c1c3fb2879db5903afbed98c700c5 | daianasousa/Ensinando-com-as-Tartarugas | /Funcoes_em_toda_Parte.py | 1,941 | 3.734375 | 4 | from turtle import *
from random import *
#uma função para mover a tartaruga para uma posição aleatória
def moveToRandomLocation():
penup()
setpos( randint(-700,700) , randint(-700,700))
pendown()
#uma função para desenhar uma estrela de um tamanho específico
def drawStar(starSize, starColour):
c... |
6141f51504cd085b38edac4071dfc3b38a141c31 | marybahati/PYTHON | /MAKING LISTS.py | 5,769 | 3.765625 | 4 | Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> fruits=['banana','apple','mango','orange','melon']
>>> for fruit in fruits:
print(fruits)
['banana', 'apple', 'mango', 'orange', 'melon']
['b... |
e8d40f6035d178f81ae1f61d95c5dfa1440ffeb8 | WouterDelouw/5WWIPython | /Toets 2/Niet-starter.py | 204 | 3.78125 | 4 | # invoer
getal = float(input('geef een getal tussen 0 en 1: '))
som, exponent = 0, 0
# berekeningen
while som < getal:
exponent += 1
som += (1 / (pow(2, exponent)))
# uitvoer
print(exponent, som)
|
0c3447af7c6c9e6871ec06ef322ae0563b03aa54 | daniel-reich/turbo-robot | /k87ztfzqrpPHvgNWR_6.py | 1,040 | 3.875 | 4 | """
Given a list of strings _depicting a row of buildings_ , create a function
which **sets the gap between buildings** as a given amount.
### Examples
widen_streets([
"### ## #",
"### # ## #",
"### # ## #",
"### # ## #",
"### # ## #"
], 3) ➞
[
"### ## #",
... |
d92e9d9228f92a39cefe12473fa73e9ded4763f1 | queirozfcom/desafiohu1 | /scripts/csvtosqlinsert | 4,429 | 3.640625 | 4 | #!/usr/bin/env python
import sys
import os
import re
from datetime import date
# convert a csv file into sql insert statements
# to insert those values into given table and rownames
def run(inputfile,outputfile,tablename,rownames):
if not os.path.isfile(inputfile):
raise Exception('\'{0}\' is not a valid ... |
dc37bbfe05d6f5f50c0ebb1a7972b1f50c6359ad | borjur/discrete_Structures | /Cesar Cipher/Ceaser_Cipher.py | 1,776 | 3.65625 | 4 | '''
Created on Mar 4, 2013
@author: Boris Jurosevic
CS 2430
Assignment: Ceaser Cipher
TUTORIAL: stackoverflow, youtube videos,python forum.
'''
import time
import string
from string import ascii_lowercase
def Ceaser(words, enter):
converts = ""
new = ""
for a in words:
... |
55e82664af3679e60f4bef593164da2011c0a2b9 | bgeer/ALDS | /Tutorial_2/2-2.py | 5,869 | 3.515625 | 4 | from matplotlib import pyplot as plt
import numpy as np
import time
import statistics as stats
# Schrijf hier de code voor opgave 2
def random_int_array(length):
array = np.random.randint(-128, high=127, size=length,
dtype=np.int8) # een array'tje met ints tussen de 0 en de 100 (exc... |
3f8b26e719d44d213e42121254b7b536d19f4d39 | maliksh7/Data-Structure-and-Algorithms-in-Python | /Case Study of OOP via Python/oop.py | 2,090 | 3.84375 | 4 | class Address:
def __init__(self, house_no = 0, street = 0, city = "", country = ""):
self.house_no = house_no
self.street = street
self.city = city
self.country = country
def get_full_address(self):
return "H. No. "+ str(self.house_no) + ", Street "+ str(self.street) + ", "+ self.city + " "+ se... |
bd91b0ee12e6e201b5cbcf39608d012b29864938 | dsztanko/Algorithms_practice | /binary_tree/node.py | 400 | 3.609375 | 4 | class Node(object):
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
if self.left is not None:
self.left.parent = self
if self.right is not None:
self.right.parent = self
self.visited = False
... |
ee6c8337b6029379f9bd3149b48bc4366f8a5723 | rbozzini/python-repo | /examples/array_sum_functional_imperative.py | 392 | 3.875 | 4 | import functools
my_list = [1, 2, 3, 4, 5]
def add_it(x, y):
print("add_it(" + str(x) + ", " + str(y) + ")")
return (x + y)
# https://docs.python.org/3/library/functools.html
# Functional:
sum = functools.reduce(add_it, my_list)
print(sum)
# Lambda:
sum = functools.reduce(lambda x, y: x + y, my_list)
prin... |
6b39168f8d402038b27fb4733dcfe34dc101ac8a | MysteriousSonOfGod/Python-2 | /Lyceum/lyc2/pg_rgb_target.py | 561 | 3.828125 | 4 | import pygame
n = int(input())
k = int(input())
red, green, blue = (255, 0, 0), (0, 255, 0), (0, 0, 255)
if k % 3 == 0:
colors = [blue, green, red]
elif k % 3 == 1:
colors = [red, blue, green]
else:
colors = [green, red, blue]
size = n
n += k * n - size
pygame.init()
screen = pygame.display.set_mode((300,... |
ae3579dd35fd375f39266c261013e28b6ab17a8e | iampaavan/Stacks_Queues_Deques_Python | /print_queue_challenge.py | 1,186 | 3.59375 | 4 | import random
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
if self.items:
return self.items.pop()
return None
def is_empty(self):
return self.items == []
class Job:
def __init__(self):
... |
9623c76235db38b3934f64559b2836a0160cb387 | suresh-boddu/algo_ds | /ds/trees/amazon_test.py | 1,502 | 3.890625 | 4 | class Node:
left = None
right = None
data = None
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class Tree:
root = None
def __init__(self, root):
self.root = root
def find_lca(node, key1, key2):
if not node:... |
8d87fae41fc862a47059f0169c978c65d2370a01 | catoteig/julekalender2020 | /knowitjulekalender/door_03/door_03.py | 2,397 | 3.890625 | 4 | def make_horizontal(matrix_txt_txt):
horizontal_result = ''
file = open(matrix_txt_txt, 'r')
horizontal = file.readlines()
for row in horizontal:
horizontal_result += row[:-1]
return horizontal_result + ' ' + horizontal_result[::-1]
def make_vertical(matrix_txt):
vertical_result = ''... |
6242edcc86f032baf60c1dacd5186290475f9398 | TodorovicIgor/Yamb | /util/aux_funcs.py | 4,036 | 3.6875 | 4 | import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def calc_val(dices, i, throws):
if 0 <= i <= 5:
sum = 0
for dice in dices:
sum = sum+dice.get_val() if dice.get_val() == i + 1 else sum
return sum
elif i == 6:
"""
for min value it is c... |
727f675002bf05b5b133d8d7540df8793f49b9ba | wattewiler/CIP_Project | /c1_web_scrapper.py | 1,015 | 3.640625 | 4 | #### webscrapping of data source C1; data dimansions: Country name, continent name
####
#### input: https://www.bernhard-gaul.de/wissen/staatenerde.php#uebneu
#### output: c1_country_src.csv
# ladet die Libraries
import requests
from bs4 import BeautifulSoup as bs
# download html file und unwanldung in soup objek... |
f18ce2e18d4d2b118f9864b5b004873aeaf2f9d8 | ElizabethBeck/Class-Labs | /lab01.py | 1,137 | 4.40625 | 4 | integer_1 = int(input("Enter one integer: "))
integer_2 = int(input("Enter one integer: "))
integer_3 = int(input("Enter one more integer: "))
print("You put in:", integer_1, integer_2, integer_3)
added = integer_1 + integer_2 + integer_3
print("Sum =", added)
product = integer_1 * integer_2 * integer_3
print("Product ... |
ee4e4287fad943bbbfb0d758e8061a6fcfe41d45 | codingyen/CodeAlone | /Python/0206_reverse_linked_list.py | 583 | 3.96875 | 4 | class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
retur... |
3932d629a09debcfd22695434fffc5038e5fa5a2 | MerrickMath/MerrickMath.github.io-PythonProject | /Square.py | 212 | 4.5 | 4 | # This Is A Program That Finds Area Given Sidelength
print("This is a Program That Finds The Area Of A Square Given A Sidelength")
a = input("input a sidelength: ")
a = int(a)
area = a**2
print("Area: ", area)
|
0759274e584965c5b26d9a7dd1f070fb279df27d | qhuydtvt/C4E6-Lectures | /Session1/1.py | 155 | 3.953125 | 4 | print('Hello world')
n = input("what's your name?")
n = "ahfuehf"
print('Hello ', n)
y = int(input('your year of birth?'))
age = 2016 - y
print(age)
|
72f44d445be20c46469d1d29ad54c169b8812062 | billkrauss3/pynet_test | /strex1.py | 202 | 3.78125 | 4 | #!/usr/bin/env python
str_1 = "John Doe"
str_2 = "John Conner"
str_3 = "John Lennon"
print "{:>30} {:>30} {:>30}".format(str_1, str_2, str_3)
str_4 = raw_input("Enter fourth name: ")
print "{:>30}".format(str_4)
|
3ad4128eed8c5122fc21bf18228d8e63cc7c93ba | kartik-soni1707/Python-Practicals | /Binary Search.py | 392 | 3.734375 | 4 | def binary_search(ar,key,low,high):
if low >high:
return -1
else :
mid =int((low+high)/2)
if ar[mid]==key:
return mid
elif key>ar[mid]:
low=mid+1
else:
high=mid-1
binary_search(ar,key,low,high)
ar=[1,2,3,4,5,6,7,8,9]... |
f9753ff525e8241f4a1db0770ba211a88609e3f1 | pepperchini/curly-funicular | /Guessing_Game.py | 722 | 4.34375 | 4 | secret_number = 16
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
number = int(input("Enter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.