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 |
|---|---|---|---|---|---|---|
d11e5c2dd401e69ba65f98f2557fb496ff1e1a47 | trivedisorabh/Triangle-Symmetries-with-Python-Turtle | /triangle_symmetry_turtle..py | 4,097 | 4.03125 | 4 | import turtle
import tkinter as tk
screen = turtle.Screen()
class Label(turtle.Turtle):
def __init__(self, coordinates=None, screen=screen):
turtle.Turtle.__init__(self)
if coordinates is None:
self.coordinates = [0, 0]
else:
self.coordinates = coordinates
... |
b20a049364c8648b65d06340a2cdd1613ff9c5ec | chris31513/haskell-pearls | /Python/criptoaritmos.py | 3,745 | 3.546875 | 4 | #Christian Rodrigo Garcia Gomez
#Decidí usar Python por que se me facilita mucho más pensar el código en este lenguaje.
#Especificamente para este problema es más sencillo usar Python porque resulta más claro a la hora de trabajar con listas.
import random
import sys
import gc
sys.setrecursionlimit(30000000)
def cr... |
2358ce9bd1a93f9692cff142908bde4f985fd4c5 | sukiskumar/sukiskumar | /ex3.py | 202 | 4.125 | 4 | ch=input("enter a char:")
if(ch=='A'or ch=='a'or ch=='E'or ch=='e'or ch=='I'or ch=='i'or ch=='O'or ch=='o'or ch=='U'or ch=='u'):
print(ch,"its a vowel letter")
else:
print(ch,"its a consonent")
|
7bd52e231d77bfe94c4277772ef77bc4f56b7f57 | Andyyesiyu/IS590 | /Assignment/A2/hw2.py | 10,993 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from ast import literal_eval as make_tuple
import math
# Edge definition:
# - p1, p2: endpoints of the segment
# - slope: slope of the segment
# - intersect: intersect of the line (extention of the segment most probably) on the y axis
class Edge:
def __i... |
4db5286513dde4db5afc628bb1c084b187ee898a | sfaisalaliuit/dictionary | /dict_double_prog3.py | 439 | 3.90625 | 4 | faisal = {'username': 'sfaisal', 'online': True, 'students': 145, 'section':'Computer Science', 'experience in years':21}
farhan = {'username': 'farhanahmed', 'online': False, 'students': 144, 'section':'Software Engineering', 'experience in years':15}
for key, value in faisal.items():
print(key, 'is the key f... |
f846806fe36f18555ee326609d90581c099e6ee2 | ps3296/Automated-Pun-Generator | /python files/Scripts/Scripts/homonyms_textfile_cdt/trial_generate_jokes.py | 967 | 3.765625 | 4 | def indefinite_article(w):
if w.lower().startswith("a ") or w.lower().startswith("an "): return ""
return "an " if w.lower()[0] in list('aeiou') else "a "
def camel(s):
return s[0].upper() + s[1:]
def joke_type1(d1,d2,w1):
return "What do you call " + indefinite_article(d1) + d1 + " " + d2 + "... |
7f27483d65ad0113c2b9159fa6ef4e15c59992b7 | TeamContagion/CTF-Write-Ups | /2022/SekaiCTF2022/crypto/SecureImageEncryption/enc.py | 1,646 | 3.6875 | 4 | from PIL import Image
def openImage():
#opens both images and loads them
img1 = Image.open("encryptedimg1.png")
img2 = Image.open("encryptedimg2.png")
pixels1 = img1.load()
pixels2 = img2.load()
width1, height1 = img1.size
width2, height2 = img2.size
list1 = []
#check for correct s... |
47846eb1a2b8b5db15f5f7262ae51e15973eb75b | oxfordni/python-for-everyone | /examples/lesson2/4_exercise_1.py | 372 | 4.21875 | 4 | # Determine the smallest number in an unordered list
unordered_list = [1000, 393, 304, 40594, 235, 239, 2, 4, 5, 23095, 9235, 31]
# We start by ordering the list
ordered_list = sorted(unordered_list)
# Then we retrieve the first element of the ordered list
smallest_number = ordered_list[0]
# And we print the result
... |
0c4af3021580b97e5d9d244695e5a22e5e9eb136 | oxfordni/python-for-everyone | /examples/lesson2/1_data_types_tuples.py | 152 | 3.875 | 4 | # Define an initial tuple
my_tuple = (1, 2, 3)
# Print out the list
print(my_tuple)
# Print the value at the beginning of the list
print(my_tuple[0])
|
c700081a72e7cc131897478a8f02db1507044b07 | apalaciosc/python_quantum | /practica_01/ejercicio_01.py | 180 | 3.671875 | 4 | def ensure_question(palabra):
if len(palabra) == 0:
print('Cadena no válida')
else:
print(f'{palabra}?')
palabra = input('Escriba una palabra: ')
ensure_question(palabra)
|
321b6d8b4b9ccd840eef7801dccf0cffa7a571fe | apalaciosc/python_quantum | /clase_07/scrapping.py | 893 | 3.875 | 4 | from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title story title2"><b>The Dormouse's story</b></p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="si... |
c1bbd7598c2a95628257451d744cfd3cf6bf1f98 | nawan44/Python-Basic | /iteration.py | 171 | 4.03125 | 4 | #basic iteration
Spirit = 5
for Day in range(1, Spirit+1):
print('Never Give Up')
#iteration in string
Hi = 7
for Good in range(2, Hi+7):
print(f'Morning {Good}') |
55e1d5407c28c0ea3953dedfe7bb97981a8d0455 | nawan44/Python-Basic | /arithmetic.py | 476 | 3.921875 | 4 |
#Standart Operator Arithmetic
a = 10
b = 3
#operator +
res = a + b
print(a, '+', b ,'=', res)
#operator -
res = a - b
print(a, '-', b ,'=', res)
#operator - Multiple
res = a * b
print(a, '-', b ,'=', res)
# operator / Dividen
res = a / b
print(a, '/', b ,'=', res)
# operator ^2 Eksponen
res = a ** b
print(a... |
18ca47e10a0af9166e4366ca61b3a726bbc74454 | callmefarad/Python_For_Newbies | /sesions/stringslice.py | 756 | 4.53125 | 5 | # slicing simply means returning a range of character
# this is done by using indexing pattern
# note when dealing with range the last number is exclusive.
# i.e if we are to get the last letter of digit 10, we would have a
# range of number tending to 11 where the 11th index is exclusive
# declaring my variable
my_s... |
f8ccced9d2f8bf8df346c5f5ff77a1fbc8d32954 | callmefarad/Python_For_Newbies | /sesions/rangetype.py | 367 | 4.125 | 4 | # showing range type representation
# declaring a variable name range_of_numbers
range_of_numbers = range(40)
# displaying the range of numbers
print("Below shows the range of numbers")
print(range_of_numbers)
# displaying python representation of the output value
print("Below show the python data type representation... |
85b7757dd6d1e1e5a6872596d297e5a690707f86 | callmefarad/Python_For_Newbies | /sesions/sorting_item.py | 5,457 | 4.3125 | 4 | # SORT
# the sorted() function is used to sort items in ascending order by default or by user prescriptions.
# basic sorting is used without a key and mapping function
# BASIC SORT
# sorting items in a list
print('\nsorted() function shows all the items in ascending order')
items = [1, 29, 37, 97, 2, 57, 37, 58, 46, 6... |
4a2d69fd9c1d182db95a7df2dbead89b3628f002 | callmefarad/Python_For_Newbies | /sesions/stringreplacement.py | 164 | 4.40625 | 4 | # The string replacement is used to replace a character with another
# character in that string.
my_sentence = "Ubani Friday"
print(my_sentence.replace("U", "O"))
|
b30d79e7e57f57b9b079bb566e41c6deb88425c5 | callmefarad/Python_For_Newbies | /sesions/languagetranslation.py | 708 | 4.0625 | 4 | # This progrma is called the cow translation language.
# It converts every vowel letter found in a word to "COW", thereby forming the cow language.
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
def translate(phrase):
word_translation = "" # an empty variable to hold each elem... |
b59e530c1b2e7d8275003cde9e1b8bce78d9b43f | callmefarad/Python_For_Newbies | /sesions/membershipin.py | 536 | 4.3125 | 4 | # a membership operator checks if sequence is present in an object
# "in" is on of the membership operator
# creating a variable named "
my_list = ['orange', 'bean', 'banana', 'corn']
print("List of items: ", my_list)
# creating a check variable
check = "banana"
# prints the result
print(check in my_list)
""""
# c... |
fd0795fd1e3b86ce259b392b644d5ade274655f0 | callmefarad/Python_For_Newbies | /sesions/func.py | 1,652 | 4.15625 | 4 | # # declaring a function
# def dummy():
# print("this is a dummy print.")
#
# # callin the function
# dummy()
#
# def add():
# user1 = float(input('Enter your firstnumber: '))
# user2 = float(input('Enter your secondnumber: '))
# sum = user1 + user2
# return sum
#
# # call the function
# add()
# x ... |
0f6be41aa20de93a0ec323b95b78b7e1b906996e | callmefarad/Python_For_Newbies | /sesions/division.py | 257 | 3.828125 | 4 | # division operator is represented with a forward slash "/"
# it is used to get a floating value after a successful divisional operation.
all_states = 30000
lagos_state = 307
total_count = all_states / lagos_state
print("The total count is: ", total_count) |
05700d145da30b014ab880e5af9be1a13d3a0a98 | callmefarad/Python_For_Newbies | /sesions/passwordChecker.py | 1,122 | 4.125 | 4 | # a program that checks if a password is too weak, weak and very strong
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
# main function
special_characters = ['!', '^', '@', '#', '$', '%', '&', '*', '(', ')', '_', '+']
special_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']... |
918bcf54bf0c511c9f3b07af080991bb0ae64965 | satvks/Djikstras-Dungeon | /P1/p1-myvers.py | 6,713 | 3.84375 | 4 | from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initia... |
9e34742605447bc3ec4ab6da44d9b5ae5a19d32b | MetallicMonkeyu/image_encrypt | /Cube.py | 5,417 | 3.5625 | 4 | from PIL import Image
from Key import *
class Cube:
#im_path can be pefected by asking user to choose a folder
def __init__(self, img_path = [], block_size = 8):
self.image = [] #Open a new file
self.blc_size = block_size
self.img_path = img_path
def Row(self, row_index, shift... |
67c8770308f34f234d91c330da73e5aefee2a58c | Ilis/dawson | /useless_trivia.py | 585 | 4.125 | 4 | # Useless trivia
name = input("Hi! What's your name? ")
age = input("How old are you? ")
age = int(age)
weight = int(input("What is your weight? "))
print()
print("If Cammings write you a letter, he write", name.lower())
print("If mad Cammings write you a letter, he write", name.upper())
called = name * 5
print("Kid... |
d05ab90c27a5d8821c19b17cb48a2dafc78f35bc | GaboUCR/Mit-Introduction-to-python | /ps1/Ps1B.py | 848 | 4.28125 | 4 | total_cost = float(input("Enter the cost of your dream house "))
annual_salary = float(input("enter your annual salary "))
portion_saved= float(input("enter the percentage to be saved "))
semi_annual_raise = float(input("Enter the percentage of your raise"))
current_savings = 0
annual_return = 0.04
total_months = 0
por... |
9aac5e114701687f7fd97c620cdba469a6d117de | malikrafsan/Python-Language-Linter | /cyk_parser.py | 1,244 | 3.578125 | 4 | # File ini adalah CYK Parser yang digunakan
# Pada file ini, dilakukan pengecekan syntax dengan CYK
def cyk_parser(grammar, prob):
#grammar -> a dictionary of CNF
#prob -> string problem
#Set up variable
numb = len(prob)
if(numb == 0):
return True
parsetable = [[[] for i in range(num... |
b5e10ed6fec1e800562c5e7a381eceb00b53b6ab | aleph2c/miros-random | /set_hacking.py | 673 | 3.59375 | 4 | from itertools import combinations
def make_combo(_max, _pick):
comb = combinations(list(range(1,_max+1)), _pick)
return list(comb)
print(make_combo(3, 2))
def make_next(_max, _pick):
full_combo = [a for a in make_combo(_max, _pick)]
sub_combo = [b for b in full_combo if _max in b]
return sub_co... |
8111dfc4110b25b75a6d8f4e3e583aa583a54d31 | DoughyJoeyD/WorkLog2 | /task.py | 1,889 | 4.125 | 4 | from datetime import datetime
import os
import time
#handy script to clean the screen/make the program look nice
def clearscreen():
os.system('cls' if os.name == 'nt' else 'clear')
#how each task is constructed
#name
#date of task
#time taken
#extra notes
class Task():
def __init__(self):
... |
bd0e4c8d341eab303c06ea1a3ab55c1b67cce480 | uniquezhiyuan/ShipClassify | /route_revise.py | 3,550 | 3.6875 | 4 | import numpy as np
import pandas as pd
from math import sqrt
import time
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# print(data_1.describe())
# 最小二乘回归
def least_squares(x, y):
x_ = x.mean()
y_ ... |
4aed7141e11f5cabd8d860ecdac245dffe71e6df | Gutwack/pythonProjects | /basicMetacamDose.py | 235 | 3.921875 | 4 | breed = input("Is this a dog or a cat?")
weight = float(input("What is the weight?"))
if breed == "dog":
dose = weight * 0.04
print(dose)
elif breed == "cat":
dose = weight * 0.05
print(dose)
else:
print("error")
|
01886e6780ca312c23c54061942ab487f0477727 | olamileke/web-scraping | /nytimes.py | 2,209 | 3.65625 | 4 | # Python program to fetch the contents of an nytimes article
from bs4 import BeautifulSoup, Tag
from urllib.request import Request, urlopen
import re
url = input('enter the url for the nytimes articles - ')
# formatting the text in the format we want
def parse_text(soup):
article_title = soup.h1.string
artic... |
2035a32bf51f3e3b3134e30a2943dd7d7a66220f | Terund/tools | /代码/进程、线程、协程/多线程访问共享数据的问题.py | 889 | 3.75 | 4 | """
多线程访问共享数据的问题:
1.哪些问题
数据混乱问题
2.如何解决
用锁(互斥锁)threading.Lock
获取锁(上锁)
lock.acquire()
释放锁(解锁)
locl.release()
获取锁与释放锁的次数要对应
好处:
保护数据安全,实现数据同步,不会混乱
弊端:
效率降低
容易导致死锁
"""
import time
import threading
#模拟的总票数
tickets = 1000
lock = threading.Lock()
def sale(name):
global tickets... |
2ac555d1dccc370a726e52e8283c1957de19b7a5 | andrew5205/Maching_Learning | /Python/regression/linear_regression/linear_regression.py | 1,933 | 3.828125 | 4 |
# Linear
# y = b0 + b1 * x1
# y: Dependent Variable (DV)
# x: Independent Variable (IV)
# b1: Coeddicient
# b0: Constant
# sum( y - y^) ** 2
# *********************************************************************************************************************
# Simple Linear Regression
# Importing the librarie... |
4ee82efb6887d9f33e7d71fdec4fa23bb129cd57 | StrategyCode/CourseEra | /Assignment_4.6.py | 392 | 3.6875 | 4 | def computepay():
if Hr > 40:
GrossPay=((Hr-40) * 1.5 * RatePerHour + (40 * RatePerHour))
else:
GrossPay=Hr * RatePerHour
return GrossPay
Hr=input("Enter Hours Worked")
RatePerHour=input("Enter Rate per Hours")
try:
Hr=float(Hr)
RatePerHour=float(RatePerHour)
except:
print("Pleas... |
ca3966a88fae4251deb78a587564f7bb82d348ec | StrategyCode/CourseEra | /Assignment_12.2.py | 617 | 3.578125 | 4 | #To read the Web Content using URL and get the sum of all numeric Values.
import urllib.request,urllib.error,urllib.parse
import re
from bs4 import BeautifulSoup
sum=0
#Reading the content of Web Page
#WebContent=urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.html').read()
WebContent=urllib.request... |
2062897e73bd9d494b843b2853bb63cfa3010477 | AzizIsa/python-challenge | /PyBank/main.py | 1,738 | 3.765625 | 4 | #Import necessary libriaries
import os
import csv
import sys
#Define average function
def average(list):
return int(sum(list) / len(list))
#Create a path for the file
csvpath = os.path.join('Resources', 'budget_data.csv')
# Open the csv file
with open(csvpath, newline='') as csvfile:
# read the file
csvre... |
48f2cb31b76fb208e71f6ffe91d372979886dd47 | harshagl2002/COVID_CLI | /Province_CovidTracker.py | 2,835 | 3.53125 | 4 | import requests
import json
import datetime
def province():
url = "https://covid-19-statistics.p.rapidapi.com/reports"
ISO = input("Enter the ISO code of the country that you would like to search for.(ISO code of India is IND. ISO code of New Zealand is NZ): ")
province = input("Enter the province you wou... |
913d183c3e9b8d62e2637c2f4bef9748c0923f83 | LostRob/Paradise | /水仙花数.py | 196 | 3.609375 | 4 | a = int(input( 'a = '))
x = int(a//100)
y = int((a//10)%10)
z = int(a%10)
if (x ** 3 + y ** 3 + z ** 3) == x * 100 + y * 10 + z:
print('是水仙花数')
else:
print('不是水仙花数')
|
b00bc36b3d68b0ecdb14f3b8906e032593a74038 | SuryaNMenon/Python | /Functions/shapeArea.py | 699 | 4.03125 | 4 | def circArea():
radius = int(input("Enter radius"))
print("Area =", (3.14 * radius**2))
def triArea():
base = int(input("Enter base"))
height = int(input("Enter height"))
print("Area =", (0.5 * base * height))
def recArea():
length = int(input("Enter length"))
breadth = int(input("Enter breadth"))
... |
2327acffc2344bdbc183846ef128e0337d5367c3 | SuryaNMenon/Python | /Classes/rectangleClass.py | 343 | 3.90625 | 4 | class Rectangle:
def __init__(self,length,width):
self.length = length
self.width = width
def Area(self):
print(f"Area = {self.length * self.width}")
def Perimeter(self):
print(f"Perimeter = {2*(self.length + self.width)}")
rec1 = Rectangle(5,10)
rec2 = Rectangle(20,10)
rec1.... |
7df9906b8a9cc0b658ed28494a8598c0948625ec | SuryaNMenon/Python | /Dictionaries/mapLists.py | 295 | 4.03125 | 4 | userlist1 = []
userlist2 = []
for iter in range(int(input("Enter the number of keys"))):
userlist1.append(input("Enter key: "))
for iter in range(int(input("Enter the number of values"))):
userlist2.append(input("Enter value: "))
userdict = dict(zip(userlist1,userlist2))
print(userdict) |
ae9a97b3fb40b8285182bb65d435f836de70ada6 | SuryaNMenon/Python | /Functions/timeAndCalendar.py | 543 | 4.21875 | 4 | import calendar,time
def localTime():
localtime = time.asctime(time.localtime(time.time()))
print(f"Current local time is {localtime}")
def displayCalendar():
c = calendar.month(int(input("Enter year: ")),int(input("Enter month: ")))
print("The calendar is:\n",c)
while(1):
choice = int(input("Menu\... |
a71788020b4f3fb954314330c388705e504a56dc | SuryaNMenon/Python | /Other Programs/whileCountdown.py | 192 | 4.21875 | 4 | #Program to print a countdown using user input range and while loop
high = int(input("Please enter the upper limit of the range"))
i=high
while i>-1:
print(i)
i-=1
print("Blast off!")
|
fb5c157023bdc1099b78647dcf39010377639d26 | SuryaNMenon/Python | /Files/writeAndRead.py | 284 | 3.625 | 4 | with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt","a") as file:
file.write(input("Enter data to be inserted into the file. EOL = NewLine"))
with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt", "r") as file:
for line in file:
print(line) |
8c2bbc0c0175bc8883d9fe65cbca3511dbefd81e | SuryaNMenon/Python | /Other Programs/leapYear.py | 217 | 4.3125 | 4 | #Program if user input year is leap year or not
year = int(input('Enter the year'))
if(year%4==0 or year%100==0 or year%400==0):
print('Given year is a leap year')
else:
print('Given year is not a leap year')
|
6feb3063ad9b8e229f56dd16dc7c9c7a525bf1d5 | SuryaNMenon/Python | /Other Programs/factorial.py | 187 | 4.34375 | 4 | #Program to print factorial of user input number
num = int(input('Enter the number\n'))
fact = 1
for iter in range(1,num+1):
fact = fact * iter
print('Factorial of', num, 'is', fact)
|
6722bc1f4b416b80bf6211d900e3444c27abd2b9 | bigsnarfdude/d3py | /d3py/css.py | 2,020 | 3.671875 | 4 | #!/usr/bin/python
class CSS:
"""
a CSS object is a dictionary whose keys are CSS selectors and whose values
are dictionaries of CSS declarations. This object is named according to the
definition of CSS on wikipedia:
A style sheet consists of a list of rules.
Each rule or rule-set consi... |
5493d5308b986e4efd6bfed3687712872d76bc35 | hyjae/udemy-data-wrangling | /DataCleaning/audit.py | 2,698 | 4.21875 | 4 | """
Observation of types
- NoneType if the value is a string "NULL" or an empty string ""
- list, if the value starts with "{"
- int, if the value can be cast to int
- float, if the value can be cast to float, but CANNOT be cast to int.
For example, '3.23e+07' should be considered a float because it can be cast
... |
d203e5505f5db11247c9235d678999ed345e5d61 | PrathmeshPure/fun-py-programs | /file-translator-using-googleapi.py | 4,098 | 3.734375 | 4 | '''
by: Prathmesh Pure
This program is written to translate small text or srt files from
original language to target language.
Source language is detected automatically.
This program is just passing a string and language code to google translate api
and takes response from api and displays only translated text.
Languag... |
4afad85b6bcbaf932ee7a4754308804db627d963 | kalyanrohan/ASSIGNMENTS | /FIBONACCI.py | 246 | 4.15625 | 4 |
#0,1,1,2,3,5,8
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
nterms = int(input("n= "))
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i))
|
1df3bc87016ad046ffc4c7a27108e943ae84da27 | kalyanrohan/ASSIGNMENTS | /level2excercise.py | 1,187 | 4.6875 | 5 | #LEVEL 2
"""
1.Using range(1,101), make a list containing only prime numbers.
"""
prime=[x for x in range(2,101) if x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0]
print(prime)
"""
2.Initialize a 2D list of 3*3 matrix. E.g.-
1 2 3
4 5 6
7 8 9
Check if the matrix is symmetric or not.
"""
"""
3. Sorting refers to arranging da... |
1ff75c4685f869eece4ada6af2fb00769e251097 | JudgeVector/Projects | /SOLUTIONS/Text/CountVowels.py | 636 | 4.1875 | 4 | """
Count Vowels - Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
"""
vowels = ['a','e','i','o','u']
vowel_count = [0,0,0,0,0]
def count_vowels(s):
for i in range(0, len(s)):
if s[i] in vowels:
for j in range(0, len(vowels))... |
47d3b0a870d32315963196eef208d39be488c468 | lduran2/dev.array-problems.in-python | /p01B-missing-number-sorted | 5,602 | 4.25 | 4 | #!/usr/bin/env python3
r'''
./p01B-missing-number-sorted
This program finds the missing number in a list of integers. This
implementation is optimized for sorted lists through use of binary
search.
* by: Leomar Duran <https://github.com/lduran2>
* date: 2019-06-28T23:53ZQ
* for: https://dev.to/javinpaul/50-data-struc... |
eeb30e32b2a5b095987e5be0d0249c84328838dc | mwanchap/Oiler | /problem1.py | 561 | 3.765625 | 4 | def getSumOfMultiples(baseNum, count):
the_sum = baseNum
max_value = int(count/baseNum) + 1
for i in range(2, max_value):
the_sum += baseNum * i
return the_sum
def sumDivisibleBy(number, count):
the_max = int(count/number)
return int(number * (the_max * (the_max + 1)) /2)
count = 999... |
73bb14c9e8453d5131fba8c15782a09a23860b28 | glennsvel90/Navy_Weather_Data_Analyzer | /navywDB.py | 8,544 | 3.828125 | 4 | from datetime import date, datetime, timedelta
from tkinter import messagebox
import sqlite3
import NavyWWeb
class NavyWDB():
"""
Create and manages a database that stores local cache of all weather data that's been
downloaded from the internet.
"""
def __init__(self, **kwargs):
""" ope... |
c1235b19604218e998ba053ac1549bc238a1bfe1 | git484/leetcoding | /prime no check.py | 219 | 3.890625 | 4 | y=int(input("enter a no\n"))
flag=1
for x in range(2, y, +1):
if y%x == 0:
print("Not prime")
flag=0
break
if flag==1:
print("It is prime")
|
4241f67d8f7f09470233d34d60cc3da6ae7e80e1 | avner-csumb/python-day4 | /number_game.py | 207 | 3.921875 | 4 | low = int(raw_input('Enter low number: '))
high = int(raw_input('Enter high number: '))
# i = low
# while i <= high:
# print(i)
# i += 1
my_list = range(low, high+1)
for i in my_list:
print(i)
|
ec3e44a582edfa4a939eb1b1f314302dea22c52f | zhangruochi/Book | /FluentPython/chapter2/bisect_module.py | 628 | 3.53125 | 4 | #!/usr/bin/env python3
#info
#-name : zhangruochi
#-email : zrc720@gmail.com
import bisect
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
NEEDLES.reverse()
for num in NEEDLES:
position = bisect.bisect_right(HAYSTACK,num)
print(position... |
34f524b2719d445a465475d2ce564c810ac2badb | cy486/python | /cards_tools.py | 3,757 | 3.734375 | 4 | #记录所有的名片
card_list=[]
def show_menu():
"""显示菜单"""
print("*" * 50)
print("欢迎使用【名片管理系统】V1.0")
print()
print("1. 新增名片")
print("2. 显示全部")
print("3. 查询名片")
print()
print("0. 退出系统")
print("*" * 50)
def new_card():
"""增加名片"""
print("-" * 50)
prin... |
f313f28359bae14970c42448354d98f346640793 | neulab/tranx-study | /analysis/submissions/638965bbb0d66a5b0eae27d1324bbf89_task1-1_1596102935/task1-1/main.py | 557 | 3.625 | 4 | import random
output = {}
# generate random chars and ints and add them to a dictionary
for i in range(100):
character = (chr(random.randint(97, 122)))
integer = random.randint(1, 20)
if character in output:
output[character].append(integer)
else:
output[character] = [integer]
# sort ... |
1526c3057de6507187e3cc2f50f9d04e1c9b6df4 | neulab/tranx-study | /analysis/submissions/34b1ef17e6625ba2350f6f1c169591a1_task2-1_1595488334/task2-1/main_patch.py | 320 | 3.609375 | 4 | # Example code, write your program here
import pandas as pd
import os
os.mkdir("output")
df = pd.read_csv('data.csv')
# If you know the name of the column skip this
first_col = df.columns[0]
last_col = df.columns[-1]
# Delete first
df = df.drop([first_col, last_col], axis=1)
df.to_csv('output/output.csv', index=False) |
68473ef8a02dcf900cb061acbc7e1c852fbea181 | neulab/tranx-study | /analysis/submissions/9dd43727b9246d7f2220b94ff43380cf_task1-1_1596138232/task1-1/main.py | 684 | 3.796875 | 4 | # Example code, write your program here
import string
import random
from collections import defaultdict
dict = defaultdict(list)
def random_char():
letter = string.ascii_lowercase
result = ''.join(random.choice(letter))
return result
for i in range (1, 100):
tempkey = random_char()
tempval = rand... |
0b3d42404a595e14ccf1a8089805f1f7e28401df | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task7-2_1591994712/task7-2/main.py | 1,184 | 3.71875 | 4 | # Example code, write your program here
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def main():
df = pd.read_csv("StudentsPerformance.csv")
grouped = df.groupby(['gender', 'race/ethnicity'])
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
bar_width = 0.35
for... |
2827ba2ce9df9c1e4174af53375b04a56f1b8981 | neulab/tranx-study | /analysis/submissions/27570bb3cfcc304aeede0cdf6c2e2762_task2-1_1600789334/task2-1/main.py | 472 | 3.640625 | 4 | # Example code, write your program here
import csv
import pandas as pd
#reader = csv.reader(open('data.csv', 'rb'))
with open("data.csv", 'r') as reader,open("output.csv", 'w') as outFile:
out = csv.writer(outFile,delimiter=',',quotechar='"')
for row in reader:
col = row.split(',')
if len(col) >... |
0e4617ecbba8d6579b53c98087b96364e5dc6e83 | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task1-1_1591986411/task1-1/main.py | 463 | 3.640625 | 4 | # Example code, write your program here
import random
import string
from collections import defaultdict
def main():
letters = [random.choice(string.ascii_lowercase) for _ in range(100)]
numbers = [random.randint(1, 20) for _ in range(100)]
d = defaultdict(list)
for c, x in zip(letters, numbers):
... |
44e9c95706879ed95d2dc9f2f4206dcfff1ac3d2 | neulab/tranx-study | /analysis/submissions/10fb8132405b6c443addb06bc941f9e3_task1-1_1597089229/task1-1/main.py | 633 | 3.703125 | 4 | # Example code, write your program here
import string
import random
num = []
num_paired = []
mydict = {}
letter = string.ascii_lowercase
res = ''.join(random.choice(letter) for i in range(100))
#print(res)
for i in range(100):
num.append(random.randint(1, 20))
#print(num)
for i in range(100):
for j in range(1... |
6657bda6817d3be50fabbe73148becf243bee6f3 | neulab/tranx-study | /analysis/submissions/0bd31633162f7a836160dd5b6359d29b_task2-1_1601661947/task2-1/main_patch.py | 188 | 3.640625 | 4 | import pandas as pd
columns_needed = ["first_name","last_name","email","gender"]
df = pd.read_csv('data.csv', usecols = columns_needed)
df.to_csv(r'example_output/output.csv')
print(df) |
f945785dd904c59d4723a7ed0db600d45e180b54 | kju2/euler | /problem067.py | 1,013 | 3.75 | 4 | """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt, a 15K text file
containing a triangle with one-hundred rows.
NOTE:... |
9b3661b407e31b15525d7caa1f956252a28a9d99 | kju2/euler | /problem047.py | 1,265 | 3.703125 | 4 | """
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 * 7
15 = 3 * 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2^2 * 7 * 23
645 = 3 * 5 * 43
646 = 2 * 17 * 19.
Find the first four consecutive integers to have four distinct primes factors.
What... |
15090f3167cc207f0cf64acb0b3c84e27bbf85c4 | kju2/euler | /problem304.py | 1,494 | 3.515625 | 4 | """
http://projecteuler.net/problem=304
"""
def fib(nth):
"""fib returns the nth fibonacci number."""
fib_matrix = [[1, 1], [1, 0]]
if nth == 0:
return 0
power(fib_matrix, nth - 1)
return fib_matrix[0][0]
def power(matrix, exponent):
"""power computes the power to a given matrix."""
... |
53cf3eed32f2c405ee56e4b433e3180bc1aa1d77 | kju2/euler | /problem033.py | 1,362 | 4.15625 | 4 | """
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in
attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is
correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples ... |
b0d32f2891d07fb5f8e5ae9e803d549f68d30e51 | kju2/euler | /problem005.py | 1,244 | 4.0625 | 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?
"""
def main():
"""
divisible by 2 if step is 2
divisible by 3 if step is 3*2
divisible by... |
62c31161a0a2b0b85a00071db97210d1d3892454 | HarshVikram/learning-python | /Python Syntax/if_else.py | 287 | 4.09375 | 4 | size = input('Enter the size of shirt: ')
value = int(size)
if value == 40:
print(' is S')
elif value == 42:
print(size + ' is M')
elif value == 44:
print(size + ' is L')
elif value > 44:
print('Size is not available')
else:
print('We would have to place a custom order')
|
79a2518aa79292f1ddffd39a3f3b78f0d7e07e0e | Kuomenghsin/my-learning-note | /HW2/heap_sort_ 06111306.py | 1,400 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
class Solution():
def heap_sort(self, nums):
self.nums = nums
self.heapSort(nums)
return nums
def toHeap(self,arr, n, i): #堆積size = n
bigest = i # 子樹根初始值 index = i
L = 2*i + 1 # (左子節點) = 2*i + 1 由左子數計算樹根位址i... |
f334ed11c9801ead3700cc0fa687ff7a81353643 | kn0709/python | /gu_nu.py | 762 | 3.796875 | 4 | import random
def number_game(in_val):
number_range = [x for x in range(1,101)]
rand_num = random.choice(number_range)
if int(in_val) == rand_num:
print("Amazing how did this happen")
else:
diff_num = int(in_val) - rand_num
if diff_num < 0:
print("You are just {} behind".format(diff_num * -1))
print("I ... |
a3940af34ce7d808facbdb0ac67cdbbd17d50a23 | xxrom/617_merge_two_binary_trees | /main.py | 2,534 | 4.125 | 4 | # Definition for a binary tree node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.__dict__)
class Solution:
# print all values
def printAll(self, root):
if root... |
f1773013a4d82b0d140d882e87e25dd3a6205bc8 | isaaczinda/route-planner | /tools/Geometry.py | 3,274 | 3.75 | 4 | import math
import numpy as np
def DifferenceBetweenDegrees(One, Two):
Difference = abs(One - Two)
if Difference <= 180:
return Difference
else:
return abs(Difference - 360)
# always returns an angle less than pi radians
def AngleBetweenLines(LineOne, LineTwo):
LengthOne = np.linalg.norm... |
2d3924eabaa80591b15c9b3530ca10b1aa0b20d7 | adityaramkumar/LeetCode | /144.py | 416 | 3.65625 | 4 | # Runtime: 44 ms, faster than 37.20% of Python3 online submissions for Binary Tree Preorder Traversal.
# Difficulty: Medium
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return [ro... |
e7b383915b973dac1dd462df936a45c53e5b8c46 | adityaramkumar/LeetCode | /125.py | 452 | 3.828125 | 4 | # Runtime: 80 ms, faster than 42.27% of Python3 online submissions for Valid Palindrome.
# Difficulty: Easy
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = self.clean_string(s)
return s == s[::-1]
def clean_string(self, s... |
1d8e332c138f58671e4d84d1fd1bd138e1be260c | adityaramkumar/LeetCode | /589.py | 428 | 3.59375 | 4 | # Runtime: 124 ms, faster than 56.96% of Python online submissions for N-ary Tree Preorder Traversal.
# Difficulty: Easy
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
p_list = [root.val... |
3146090c54d237ba2d17d20780f447a5610a722d | adityaramkumar/LeetCode | /58.py | 298 | 3.71875 | 4 | # Runtime: 20 ms, faster than 99.23% of Python online submissions for Length of Last Word.
# Difficulty: Easy
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split()[-1]) if len(s.split()) > 0 else 0
|
fcb2d0b0cced1ec811c4f97be08ba07bc47453d4 | yuvraj1987/Acadgild_Assignment_2- | /.gitignore/Assignment2_list_Comphersion_nested_list.py | 984 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 16:27:42 2018
@author: jkdadhich
"""
Text = "acadgild"
Result = [x.upper() for x in Text] # Using Uppercase and iterate over character
Variable = "xyz"
# Mulitpy iteration with range
Result_1 = [ x*k for x in Variable for k in range(1,5)]
# mulitpl... |
4a17f972b166a9366ef4445409b707659fb8843f | abhineetmishra64/Algorithm | /python/sumevenfibo.py | 275 | 3.578125 | 4 | def evenfibo(limit):
if(limit<2):
return 0
ef1=0
ef2=2
sm=ef1+ef2
while(ef2<=limit):
ef3=4*ef2+ef1
if(ef3>limit):
break
ef1=ef2
ef2=ef3
sm=sm+ef2
return sm
limit=9
print(evenfibo(limit))
|
dc3416bc1ecc7f1546818662d475aa2fd7245194 | abhineetmishra64/Algorithm | /python/exam.py | 359 | 3.734375 | 4 | n=int(input("Enter no. of student: "))
std={}
for i in range(n):
info={}
info['name']=input("Enter name: ")
info['age']=int(input("Enter age: "))
info['marks']=int(input("Enter marks: "))
std[i]=info
print(std)
marks=[]
for i in range(n):
marks.append(std[i]['marks'])
print(sum(marks)/n)
ind=m... |
102b3bd3f57932ce61c8eb3cacafb406d15929cd | to-besomeone/algorithm | /181009 - 2562.py | 197 | 3.734375 | 4 | arr = []
for i in range(9):
arr.append(int(input()))
maxValue = arr[0]
j = 0
for i in range(1, 9):
if arr[i] > maxValue :
maxValue = arr[i]
j = i
print(maxValue)
print(j+1) |
91c8697f3842b6adaf0481038f666f8c510d63a6 | to-besomeone/algorithm | /181111-2750_1.py | 314 | 3.59375 | 4 | N = int(input())
mat = [int(input()) for _ in range(N)]
for i in range(N-1, -1, -1): # for i in range(N-1):
for j in range(i): # for j in range(N-1):
if mat[j] > mat[j+1]:
tmp = mat[j]
mat[j] = mat[j+1]
mat[j+1] = tmp
for i in range(N):
print(mat[i]) |
5e6676fe294341190b98333567d7242eebb063a8 | pmillerschmidt/lockers | /https/docs.google.com/document/d/1puiqxz9kzwaWOi65MAb_kQtessXq86-zM4ITiX1Pd3k/lockers.py | 958 | 3.921875 | 4 | import random
from time import sleep
right = 0
i = 0
print("How many lockers and students are there?")
total_lockers = int(raw_input())
print("Cool! There are %d lockers and students" % total_lockers)
print("--------------")
sleep(1)
print("How many time do you want the program to run")
input = int(raw_input())
runs ... |
01c994d42749b26d6a32de3a6682a60f38ccc4eb | quantabox/hackerrank | /10-days-of-statistics/poisson_distribution_ii.py | 810 | 3.796875 | 4 | #!/usr/bin/env python
# Approach I
def fact(y):
if y <= 1:
return 1
return y*(fact(y-1))
poisson_random_variables = [float(x) for x in input().split()]
e = 2.71828
l_A = poisson_random_variables[0] # Machine A repair poisson random variable mean variance
l_B = poisson_random_variables[1] # Machine B r... |
2d425e371bd59c5a0ad3e6807a239378c5e44a12 | jiaoqiyuan/Tests | /Python/python-practice/chapter5-if/toppints.py | 1,428 | 4.25 | 4 | requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperon... |
45246247635523f9d8a41c9402effce330e9c013 | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/animals.py | 180 | 3.984375 | 4 | animals = ['pig', 'chiken', 'tigger', 'bird', 'bull']
for animal in animals:
print("A dog would make a great pet " + animal)
print("Any of these animals would make a great pet!") |
1e3897dc264c6e7927e677227e6389f05dc7e062 | jiaoqiyuan/Tests | /Python/python-practice/chapter7-while/trival.py | 306 | 4.09375 | 4 | places = []
flag = True
while flag:
place = input("\nIf you could visit some places in the world, where would you go?\nEnter 'quit' to exit!")
if place == 'quit':
flag = False
else:
places.append(place)
print("\nYour places are: ")
for place in places:
print("\n" + place)
|
4be74b37275fdd68dac3287633b5001a4c6b357b | jiaoqiyuan/Tests | /Python/python-practice/chapter4-uselist/pisas.py | 458 | 4.0625 | 4 | pizzas = ['New-York-Style', 'Chicago-Style', 'California-Style', 'Pan-Pizza']
for pizza in pizzas:
print("I like pepperoni pizza " + pizza)
print("I like pizza very much, I really love pizza!")
friend_pizzas = pizzas[:]
pizzas.append('Take and Bake Style')
friend_pizzas.append('Stufffed')
print("My favorite pizza a... |
59d7d9ba327ce1f559135bf000f5acb986578733 | Harishjm/Basic_Python | /Beark_Continue.py | 116 | 3.96875 | 4 | for i in range(0,9):
if(i%2==0):
continue ###break ###this is for printing odd numbersss
print(i) |
fef2bea17ffb60458cf22821fc4503494914b2ea | esselstyn/Homework_1 | /prime.Factor.py | 690 | 3.671875 | 4 | #!/usr/bin/env python
max = int(raw_input('Select the maximum value: '))
max = max + 1
#Make a list of all prime numbers between 1 and max
primes = []
for i in range(1, max):
x = 0
if i < 4:
primes.append(i)
else:
for j in range(2, i-1):
if i % j == 0:
x = 1
if x == 0:
primes.append(i)
##reduce th... |
4b65bba88943870e3121c6009e78563b8109ae5a | nagase2/nagaden | /module/CalcUtil.py | 960 | 3.546875 | 4 |
import datetime
def checkIfPastSpecificTimeInSec(lastTime, currentTime ,pastTimeInSec):
"""前に通知した時間よりも5分(5*60)以上たっているか判定する"""
#lastNotifiedTime =datetime.datetime(2017, 12, 28, 22, 5, 6, 620836)
#currentTime=datetime.datetime.now()
diff = currentTime-lastTime
print(diff.seconds)
if diff... |
48fc03d448664155dcc7edad585aea16e730618b | R0bertWell/estrutura-de-dados | /aula_01/meu_max.py | 663 | 3.78125 | 4 | from math import inf
from time import time
def meu_max(iteravel):
"""
Análise do algorítmo
Tempo de execução, algoritmo O(n)
Em memória O(1)
:param iteravel:
:return:
"""
max_num = -inf
for i in [1, 2, 3, 4, 5, 6]:
if i > max_num:
max_num = i
return max_num
... |
971f92ebcde170ea9c198e1e5aba3b881427113b | shred2042/Forward-Space-Search | /FWD_Space_Search.py | 9,182 | 3.71875 | 4 | # returns true if the smaller set is included in the bigger set
def included(smaller, bigger):
for x in smaller:
if not x in bigger:
return False
return True
#taken from the lab
def NOT(P):
return "NOT_" + P
#main function
def makePlan(problemData):
problem = processInput(problemDa... |
2a74b2bc17b8407ee6bdf8b060e89ce4d59bfe28 | collinskibetkenduiwa/UrlshortenerinPython | /ulshorner.py | 627 | 3.5625 | 4 | import pyperclip,pyshorteners
from tkinter import *
root=Tk()
root.geometry("400*200")
root.title("URL SHORENER")
def urlshortener():
urladdress=url.get()
url_short=pyshorteners.Shortener().tinyurl.short(urladdress)url_address.set(url_short)
def copyurl():
url_short=url
pyperclip.copy(url_short)
La... |
248a5e497ca60c6f26a4a5958e537d5d06cc44f5 | steveding1/CS-1 | /task2.2-exer5.py | 403 | 4.03125 | 4 | #CS-1 Task 2.2 - Exercise 5 from Steve Ding
looping = True
while looping:
try:
celsius = float(input('\nEnter the Celsius temperature: '))
print ('Fahrenheit temperature is: ', (celsius*9/5+32))
ans1 = input('\ncontinue? y/n\n')
if ans1.upper() in ("NO", "N"):
loo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.