blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
7a3119eb105894553bb5664257127a22efb5585f | shimischwartz/67101_INTRODUCTION_TO_COMPUTER_SCIENCE_EX_2 | /check_largest_and_smallest.py | 1,004 | 4 | 4 | #################################################################
#FILE:check_largest_and_smallest.py
#WRITER:shimon_schwartz , shimioschwartz , 201572807
#EXERCIS:intro2cs1 ex2 2018-2019
#DESRIPTION:a programe that checks the function:
# "largest_and_smallest" from above
###############################################... |
600e0e1fef0fed40a8d081093e8311d26227a488 | Hoan1028/IS340 | /IS340_ExtraCredit1_7.py | 846 | 3.90625 | 4 | #Ch 6. Functions Problem 7
#Find best customer from biggest sale
#Program continuosly prompts user until sentinel. First input is sale, second is customer name
def main():
#Create empty lists
sales = []
customer = []
saleInput = 0
#Prompt then read the input values until sentinel
print("Please enter sale followed ... |
c5fbb42554a9473809f9dc75e78d93697e5c7a4d | DelStez/PythonLabs | /1.22.py | 542 | 4.21875 | 4 | # Характером натурального числа назовем сумму всех его делителей, не равных единице и самому числу.
# Характером простого числа будем считать нуль.
# Написать программу, которая вычисляет характер числа.
n_1 = int(input("Введите натуральное число: "))
e = 0
for i in range(2, n_1):
if n_1 % i == 0:
e = e + i... |
d0f6c436410d8118c31adf455bcdb8bfcac868e6 | sudoom/Python_study | /IT-Academy/Lesson 3/3.3.py | 105 | 3.6875 | 4 | String = 'Hello!Anthony!Have!A!Good!Day!'.split('!')
String.pop()
String.sort()
print('\n'.join(String))
|
406031eef6e7d27eef03fd78e7f84ba3260c2178 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/a7c6110364184cf78d41080aef034aca.py | 364 | 3.875 | 4 | def difference(num):
return square_of_sum(num) - sum_of_squares(num)
def square_of_sum(num):
# Square of the first n numbers added together
numList = xrange(1,num+1)
return ((numList[0] + numList[-1]) * len(numList) / 2) ** 2
def sum_of_squares(num):
# Finds the sum of the first n squares
retu... |
31fe6ffc6fa12eafd5447ca7c6a328a100f605c7 | srikantanp/GraduateTrainingProgram2018 | /Python/card.py | 610 | 3.84375 | 4 | """#l=[1,2,3,4,5]
def square(n):
return n**2
def cube(n):
return n**3
#y=map(square,l)
funcs=[square,cube]
for i in range(5):
value=map(lambda x:x(i),funcs)
print value
#print(type(y))
#print (y)"""
import pandas as pd
df=pd.DataFrame(data=[1,2,'test',4,5])
#print df
df1=pd.DataFrame(data={'col... |
5535b1ca065081b3ee3ae82c9ae35676a51f88d1 | Laksh-Devloper/Guess_The_Number | /guess.py | 353 | 4.125 | 4 | import random
random_no = random.randint(1, 10)
guess = 0
while guess != random_no:
guess = int(input("Guess a Number(from 1 to 10): "))
if guess < random_no:
print("Be Bold Increase Your Guess")
elif guess > random_no:
print("Don't Be Too Bold Decrease Your Guess")
print("JackPot computer t... |
460969e95696e157a7f96f1ec5efd6458fda962d | shivamsammy/my-files | /RockPaperScissors.py | 1,320 | 4.0625 | 4 | import random
while True :
choice_list = ["rock", "paper", " scissors"]
computers_choice = random.choice(choice_list)
users_choice = input(" please enter your choce :").strip()
if users_choice=='rock'or users_choice=="paper " or users_choice=='scissors':
if users_choice== computers_choice... |
bad9b2f0308cc852b4e7f2edc7841768edfef192 | QuietghostDev/Python | /tupleListSorter.py | 540 | 3.53125 | 4 | def sortBy(tup):
return tup[1]
def openFile(fileName, mode):
f = open(fileName, mode)
return f
def main():
f = openFile("Quotes","r")
quoteList = f.readlines()
f.close()
tupleList = []
for i in quoteList:
quote = i[:i.index("%")]
name = i[i.index("%")+1:]
tupleL... |
8cd4ce5a2242852f9a55758bf0159ba00e1bf767 | dracohan/script | /python/byteOfPython/func_param.py | 247 | 3.640625 | 4 | #!/usr/bin/env python
# Filename: func_param.py
def printMax(a,b):
if a>b:
print a,'is maximum'
else:
print b,'is maximum'
printMax(3,4) # directly give literal values
x=5
y=7
printMax(x,y) # give variables as arguments
|
ab8c2665a80dce19f606898985efba9c38b53107 | ebegeti/LeetCode-problems | /reorderLogFiles.py | 1,588 | 3.796875 | 4 | '''
You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-logs: All words (except the identifier) consist of digits.
Reorder these lo... |
a6dfcac153e99d202543c470eb7b4fc7dd6dac9a | eharley19/python_practice | /dsa1/sortAlgos.py | 3,358 | 4.0625 | 4 | def selection_sort(lst):
lst_length = range(len(lst) - 1)
for i in lst_length:
min_index = i
for j in range(i + 1, len(lst)):
if lst[j] < lst[min_index]:
min_index = j
if min_index != i:
lst[min_index], lst[i] = lst[i], lst[min_index]
... |
fb72b639d43074aeba30d4d20a57d9e30807c4ce | Linter-8/week1 | /test5.py | 480 | 3.734375 | 4 | #回到原点
countx = 0
county = 0
answer="no"
while(answer=="no"):
mingling=input("you choose:")
if(mingling=="U"):
county+=1
if(mingling=="D"):
county-=1
if(mingling=="L"):
countx-=1
if(mingling=="R"):
countx+=1
else:
print("please input rihgt ... |
0dad8d5f7eea6769cd632442c70b298bb45c5db3 | mark124/CIS-214 | /Activity-8/useGraph.py | 2,363 | 3.796875 | 4 | # This program exercises graphs.
# Replace any "<your code>" comments with your own code statement(s)
# to accomplish the specified task.
# Do not change any other code.
# The following files must be in the same folder:
# abstractcollection.py
# graph.py
from graph import LinkedDirectedGraph
# Part 1:... |
a6c443170bf95b5ed456bd3aee542f8aa9aa8c41 | usernamesarehard15/rpg | /color.py | 794 | 4.21875 | 4 | def colorStr(string, col):
"""Returns a coloured version of the input string
Keyword arguments:
string -- input string
col -- tuple of 3 ints from 0-5, representing the text colour
"""
if 1 >= col[0] >= 5 or 1 >= col[1] >= 5 or 1 >= col[2] >= 5:
return
col = str(col[0] * 36 + col[1]... |
bfb45c8d02d432288848a4bf5bfffbad01a358cb | crudalex/microsoft-r | /leetcode/removeElements.py | 850 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def insert(self, x):
if not self.next:
self.next = ListNode(x)
else:
self.next.insert(x)
class Solution:
def removeElements(self, head, val):
... |
16285b0afcb5ae8042688065cbb463abd5a79df5 | yongyonghw/algo | /algo/yonghw/Level1/xSpace.py | 263 | 3.765625 | 4 | def number_generator(x, n):
# 함수를 완성하세요
arr = []
sum = 0
for i in range(n):
sum += x
arr.append(sum)
return arr
# 아래는 테스트로 출력해 보기 위한 코드입니다.
print(number_generator(3,5)) |
0edebb0b37a389d890d7ed3b0774c530d0693cc9 | yujinnnnn/python_practice | /py.script/CH03/bmi1.py | 358 | 3.9375 | 4 | def bmi_f(h,w):
b=0.0
h=h/100
b=w/(h**2)
return b
height, weight, bmi =0.0,0.0,0.0
height = float(input("Enter your height >> "))
weight = float(input("Enter your weight >> "))
bmi = bmi_f(height, weight)
if bmi >= 20 and bmi<= 24:
print("표준체중")
elif bmi < 20:
print("저체중")
else:... |
05b41aaba459ff436756158ff0f79b99e49fbd6d | LydiaSbityakov/INCAT | /Preprocessing and Clustering Code/nvd_annotation_data_parser.py | 4,356 | 3.515625 | 4 | #
# DESCRIPTION:
# This Program (nvd_annotaion_data_parser.py) parses json files from the national threat database and converts to csv
# files containing randomly selected sets of 50 records containing the ID and Description for annotation processing
#
# NOTE: not all fields available in the threat database are conve... |
8cd05cc8efd6a9b3a36a6a346ccd051b3660f9cf | nlewis97/cmpt120Lewis | /Tennissimulation.py | 716 | 3.9375 | 4 | # Introduction to Programming
# Author: Nicholas Lewis
#Date: 4/27/18
# Tennissimulation.py
from simstats import SimStats
from Tennismatch import Tennismatch
def ProgIntro():
print("This program functions as a simulation for a tennis match ")
def getStats():
probA = float(input("Enter the probability of A wi... |
d1227e6c72fe18214bc982099549f8643381936c | alperkesen/game-of-life | /gol.py | 1,293 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
class GameOfLife(object):
def __init__(self, width=25, height=25, world={}):
self.start = 0
self.width = width
self.height = height
self.world = world
if not self.world:
self.create... |
ac2e658b803dececf8fdc079e971266aadcb5acc | hyo-eun-kim/algorithm-study | /ch20/kio/ch20_1_kio.py | 1,469 | 4.0625 | 4 | '''
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1... |
c79d316a32332b5ff508a559332449d1cdae0fe3 | sidarthshahri/Intro-to-Computer-Networks | /Lab_1/UDPClient.py | 1,043 | 3.796875 | 4 | from socket import * # Contains everything you need to set up sockets
# Create destination server name and server port to send message to
server_name = '127.0.0.1' # This can be a website URL! DNS lookup happens automatically, very cool
server_port = 400 # Port address is the socket address ... |
51b42fbf538ff032a28e56ad7d56c07c77c6ba11 | Faisal-Alqabbani/python_fudamentals_assigments | /OOP/store_products/alqabbani_faisal.py | 1,178 | 3.5625 | 4 | class Store:
def __init__(self,name):
self.name = name
self.list = []
def add_product(self, newProduct):
self.list.append(newProduct)
return self
def sell_product(self, id):
self.list.remove(id)
return self
def inflation(self, percent_increase):
fo... |
64e81b6f723c51b996fd08315bda1b5e27b2bf9b | benFrogg/System-Security | /RainbowTable/RainbowTable.py | 5,820 | 3.5625 | 4 | # Import
from hashlib import md5
class RainbowTable:
def __init__(self, password = "", hashVal = "", reduceVal = ""):
self.W = password
self.H = hashVal
self.R = reduceVal
# Q1P1
# Get a list of all lines
def _totalPassword(self):
file = open(r'Wordlist.txt'... |
490c79f06f5d5e005379e410244543d0db666e11 | jbaudson/smallpbs | /pb005.py | 551 | 3.953125 | 4 | # 2520 is the smallest number that can
# be divided by each of the numbers from
# 1 to 10 without any remainder.
# What is the smallest positive number
# that is evenly divisible by all of
# the numbers from 1 to 20?
from math import sqrt
from math import ceil
def isMinMult(x, nb) :
count = 2
while count <= x... |
c092a2264171853a9b074db8fe070dd01f3e0a01 | katherinelasluisa/Laboratorio3 | /calculadora1.py | 1,158 | 3.984375 | 4 | import math
figura = int(input("Ingrese un numero de lados de una figura geometrica : "))
if figura == 2:
print ('no hay figuras geometricas formadas por dos lados')
elif figura == 3:
a = int(input("ingrese el lado 1 del triangulo: "))
b = int(input("ingrese el lado 2 del triangulo: "))
c = int(input("ingrese ... |
d4bfe5bce8734309b3b8c6a596ad8cd60c3ca370 | jonas-bird/Using-Python-to-Interact-with-the-Operating-System-by-Google | /Week3_4ModuleReview.py | 2,663 | 4.46875 | 4 | #%%
"""
Using Python to interact with the operating system, by Google
WEEK 3 – Regular Expressions
4 MODULE REVIEW
Qwiklabs Assessment: Working with Regular Expressions
Introduction
It's time to put your new skills to the test!
In this lab,
you'll have to find the users using an old email domain in a big list u... |
5323970e9fccfe63d88a0d4a818fc81e43564f75 | leefakes/HIT137 | /assignment2/question_1.py | 4,225 | 4.125 | 4 | # Import module
import turtle
class DrawNumber():
def __init__(self, size=100, width=20, x=0, y=0, colour="#000000"):
# turn off draw mode
self.turtle = turtle.Turtle()
self.turtle.speed(0)
self.turtle.penup()
self.turtle.goto(x, y)
self.turtle.showturtle()
... |
f825efaebbdfb79f76803f380d0702c6579efcec | nidiodolfini/descubra-o-python | /URI/1013.py | 212 | 3.703125 | 4 | dados = input().split(" ")
a = int(dados[0])
b = int(dados[1])
c = int(dados[2])
if a > b and a > c:
print(a ,"eh o maior")
elif b > a and b > c:
print(b , "eh o maior")
else:
print(c, "eh o maior") |
4ffe0cc1ce358a8df99f907d30a17ae5c93008d2 | joelgarzatx/portfolio | /python/Python3_Homework02/src/coconuts.py | 1,779 | 4.25 | 4 | """
API for coconut weights
"""
# [item for item in a if item[0] == 1]
class Coconut:
def __init__(self, coconut_type):
"""
Create a coconut object. Valid type are "South Asian", "Middle Eastern", and "American"
"""
self.coconut_types = (("South Asian", 3), ("Middle ... |
3b503d569dc86ba652d3a7aa2acded9ade1148ba | LuannMateus/python-exercises | /python-files/third_world-exercises/13-functions_part_2/exer101-voting_functions.py | 810 | 4.125 | 4 | '''Exercício Python 101: Crie um programa que tenha uma função chamada voto()
que vai receber como parâmetro o ano de nascimento de uma pessoa, retornando um
valor literal indicando se uma pessoa tem voto
NEGADO, OPCIONAL e OBRIGATÓRIO nas eleições.'''
# Title;
def title():
print('\033[1;37m~~' * 20)
print('V... |
91bf02fd6f7bdfeb538e82fe90bfb538e28efc5c | surya-pratap-2181/python-all-programs | /prob10_dictionayList_average.py | 1,069 | 4.21875 | 4 | '''
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.
marks key:value pairs are
'alpha':[20,30,40]
'beta':[50,40,70]
query_name = 'beta'
The query_na... |
5f2c17004bc86f17ebc9b3cf015a1ac691160807 | ahmedragab96/Network-Assignments | /CRC/main.py | 4,398 | 3.53125 | 4 | # Returns XOR of 'a' and 'b'
# (both of same length)
def xor (a, b):
# initialize result
result = []
# Traverse all bits, if bits are
# same, then XOR is 0, else 1
for i in range(1, len(b)):
if a[i] == b[i]:
result.append('0')
else:
... |
296eee0c1dc3c46faf91784ca4ea464358d9837a | Zoey215/Newcoder_HW | /字符个数统计.py | 111 | 3.65625 | 4 | s = input()
a = []
for i in s:
if ord(i) in range(128) and i not in a:
a.append(i)
print(len(a))
|
0df17421b67e91fabe70c78ec855ee623c4f42cb | Dark-Leader/sorting-algorithms-visualization | /shapes/buttons_handler.py | 2,222 | 4.125 | 4 | from shapes.button import Button
class ButtonsHandler:
"""
The ButtonHandler takes care of all the buttons in the display.
Parameters
----------
button : list / Button.
the list of buttons.
Attributes
----------
self.buttons : list.
this is where we store the list of button... |
e694a63d1c8c3431f4889ebc59e24f37dc69fe60 | Alan-Flynn/Python-Labs | /printing.py | 263 | 3.578125 | 4 | # Name: Your Name
# Student ID: 012345678
# File: printing.py
############################################################################
##
## Your code goes here
##
def printing(l):
for i in l:
print(i * 2, end = '')
|
1201fc0a5cfb89adcf9a1107faba0a3936c61c7d | bertcarremans/RaspberryPi_Projects | /LED/morse_led.py | 1,700 | 3.828125 | 4 | from gpiozero import LED
from time import sleep
# LED connected to GPIO pin 25
led = LED(25)
# Time length for morse signs
# There's a silence lasting exactly as long as a dash, between letters.
# And, between words, a pause that lasts exactly as long as seven dots.
# More info on : https://www.quora.com/How-do-you... |
c6109538ca83105fdbacdfe82fbf7d35f6cd8e38 | abbas-malu/Python | /hangman/main.py | 2,192 | 3.875 | 4 | from words import word
import random
import os
print("Welcome To Hangman Game")
print("""Rules:
1.The Word to be guessed is randomly generated
2.The total attempts to guess the letter are 6.
3.Every time you guess wrong your one attempt will be deducted""")
ch = 1
while ch == 1:
atmpt = 6
w_mn = word()
#w_m... |
5771ccb7927c6fbd6a50fe63c9b28fa29b6c11e1 | karurvishal/Python_Examples | /bubble_sort.py | 503 | 4.21875 | 4 | def bubble_sort(elements):
size = len(elements)
for i in range (size-1):
swapped = False
for j in range (size-1-i):
if elements[j] > elements[j+1]:
temp = elements[j]
elements[j] = elements[j+1]
elements[j+1] = temp
swapped = True
if not swapped:
break
if __name__ == '__main_... |
91e123f3c487164829104a881d78010442177690 | NinaTrif/Genome_Informatics_Project | /burrows_wheeler_transform.py | 1,455 | 3.6875 | 4 | def rotations(s):
""" Return list of all rotations of input string s """
# Assumes $ has already been appended to the input string t
tmp = s * 2
return [tmp[i:i + len(s)] for i in range(0, len(s))]
def bwm(t):
""" Return lexicographically sorted list of t’s rotations """
return sorted(rotation... |
3c128a2f3c26ba1a9bbcfd1342b1210b38968589 | JaderMac/USP-intro-cienc-comp-Python | /Semana 4/primos.py | 239 | 3.90625 | 4 | numero = int(input("Digite um número inteiro:"))
cont = 0
i = 0
while ((i<=numero) or (cont<2)):
i=i+1
x = numero%i
if x==0:
cont=cont+1
if cont <= 2:
print("primo")
else:
print("não primo")
|
0d08b017fef45c3c33a01320db7e4d5e00eb2e26 | Git-Sergio/Python3Git | /ITGenio/you_like_your_boss?.py | 144 | 3.796875 | 4 | kinder = ''
while kinder != 'I like my boss!':
kinder = input('you like your boss? \n')
print('Okej')
input('Thanks, Please touch "ENTER"')
|
3e432c098553c6a1cf913f7a8304c6c765ee2657 | AndressAndrade/ufba-python-ilp | /Unidade 2/ex16.py | 178 | 3.578125 | 4 | lista = [2,5,7,8,4,1]
ord = []
for elemento in lista:
k = 0
while k < len(ord) and elemento > ord[k]:
k = k + 1
ord = ord[:k]+[elemento]+ord[k:]
print(ord)
|
8e16ccbb69b0e2b70bd1f1b7b10e15bcc8fd7a4e | sanjeevs/puzzles | /turtle/curves.py | 824 | 3.84375 | 4 | import turtle
def draw_circle(pen, incr, angle, total_trip=360):
num_steps = round(total_trip / angle)
for i in range(num_steps):
pen.fd(incr)
pen.rt(angle)
def draw_qcircle(pen, incr, angle):
draw_circle(pen, incr, angle, 90)
def draw_spiral(pen, incr, angle):
for i in range(1024)... |
506bbf7c6530ad4af12fed138a893316706d152a | jayprajapati009/OpenCv-BasicCodes | /How_to_Write_Text_on_Images.py | 563 | 4.1875 | 4 | # How to draw shapes on an empty image
# Importing Libarary
import cv2
import numpy as np
print('Library Imported')
# Creating an empty matrix of size (512, 512) for creating a black empty image
img = np.zeros((512, 512, 3), np.uint8)
#img[:] = 255, 0, 0 To Give a specific colour to our image
# Putting a text ... |
5c5cb61ae6edc27d74486a714abb619dba51236e | wbroach/python_work | /review3.py | 398 | 3.78125 | 4 | def show_magicians(magicians):
for magician in magicians:
print(magician.title())
def make_great(things):
for i in range(len(things)):
things[i] += " the Great!"
return things
magicians = ['tom', 'dick', 'harry', 'steve']
magicians_plus_the_great = make_great(magician... |
726652d30e84bed4f714162c0b59b0363ebde556 | profnssorg/claudioSchefer1 | /8_6.py | 424 | 3.859375 | 4 | """Programa 8_6.py
Descrição:Reescrever programa da listagem 8.8 de forma a utilizar for em vez de while
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
# Entrada de dados
L = [1,7,2,9,15]
# Processamento
def soma(L):
total = 0
x = 0
for e in L:
total += L... |
d1a6cf1b658d460a48d5b05ae64b714ae7386a45 | bethmlowe/Python | /avg_sale_calc.py | 3,149 | 4.1875 | 4 | #===============================================================================
#Program: Average Sale Calculator
#Programmer: Elizabeth Byrne
#Date: June 19, 2021
#Abstract: This program will input a salesperson's name follwed by the
# first sale amount then the number of sales as... |
7b759807d97f4d5fd300d6e6a20d5790c6652e70 | SEOULVING-C1UB/Daily-Algorithm | /Daily-Algo/2020-09-03 Queue/미로의거리/손준희_미로의거리.py | 1,511 | 3.578125 | 4 | movement = [[-1, 0], [1, 0], [0, -1], [0, 1]] # 좌 우 상 하
def find_start_pos(N): # 종착지 찾는 서브함수
for y in range(N):
if 3 in maze[y]:
return [maze[y].index(3), y]
return 0
def maze_runner(maze): # 미로 탈출하는 서브함수
que = [[0, find_start_pos(N)]] # [거리 0, 종착점]
check_list = []... |
54da8cf5738b85407fdba0421b542dfaddb87b7b | wangxiaodong-950127/git | /test.py | 1,680 | 3.859375 | 4 | def homework1():
str="aaa你好,你好ajflajfalk你好"
print (str.count("你好"))
def homework2():
n=3
while n>0:
a = input("input:")
if a == '1':
print('Monday')
break
elif a == '2':
print('Tuesday')
break
elif a == '3':
... |
fcf9ea9fcc1cacb1f5c957680fd09407e8e8d5a8 | gateway17/holbertonschool-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 1,224 | 3.953125 | 4 | #!/usr/bin/python3
"""
Write a class Rectangle that inherits from BaseGeometry (7-base_geometry.py).
(task based on 8-rectangle.py)
Instantiation with width and height: def __init__(self, width, height)::
width and height must be private. No getter or setter
width and height must be positive integ... |
f7f90c9ec941eec64e14f3c3380f4501f879c330 | yidianfengfan/lutos_doc | /doc/type.py | 568 | 3.5625 | 4 | #int
integer_number = 90
#
float_number = 90.4
#
complex_number = 10 + 10j
#list
sample_list = [1,2,3,'abc']
#dictionary ֵ
sample_dic = {"key":value, 2:3}
#tuple ֻ
sample_tuple = (1,3,"ab")
#Ƕ
sample_nest = [(1,2,3),{1:2,3:4,'key':[1,2]},3]
#everythind is object
'str str'.split() #['str', 'str']
1..is_inte... |
17117084dc4ee8d7e28496ac5ccd8a8ceeb48efc | SoumyaMalgonde/AlgoBook | /python/linked_list/Singly_LinkedList.py | 2,866 | 4.25 | 4 | class Node:
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def to_linkedlist(self, input_list):
#Function to create a linked list from a input list.
self.tail = None
for item i... |
dc7ad8b432b8557f91a6a8e4b549a996c8c8a65a | jaaanko/advent-of-code-2020 | /day-17/solution.py | 3,176 | 3.609375 | 4 | def getAdjacent4d(x,y,z,w):
adjacent = []
for x1 in range(x-1,x+2):
for y1 in range(y-1,y+2):
for z1 in range(z-1,z+2):
for w1 in range(w-1,w+2):
if x1 == x and y1 == y and z1 == z and w1 == w:
continue
adjacent... |
3e12f4829a403862f9f3f31d66c464671ee7782e | DanielW1987/python-basics | /python_012_threads/communication/CommunicationUsingBooleanFlag.py | 919 | 3.78125 | 4 | from threading import *
from time import *
class Producer:
def __init__(self):
self.__products = []
self.__orders_placed = False
def produce(self):
for i in range(1, 5):
self.__products.append("Product {}".format(i))
sleep(1)
print("Item added")
... |
7847783b84c3e8355d84e715cad27a60fce4174b | balwantsinghmnit/using-databases-with-python-coursera | /emaildb.py | 798 | 3.5625 | 4 | import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts(email TEXT, count INTEGER)')
file_name = input('Enter File Name')
if len(file_name)<1:
file_name = 'mbox-short.txt'
file = open(file_name)
for line in file:
if ... |
f489dc98b116a1e421dff98c3bf190d108ba8704 | ranajaydas/AutomateBoringProject | /regex_phonenumberfinder.py | 1,157 | 4.1875 | 4 | import re
raw_text = 'My name is Ranajay Das. My phone number is +65 96648194. My other cell number is +65 97776555'
""" Find a phone number without using any grouping """
print(' Without grouping '.center(30, '='))
phone_regex1 = re.compile(r'\+\d{2} \d{8}') # can also add () around the \d to create groups
mo... |
bc25c6842b9a16a538ca6f7b65d58872a00fbaad | liangshinegood/lg-Python | /the_hard_way/loops.py | 829 | 4 | 4 | N = int(input("请输入一个整数:"))
for i in range (0,N):
print(i**2,end='\t')
sumA = 0
n = 1
while n <=100:
sumA += n
n += 1
print('1..100的和为:',sumA)
print('使用function sum can do this:',sum(range(1,101),0)) # 从什么 0 , 1,2 开始就要加上后面的这个数
# 注意break 的使用
for n in range(2,6):
for x in range(2,n):
if n % x == ... |
29addae478443b9ae01a1d9d68ab28a6a0fce6c0 | dauren/programming-kbtu | /notes/aziz/02.py | 205 | 3.9375 | 4 | def toUpper(c):
if ord(c) >= 97 and ord(c) <= 122:
x = ord(c) - 32
return chr(x) #Функция .upper, которую написали мы сами
return c
c = input()
print (toUpper(c)) |
86d8a77b7177e906bd392158eb8b1aacb12b6b83 | osamascience96/CS50 | /python/exceptions.py | 264 | 3.65625 | 4 | from sys import exit
try:
a = int(input("A: "))
b = int(input("B: "))
except ValueError:
print("Invalid Input")
exit(1)
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by 0")
exit(1)
print(f"{a} / {b} is {result}") |
cb43ba23d72707ae06506c5f3847e3f38b76c3d0 | sakshigarg22/python-projects | /array.py | 211 | 3.828125 | 4 | def triangle(n):
k = 2*n-2
for i in range(0,n):
for j in range(0,k):
k = k-1
for j in range(0,i+1):
print("*",end="")
print("\n")
n = 5
|
2da9ea8ac294025eefc3d59df0524bf5a75d1cf7 | Jsonlmy/leetcode | /人生苦短/二叉树的直径.py | 1,290 | 4.15625 | 4 | '''
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
'''
# Definition for a binary tree node.
clas... |
da45003dc8841e6bed0ddee34ac19b1d0195d1bb | Ben0p/tropos_converter | /TropOSkml.py | 5,553 | 3.515625 | 4 | import os
'''
Mine Systems TropOS drive csv to kml converter
Input a formatted .csv of the TropOS drive results
Generates a .kml
'''
def generate(csv_in):
'''
Generate a .kml from a formatted .csv
csv_in is the input formatted .csv
'''
# Header of .kml
header = (
'<?xml version="1.0... |
87ea8a21f2af9c32c8f10817e022b289c3216b92 | cindy3124/Study_PythonWebFramework | /2.login.py | 1,158 | 3.9375 | 4 | # -*- coding: utf-8 -*-
'''
2、使用python编写一个命令程序:里面保存了若干用户成员的信息,用户只有登陆后才能查看这些用户的信息。
即:用户启动python脚本,然后输入用户名密码登陆成功后,使用命令可以查看其他用户信息
'''
user = {'1':'a','2':'b','3':'c'}
user_info = {
'1':['小丽','女','11111111'],
'2':['小林','男','11111112'],
'3':['林艳','女','11111113']
}
# 判断用户名是否存在
def login(username):
if userna... |
131c757182ed0642b0b74bd92724d08cd8deb264 | 547sereja/netology_stack | /mystack.py | 589 | 3.828125 | 4 | class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def size(self):
return len(s... |
f005d49e585455ae7e6ca044f146cbb2467de553 | dgpllc/leetcode-python | /learnpythonthehardway/Numbers-At-Most-N-Given-Digit-Set-902.py | 3,933 | 3.984375 | 4 | # We have a sorted set of digits D, a non-empty subset of {'1','2','3','4','5','6','7','8','9'}. (Note that '0' is
# not included.)
#
# Now, we write numbers using these digits, using each digit as many times as we want. For example, if D = {'1','3',
# '5'}, we may write numbers such as '13', '551', '1351315'.
#
# Re... |
bfe3382721e77f50aca3e9c6a14ff16f5afaedd9 | Emmalito/Mastermind | /fonction_projet_2.py | 2,830 | 3.734375 | 4 | import os
import pickle
from random import *
def récup_nom_utilisateur(a):
nom_utilisateur = input("Nom joueur 1 : ")
nom_utilisateur = nom_utilisateur.capitalize()
if a > 1:
nom_utilisateur_2 = input("Nom joueur 2 : ")
nom_utilisateur_2 = nom_utilisateur_2.capitalize()
... |
ea0fd7c5729ff632944bc1c0b02514e7e6f324d3 | kdk745/Projects | /CS313E/Mondrian.py | 4,802 | 3.515625 | 4 | # File: Mondrian.py
# Description: Draws a scenic background, random trees with fruits, and then writes poetry
# Student Name: Kayne Khoury
# Class ID number: 76
# Student UT EID: kdk745
# Course Name: CS 313E
# Unique Number: 51730
# Date Created: 3/5/2015
# Date Last Modified: 3/7/2015
import turtle... |
d71d94e5ca13f845c86446808c87de317d3f09ea | mnaniwa-291031/programming_study | /project_euler_study/0001/p_e_0001.py | 174 | 4 | 4 | #!/usr/bin/env python3
def sum_multi_3or5(z):
return sum([x for x in range(z) if (x % 3 == 0) or (x % 5 == 0)])
print(sum_multi_3or5(10))
print(sum_multi_3or5(1000))
|
1001186005ac7ab5688153f36749b7bd98f9fc1c | isisisisisitch/geekPython | /basic/review/Demo05.py | 226 | 3.75 | 4 | #获得用户输入,用户输入的值是#则退出,否则让用户重新输入
if __name__ == '__main__':
ans = input('type something: ')
if ans == "#":
print("exit")
else:
print('try again') |
d22eb510bfffc5cc4b850b34e141e1b739c9bc2b | sparshjain265/AI-Lab | /puzzle15/tempCodeRunnerFile.py | 453 | 3.828125 | 4 | print("Enter the elements of the matrix: ")
for i in range(self.dimension):
temp = input().strip().split()
for j, x in zip(range(self.dimension), temp):
if(x == '*'):
self.mat[i][j] = self.dimension*self.dimension
#print(self.mat[i]... |
06e10a6530efc5bfc50040dc12c1d0840f3eb5e1 | Nafisa-Tasneem/Problem-solving | /timeconversion.py | 439 | 3.609375 | 4 | s = input()
def timeConversion(s):
arr = s.split(sep= ':')
arr2 = list(arr[2])
arr2.pop()
ap = arr2.pop() # returns A or P
arr2_new = ''.join(arr2)
arr[2] = arr2_new
# print(arr2_new)
if ap == 'P' and arr[0] != '12':
arr[0] = str(int(arr[0]) + 12)
if arr[0] =='12' and ap ==... |
61879d32e917834aea7aa66efaedad904ffb1794 | sabbirDIU-222/Learb-Python-with-Sabbu | /sgpa.py | 168 | 3.890625 | 4 | numberOfSub = int(input())
marks = input()
marksAsList = marks.split()
sum = 0
for x in marksAsList:
sum += int(x)
avg = sum/numberOfSub
print(avg)
|
bb509ac0710fae9103b7b6a3932af4720d4a38ea | vinicius5581/learn-phyton | /userInputAndCasting.py | 117 | 3.90625 | 4 | string = str(input("Name: "))
print("Hello", string)
number = int(input("Number: "))
print("The number is", number) |
70b38f9c5a0ad3803f5a0e53e5a11da5c90319c9 | sahasukanta/college-assignments-repo | /Assignment 2/domino175.py | 9,693 | 3.859375 | 4 | # CMPUT 175 Assignment 2
# Author: Sukanta Saha
# Student ID# 1624111
from queues import CircularQueue as cq
import random
class Domino:
"""Domino object with max of 6 dots"""
def __init__(self, dotsA, dotsB):
"""
Creates a domino with dots A and B
inputs: two integers b/w 0 and 6
... |
1ed4ea179560b5feec261b094bdbe5b2848b4e03 | Sharmaanuj10/Phase1-basics-code | /python book/book projects 1/4-7/input while loop/flag.py | 321 | 4.1875 | 4 | active = True
print("if you want to quit type quit")
while active:
message = input("Enter your message: ")
if message == 'quit':
# break # to break the loop here
active = False
#comtinue # to execute left over code exiting the if
else:
print(message)
... |
99650bd684602c9b7ec6483dff666e4689a56cd2 | adityawalunj/PyCharm-Projects | /CarRentalInc.py | 1,592 | 3.90625 | 4 | def getValidInput(prompt,error,options):
value=input(prompt)
value=value.upper()
while value not in options:
print(error)
value=input(prompt)
value=value.upper()
return value
def getValidNumber (prompt,error,min,max):
number = input(prompt)
while not number.is... |
2d7ca7edc8ba3175ed555b37022886d4e2b1620a | fpem123/programmers_challenges | /Level 3/디스크_컨트롤러.py | 646 | 3.65625 | 4 | from queue import PriorityQueue
def solution(jobs):
answer = 0
q = PriorityQueue()
size = len(jobs)
jobs = sorted(jobs, key=lambda x: x[1])
jobs = sorted(jobs, key=lambda x: x[0])
a, t = jobs.pop(0)
q.put((t, a))
time = a
while not q.empty():
t, a = q.get()
time += ... |
f1eb1227bfb3b1c8cbe51a92b839e32c23e322f3 | katerinanil/repa | /web_server/aho_rec.py | 1,166 | 3.5625 | 4 | from string_algorithms import aho_corrasick, naive_find
def _aho_rec(ans, lst):
i = ans[-1][0] #first element of last taken tuple
sub = ans[-1][1] #2nd element of last taken tuple
nextI = i + len(sub) #index of next substring
"""in case we got full combo or made our best
we return them, otherwise w... |
3c1b00c95906daac6afde2944d459c08727cc8ff | venkatsvpr/Problems_Solved | /LC_Minimum_Number_of_Arrows_To_Burst_Ballons.py | 1,902 | 3.921875 | 4 | """
452. Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of t... |
b90a74ec01ea4587157f79c68e853b2e6860cf3a | yangbo1/leetcode | /35_searchInsert.py | 1,187 | 4.0625 | 4 | # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
#
# 你可以假设数组中无重复元素。
#
# 示例 1:
#
# 输入: [1,3,5,6], 5
# 输出: 2
# 示例 2:
#
# 输入: [1,3,5,6], 2
# 输出: 1
# 示例 3:
#
# 输入: [1,3,5,6], 7
# 输出: 4
# 示例 4:
#
# 输入: [1,3,5,6], 0
# 输出: 0
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/search-i... |
758a7126cb01830538be7ba11e9177374b98fdc5 | seanbrhn3/AI-with-python | /practice/random_test_data.py | 944 | 3.578125 | 4 | #Creating a csv file with random data to then use for testing purposes
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import normalize
def make_Data():
with open("test_data.csv",'w') as data:
for i in range(1,1001):
data.write(str(random.randint(0,i)... |
699939dfd88932db5dfd86f6fcfc3cc6ac6f3bf3 | southrriver/pytt | /src/base/class/to_dict.py | 685 | 3.75 | 4 | # -*- coding: utf-8 -*-
class Person:
desc = 'Person'
def __init__(self, name, age):
self.name = name
self.age = age
def get_desc(self):
return self.desc
def object_member_tt():
p = Person('hong', 18)
pd = p.__dict__
print(pd)
print(p.g... |
118c1ad282b67213a8ed099aefdcc3909f75ecb7 | Batyi/Website-Fingerprinting-on-Proxy | /workspace/outlier_detection/z_score_algo.py | 1,148 | 3.75 | 4 | import numpy as np
#% matplotlibinline
import matplotlib.pyplot as plt
"""
When computing the z-score for each sample on the data set a threshold must be
specified. Some good ‘thumb-rule’ thresholds can be: 2.5, 3, 3.5 or
more standard deviations.
"""
def detect_outliers_with_z_score(data):
"""
... |
0209b32df16d2dd25ed03093f452e792f20dfe44 | fionnmccarthy/FionnWork | /Week03/Lab3.3.2-normalise.py | 526 | 4.34375 | 4 | # normalise.py
# Lab 3.3 Part 2
# This program takes in a string and strips any leading or trailing spaces,
# the program should also convert the string to lower case.
# Author: Fionn McCarthy
rawString = input("please enter a string:")
normalisedString = rawString.strip().lower()
lenghtOfRawString = len(rawString)
l... |
d4c0d4ec99948a1bd0f29489b8e4a452635b7aed | HTML-as-programming-language/HTML-as-programming-language | /HTML_to_C_compiler/htmlc/html_parser.py | 6,481 | 3.765625 | 4 | import re
from htmlc.utils import split_preserve_substrings
class HTMLParser:
"""
The HTML parser reads the HTML file that is given in feed()
While it reads the HTML file it will call several methods of the handler:
- handle_starttag() when it encounters a start-tag like <var a=5>
- han... |
9b13c6742e2cdd74b14090381aaf0e5c6cf0b5c2 | halysl/python_module_study_code | /src/study_cookbook/14测试调试与异常/调试基本的程序崩溃错误.py | 424 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import traceback
import sys
def func(n):
return n + 10
# func('Hello')
# python3 -i 调试基本的程序崩溃错误.py
# 以上指令会打开 Python shell
try:
func('hello')
except:
print('**** AN ERROR OCCURRED ****')
traceback.print_exc(file=sys.stderr)
def sample(n):
if n > 0:
sample(n-1)
... |
f16e4381404c5816aa8460cdfde929bd2563a9e9 | tahsinalamin/leetcode_problems | /leetcode-my-solutions/35_search_insert_pos.py | 543 | 4.25 | 4 | """
Author: Sikder Tahsin Al-Amin
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Input: [1,3,5,6], 5
Output: 2
"""
def searchInsert(nums, target):
if target <nums[0]:
return 0
for i in ... |
c351080e5a4fccd375a3b1fbc89e54ce3e381039 | DorianGPersaud/Factorial---Iterative-Implementation | /main.py | 457 | 4.1875 | 4 | x=int(input("Choose a value of x for f(x)=x! "))
if x<0:
print("You can't take the factorial of a negative number!")
elif x==0:
print(1)
else:
y=input("Choose a factorial, 1 (front) or 2(back) ")
if y==1:
def Frontfactorial(x):
z=1
for i in range(1,x+1):
z*=i
return z
print(Fro... |
ecec10e23c9ddccc6cffe282662a25b7909889b0 | wwxFromTju/Python-datascience | /python-data-analysis/python_data_analysis/ch09/ch09-2.py | 905 | 3.640625 | 4 | #!/usr/bin/env python
# encoding=utf-8
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
people = DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
print people
people.ix[2:3, ['b', 'c']] ... |
c1939ec3639349e088486fee07e89127aa8ad123 | Gaurav3099/Python | /L1/ip-op.py | 151 | 3.9375 | 4 | #add two numbers
s1 = input('enter first number')
n1 = int(s1)
s2 = input('enter second number')
n2 = int(s2)
res = n1+n2
print('Result ' ,res)
|
c952f00084078c4c85959f68220d095cc381cf56 | DieHard073055/fluffy-tanuki-of-life | /search_algorithm.py | 1,517 | 4.0625 | 4 | #
# @file search_algorithm.py
# @author Eshan Shafeeq
# @version v0.5
# @date 27 August 2015
# @brief This file contains the depth first search algorithm to
# do a DFS after generating a random maze from the maze
# generation algorithm.
class search_algorithm():
"""docstring for ... |
52d5f9a42b720b9266827eeae06b9e6f1959e8e6 | wangtao090620/LeetCode | /wangtao/leetcode-easy/0268.py | 409 | 3.78125 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : wangtao
# @Contact : wangtao090620@gmail.com
# @Time : 2020-07-19 10:39
from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
num_set = set(nums)
n = len(nums) + 1
for num in range(... |
b2fc2047da988f53ec8ab8c91e39a2aea5144d45 | cmeikle/PlanetOSAPI | /LandWaterContent/checking_out_data.py | 936 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import requests
import logging
import io
import folium
#import urllib
from pathlib import Path
data_folder = Path("../LandWaterContentData/")
apikey = "c9f1fcccdac44031a945633ce6df8da3"
latitude = "15.5"
longitude = "-15.5"
#latitude, longitude = lat_long_roundin... |
58e2c9c303e3d243727c81e0c6ac5686e31398d6 | allenzhong/UserUpload | /test/test_user.py | 2,001 | 3.765625 | 4 | import unittest
from processors.user import User
class TestUser(unittest.TestCase):
def test_create_user(self):
name = 'John'
surname = 'Allen'
email = "johnallen@email.com"
user = User(name, surname, email)
self.assertEqual(name, user.name)
self.assertEqual(surname, user.surname)
self.a... |
b3ef626cfb5c61e147273a7ca0592b72d1dd4ede | romeorizzi/temi_prog_public | /2019.02.27.recupero/all-CMS-submissions-2019-02-27/20190227T103225.VR437299000.collatz.py | 295 | 3.5 | 4 | """
* user: VR437299000
* fname: ENRICO
* lname: MELEGATI
* task: prova-collatz
* score: 0.0
* date: 2019-02-27 10:32:25.361553
"""
i=int(input())
print(i)
lista = [i]
while i>1:
if i%2==0:
i=i/2
else:
i=3*i+1
print(i)
lista.append(i)
#print(lista)
|
a33646ee5bdf5d76b28a84cedefbb4abf07971e6 | chlomcneill/project-euler-python | /Python/Euler44.py | 1,002 | 3.515625 | 4 | import itertools
pentagonal_numbers = []
for num in range(1,1000):
pentagon_num = (num*((3*num)-1))/2
pentagonal_numbers.append(pentagon_num)
# print(pentagonal_numbers)
pairs_diff = []
for x, y in itertools.combinations(pentagonal_numbers, 2):
if abs(x-y) in pentagonal_numbers:
pairs_diff.append... |
19c8d89b8809cd13bbb150f1b0e20303fdb3600a | adamrodger/google-foobar | /5.py | 4,778 | 3.53125 | 4 | # Notes:
# - https://www.youtube.com/watch?v=wdDF7_vfLcE
# - this video was incredibly helpful
# - a standard 2D grid can be rotated or reflected 8 ways - 4 rotations, where 1 rotation is the 'do nothing'
# rotation and 4 reflections (horizontel, vertical and 2 diagonals)
# - So G = 8 in orbit/st... |
ba3732c144ebb98a0beab50bde0df9a185282391 | nosoccus/python-online-course | /TASK_6/customlist.py | 4,993 | 4.125 | 4 | # Кожен вузол містить дані і вказівник на наступний (LinkedList)
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
# Список має вказівник на початок
class LinkedList:
def __init__(self, nodes=None):
self.head = Non... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.