blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
bdcf738bc2d40c5d881714995eda8f532cab49a9 | randolphwong/libdw | /libdw/colors.py | 3,393 | 3.953125 | 4 | """
Utility procedures for manipulating colors
"""
from math import log, floor
import util
# h in [0, 360]
# s in [0, 1]
# v in [0, 1]
# returns values in [0,1]
def HSVtoRGB(h, s, v):
"""
Convert a color represented in hue, saturation, value space into
RGB space.
:param h: hue, in range (0, 360)
... |
fea35d9e1b68cfed9b91e7cd123ef773870a7967 | randolphwong/libdw | /libdw/boundarySM.py | 4,128 | 3.8125 | 4 | """
Very simple behavior for following the boundary of an obstacle in the
world, with the robot's 'right hand' on the wall.
"""
import sm
from soar.io import io
######################################################################
# Global Variables
#################################################################... |
4f8fad4f5a4995f4bd1c53f78d58a3485790ab8d | katatanziH/vscode_test | /add_naturalnumbers.py | 352 | 4.0625 | 4 | import math
import os
import random
# Sum of natural numbers up to num
name = input("Your Name! ")
print("Hello !", name, "Solve this problem")
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while num > 0:
sum += num
num -= ... |
ce110be374e105cbea1b7ae6befb50d7b034e457 | walebash/Practice | /nameGenerator.py | 1,392 | 4.21875 | 4 | import random
import string
def name_generator(letters):
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 'y', 'v', 'w', 'x', 'y', 'z']
v = []
c = []
names = []
for letter in letters:
if l... |
480eade3527b22fbba59888e7294c18da54f2c39 | KanyshaiT/CSPython | /Lambda.py | 120 | 3.765625 | 4 | '''result= lambda x: x*x
print(result(5))
'''
numbers = [1,3,6]
newN= tuple(map(lambda x:x, numbers))
print(newN)
|
bf67f41ce09cc366ce379e8c61114c86771c3f4c | KanyshaiT/CSPython | /sum_of_multiples_of_3.py | 553 | 3.9375 | 4 | '''total=0
for i in range(1,9):
if i%3 == 0:
total +=i
print(total)
'''
#sum of multiples of 3 and 5 less that 100
'''total=0
for i in range(1,100):
if i % 3 ==0 or i % 5 == 0:
total +=i
print(total)'''
#typing once, twice ...
'''list=["hi", 'my', 'is', 'Stitch']
for i in r... |
6b27e5d8ff451f017a504050e8d0c5e4640c68e4 | JuanCarlos-A01376511/Mision_08 | /Misión_08.py | 3,653 | 3.734375 | 4 | # Autor: Juan Carlos Flores García A01376511. Grupo 02.
# Programa que realiza operaciones usando cadenas.
# Función que recibe una cadena y luego regresa otra cadena con las mayúsculas y minúsculas combinadas.
def combinarLetras(cadena):
contarLetras = 1
acumularLetras = ""
for n in cadena:
... |
8f4f38713dc22b2f63d3f321c1183c5f066738c7 | rakaadli/latihanraka | /0.py | 1,348 | 3.671875 | 4 | print('Selamat datang')
print('Silahkan pilih program yang akan Anda mau :')
print(' (1) KODE MORSE')
print(' (2) IDR USD BITCOIN')
print(' (3) CUACA')
print(' (4) Pemain Bola')
try:
pilihanprogram = int(input('Input program yang kamu mau (1/2/3): '))
except ValueError:
print('coba lagi pakai angka')
except Na... |
572958225a475b6e9d2e3e5aca6ef126beefea12 | Athenian-ComputerScience-Fall2020/project-1-mishikag | /my_code.py | 4,722 | 4.0625 | 4 | # Collaborators (including web sites where you got help: (enter none if you didn't need help)
# shanie lee
#introduction to the game
import random
def introduction():
intro = input("Are you ready to play the game? ")
#this trys for bad user input
def fun():
global category
category=int(input("please select ... |
eac24a8d832a9ccfba0950e29a47ec4c99b1e9ea | jinook929/leetcode-interview | /Bloomberg/candy-crush-1d.py | 4,665 | 3.875 | 4 | def candy_crush(s): # ABCCCCCBBAACDDDCCC -> C
checkAgain = True # set flag true to begin first check
while checkAgain: # repeat checking till no string update
checkAgain = False # set default flag not to repeat
counter = 0 # set same letter counter
left = 0 # set 2 pointers for letter co... |
3295b676d8ea6c51c5e9ff5909aa62a86e14675a | jinook929/leetcode-interview | /easy/array/rotate-image.py | 439 | 3.84375 | 4 | def rotate(matrix):
result = [[0 for _ in matrix[0]] for _ in matrix]
last_column = len(matrix) - 1
for row in matrix:
for i in range(len(matrix)):
result[i][last_column] = row[i]
last_column -= 1
for i in range(len(result)):
matrix[i] = result[i]
retur... |
975362f25d383cc9dcee9bd9b9b092fd45643757 | blueyonder1234/Sickle_and_kite_music | /main.py | 708 | 3.578125 | 4 | import pygame
import RPi.GPIO as gpio
MUSIC_FILE = "./Anthem_of_the_Soviet_Union.mp3"
gpio.setmode(gpio.BCM)
gpio.setup(2, gpio.IN)
def main():
previous_state = gpio.HIGH
while True:
if gpio.input(2) == gpio.LOW and previous_state != gpio.LOW:
print("ソビエトロシアでは、プログラムがあなたを実行する!!")
... |
6c57bc9f1df34db1b013cedd027ae3f0028ae067 | Abraham1314/my_study_python | /python/测试/text3.py | 363 | 3.734375 | 4 | a=eval(input("请输入你想判断的数据a:"))
b=eval(input("请输入你想判断的数据b:"))
c=eval(input("请输入你想判断的数据c:"))
d=eval(input("请输入你想判断的数据d:"))
print("a的类型为{}".format(type(a)))
print("b的类型为{}".format(type(b)))
print("c的类型为{}".format(type(c)))
print("d的类型为{}".format(type(d))) |
d16bd1dd16fa2d0d320a25cc8739be99c3c86ca4 | lz023231/CX.PY | /爬虫/爬虫/1、urllib爬取网页.py | 1,116 | 3.578125 | 4 | import urllib.request
url = "http://www.baidu.com"
#向指定的URL地址发起请求,并返回服务器响应的数据(文件的对象)
response = urllib.request.urlopen("http://www.baidu.com")
#读取文件的全部内容,会把读取到的数据赋值给一个字符串变量
data = response.read().decode("utf-8")
print(data)
#将爬取到的网页写入文件
#with open(r"E:\CX.PY\爬虫\file\file1.html","wb") as f :
#f.write(data)
#读... |
572a696783a6ca1c084a7e49d3cee7b4374bca2a | lz023231/CX.PY | /tkinter/23、相对布局.py | 416 | 3.609375 | 4 | import tkinter
win = tkinter.Tk()
win.title("雷哥")
win.geometry("400x400+200+20")
label1 = tkinter.Label(win,text="good",bg="blue")
label2 = tkinter.Label(win,text="nice",bg="red")
label3 = tkinter.Label(win,text="cool",bg="pink")
#相对布局窗体改变对控件有影响
label1.pack(fill=tkinter.Y,side=tkinter.LEFT)
label2.pack(fill=tkinter.X... |
2119fa5f8557ace83d4b4b1c8efddf7f050fff86 | lz023231/CX.PY | /控制窗体、内存、异常、语音/异常处理.py | 1,799 | 4.15625 | 4 |
'''
'''
#当程序遇到问题是不让程序结束,而略过错误继续向下执行
'''
try……except……else
格式:
try:
语句t
except 错误码 as e:
语句1
except 错误码 as e:
语句1
……
except 错误码 as e:
语句n
else:
语句e
注意:else可有可无
作用:用来检测try语句块中的错误,从而让except补货错误信息并处理
逻辑:当程序执行到try~expect~else语句时
1、如果当try“语句t”出现错误,会匹配第一个错误码,如果匹配上就执行对应的语句
2、如果当try“语句t”出现错误,没有匹配的异常,... |
43d82445ab2275ad6f3b5076664829cd1e1dae73 | lz023231/CX.PY | /爬虫/爬虫/6、GET请求.py | 266 | 3.703125 | 4 | '''
特点:把数据拼接到请求路径的后面船体给服务器
优点:速度快
缺点:承载的数据量小,不安全
'''
import urllib.request
url = ""
response = urllib.request.urlopen(url)
data = response.read().decode("utf-8")
print(data)
|
d75bf8a2416e8b462ed47bd485dca98ea7df8412 | lz023231/CX.PY | /tkinter/25、鼠标点击事件.py | 641 | 3.609375 | 4 | import tkinter
win = tkinter.Tk()
win.title("雷哥")
win.geometry("400x400+200+20")
#<Button-1>鼠标左键
#<Button-2>鼠标中键
#<Button-3>鼠标右键
#<Double-Button-1>鼠标左键双击
#<Double-Button-2>鼠标中键双击
#<Double-Button-3>鼠标右键双击
#<Triple-Button-1>鼠标左键三击
#<Triple-Button-2>鼠标中键三击
#<Triple-Button-3>鼠标右键三击
def func(event):
print(event.x, even... |
5c36b47de38425bf90e47c7348b525a35c173305 | annewoosam/shopping-list | /shoppinglist.py | 628 | 4.21875 | 4 | print("create a quick, no duplicate, alphabetical shopping list by entering items then hitting enter when done.")
shopping_list=[]
while True:
add_item=input("add item>")
if add_item.lower()!="":
shopping_list.append(add_item.lower())
shopping_list=set(shopping_list)
print( "\no... |
5601f569fd945a6ff7582949a953488644152193 | 10sr/junks | /python/tokenize_try/a.py | 157 | 3.546875 | 4 | #!/usr/bin/env python3
def f1(a: int) -> int:
v = a
for i in range(3):
v = v + i
return v
if __name__ == "__main__":
print(f1(4))
|
40c120f9525397f0f1b5e02bb588ce37a5cd5e34 | itsme-dazainaki/Praktikum-Protek-05 | /Praktikum-Protek-05/Latihan 1/latihan04.py | 1,216 | 3.734375 | 4 | #mari menginput, variabel beserta type dan inputannya
kode = int(input("Masukkan Kode Karyawan : "))
nama = str(input("Masukkan Nama Karyawan : "))
gol = str(input("Golongan ( A, B, C, D) : "))
#ini untuk mengecek besarnya gaji berdasarkan inputan gol
if(gol == "A"):
gaji = 10000000
potongan = 2.5
... |
e938d73ff9fa31b8f33290cb42beba1033ba5c3d | Majorparadox/Challenges | /ASchallenges/12.py | 1,068 | 3.828125 | 4 | print("1 \n")
import calendar
cal = calendar.TextCalendar() # Create an instance
cal.pryear(2012)
#b
#c
mon = calendar.TextCalendar()
mon.prmonth(2019, 1)
#d
d = calendar.LocaleTextCalendar(6, "SPANISH")
d.pryear(2012)
#e returns True or False depending on if the year is a leap year
print("2 \n")
#a 49
#b re... |
642bde03f973af2c1fb234b575b4cef2d5d5d144 | AeroEngDev/TeachManger | /src/DB_con.py | 5,131 | 3.671875 | 4 | import sqlite3
import pdb
class DB_con:
def __init__(self, db_name):
try:
self.conn = sqlite3.connect(db_name)
self.c = self.conn.cursor()
except:
pass
def __del__(self):
self.conn.close()
def CreateStudentsTable(self):
... |
32c199d5cb130b0e25339698463ece8ec86ba467 | zuldijin/Algorithm-excercises | /binaryTree/branch.py | 1,665 | 3.5625 | 4 | '''
Created on Nov 6, 2017
@author: ricardo.villa.berger
'''
class branch(object):
def __init__(self, value):
self.value = value
self.right_leaf = None
self.left_leaf = None
@staticmethod
def spacesForValue(value):
sapce_number=5
if (value=="Ha... |
39e1769d54ed116972b3927f26401c73bcaa5f57 | osnryo/Python006-006 | /week06/zoo.py | 223 | 3.90625 | 4 | class Zoo(object):
def __init__(self, name):
# 普通字段
self.name = name
def add_animal(self, name):
if name not in self.name:
print('没有同名动物,可添加动物')
|
f6af82e5c2fb393a3b0d436813af2c30dd7d7b2b | jdd1260/pinochle-meld-simulation | /deck.py | 773 | 3.6875 | 4 | import random
import config as config
#A class to represent a Card deck. Functions: Shuffle, deal
class Deck:
#Create a deck based on deck configuration
def __init__(self):
self.cards = [ value+suit for value in config.values for suit in config.suits ]
self.cards *= config.occurrences
... |
e7bbb724c2fca4d5aa47abe1a1a3393e6455b891 | klAndersen/scikit-learn_tutorials | /Cross validation/cross_validation.py | 4,763 | 3.78125 | 4 | """
Based on:
http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation
Learning the parameters of a prediction function and testing it on the same data is a methodological mistake:
a model that would just repeat the labels of the samples that it has just seen would have a perfect score but
would ... |
80578567b85312a5a73d8aeba550e8b8975f3145 | eishkumar/dumypro | /var.py | 157 | 3.578125 | 4 | #a=('eish','ravi')
#
def name(*name):
#l=len(name)
for i in range(0,2):
print('hello',name[i])
#print(name[1])
#print(type(name))
name('eish','ravi')
|
1a6e14c40cd0a1dc304727ebf0d92c20d87974a2 | eishkumar/dumypro | /pat.py | 257 | 3.71875 | 4 | for i in range (1,4):
for j in range (1,6):
if(j%2 != 0):
print(''.join(map(str, '__')))
else:
print(''.join(map(str, '|')))
'''a=['__','|','__','|','__']
for i in range(0,4):
#if i==3 and a== '__':
# break
print(''.join(map(str, a[i])))'''
|
cf21b4516576c1d6cddd3679f517bf5daaee6498 | eishkumar/dumypro | /dic.py | 136 | 3.65625 | 4 | a={1:'he','nu':'hehe'}
print(a[1],a['nu'])
print(a.values())
print(a.keys())
a=['key1','key2','key3']
dic=dict.fromkeys(a,10)
print(dic) |
70003d324097aa9917befa2c2d37264edd1a3817 | eishkumar/dumypro | /funt.py | 104 | 3.78125 | 4 | l=['mi','sony','samsung']
def find(a,b):
for i in l:
print('the size of 'a[i],'is',i)
find(a='mi') |
7c1b8dd77fd8a30d9f595418a78e646b0bcae664 | jrs33/Cracking_Coding | /ch10_sortingAndSearching/sortedMerge.py | 361 | 3.828125 | 4 | def sortedMerge(arrayA, arrayB):
endA = len(arrayA) - 1
endB = len(arrayB) - 1
endMerge = len(arrayA) + len(arrayB) - 1
while(endB >= 0):
if(arrayA[endA] > arrayB[endB]):
arrayA[endMerge] = arrayA[endA]
endA -= 1
elif(arrayA[endA] < arrayB[endB]):
arrayA[endMerge] = arrayB[endB]
endB -= 1
endMer... |
3aaf7b5e894011350dd6577e66ea070c9aada1d2 | jrs33/Cracking_Coding | /ch5_bitManip/flipBit.py | 1,034 | 3.59375 | 4 | #
# With a given integer, flip a bit from 0 to a 1, and find longest sequence of 1's
#
def flipBitToWin(inputNum):
binaryString = bin(inputNum)
bitArr = [int(char) for char in binaryString[2::]]
preCount = 0
postCount = 0
best = 0
for bit in bitArr:
# Haven't encountered a zero yet
if(bit == 1 and postC... |
cc10d6a496a8f20dc3ff8cb3783b26537674000a | jrs33/Cracking_Coding | /stringNum.py | 878 | 3.546875 | 4 | mapDict = {'A': 1, 'B': 13, 'C': 110}
def stringNum(inputString,mapDict):
arr = list(inputString)
runningSum = 0
runningSubtraction = 0
currentValue = 0
for index,char in enumerate(arr):
print(runningSum)
print(runningSubtraction)
if index == 0:
runningSum += mapDict[arr[index]]
runningSubtraction -... |
13d7712e86acb4b5c9a48e2bc1c268a4601f09b9 | dileepchebolu/python | /Examples/12.While_lopp.py | 389 | 3.734375 | 4 | i = 1
while i <= 10:
print(i)
#i = i + 1 ## Will perform as like below
i += 1
print("Done with the loop")
'''
## The code written in between three single quotes, wont execute
print("checking wether 3 quote block is working or not")
'''
# =============================
# Output:
# 1
# 2
# 3
# 4
# 5
# 6... |
6f0dff4928f496b98b3ece7198045006eeaa3d4f | dileepchebolu/python | /Examples/6.Functions.py | 897 | 3.734375 | 4 | def sayhi(): ## def is equal to function in bash scripting
print("hello World !!")
print("Top")
sayhi() ## calling the function
print("Bottom")
# Output:
# Top
# hello World !!
# Bottom
# In bash scripting:
# xyz23 ()
# {
# echo "$FUNCNAME now executing." # xyz23 now executing.... |
fbf139ec9e786160fa1f41fa1b03acff826b4ea5 | dileepchebolu/python | /Examples/5.Tuples.py | 351 | 4.09375 | 4 | ## Difference between tuples and lists : In tuples, we cannot modify the list. as in lists, we can modify, update and delete the list values
list_values = ("dileep", "surya", "nagendra", "kumar")
print(list_values[0])
print(list_values)
## In tuples, if you want to modify a tuple, need to create a new tup... |
70f5dee094dada10999ae09191ca142a02b96d88 | dileepchebolu/python | /Hackerrank/23.py | 1,474 | 4.03125 | 4 | #!/bin/python3
import sys
def bubbleswap(array):
n = len(array)
swaps = 0
for i in range(n):
num_swaps = 0
for j in range(n-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
num_swaps += 1
if num... |
6b6935c09fca77e3229e680307514fcfe4ae2787 | dileepchebolu/python | /scripts/10.Advanced_Iteration_with_List_Comprehensions.py | 1,223 | 3.953125 | 4 | import argparse
parser = argparse.ArgumentParser(description="Searching for words including partial word")
parser.add_argument("snippet", help = "Partial ot complete string to search for in words")
args = parser.parse_args()
snippet = args.snippet.lower()
with open("scripts/sample.txt") as f:
words = f.readline... |
e4ba4d901bfb8188edeff3c5050b6cf890f0e179 | dileepchebolu/python | /Examples/21.Writing_files.py | 632 | 3.90625 | 4 | employee_file = open("Examples/employee_file.txt", "a")
print(employee_file.writable()) ## Will check wether we able to write the file or not. and the output is like boolean value.
employee_file.write("\nhari - Systems engineer") ## it will append this content to the last line in the file. if you want to add this... |
987650133ed8611b645aef9a6c2ef0fef97dc2be | tasnia18/Python-assignment-certified-course-in-Coursera- | /Python Data Structure/7_2.py | 954 | 4.125 | 4 | """ 7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
and produce an output as shown ... |
e08d6bc55c75701dba3f0522d3591984a73506c6 | plumbobgit/inClassActivityCalcUnit | /test-calc.py | 810 | 3.609375 | 4 | import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(2, 2), 4)
self.assertEqual(calc.add(-2, 2), 0)
self.assertEqual(calc.add(-2, -2), -4)
def test_subtract(self):
self.assertEqual(calc.subtract(2, 2), 0)
self.as... |
33791e76660c95af96ae04c7b45fd8b1bcfb5646 | snowd25/pyPract | /stringPermutation.py | 611 | 4.25 | 4 | #Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
#without using permutations builtin
def permuteStr(lst,l,r):
if l == r:
print("".join(lst))
else:
for i in range(l,r+1):
lst[l],lst[i] =lst[i],lst[l]
permuteStr(lst,l+1,r)
lst[l],lst[i] =lst[i],lst[l]
# permuta... |
e550d4da51c78a3a21870197c4939d3b49d4b8b5 | husanpy/codewars_husanpy | /persistent_bugger.py | 430 | 3.71875 | 4 | def persistence(n):
"""takes in a positive parameter n and returns its multiplicative persistence,
which is the number of times you must multiply the digits in num until
you reach a single digit"""
count_frames = 1
if n < 10:
return 0
multiplier = 1
while n > 0:
last_d... |
8055ab06a40f4154bfc781d134903525acc70392 | rscinto/WeatherStation | /lightTest.py | 527 | 3.59375 | 4 | import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
redLED = 20
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Use physical pin numbering
GPIO.setup(redLED, GPIO.OUT) # Set pin 8 to be an output pin and se... |
c477d3040b7333e98b87d4fdb940f08b2f62fe0e | RishabGoel/Keras_CNNs | /resnet.py | 4,800 | 3.5 | 4 | import keras
from keras.layers import Dense, Flatten, Activation, Input, Concatenate
from keras.layers import Conv2D, MaxPooling2D, LeakyReLU,Dropout
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.datasets import mnist
import numpy as np
class AccuracyHistory(keras.... |
b299c50e3fa26dbf0c1f7dab579813670ec6dea1 | moonlimb/tree_problems | /isBST.py | 383 | 4.1875 | 4 | from Node import Node
def is_BST(node):
"""returns True if a given node is a root node of a binary search tree"""
if node.is_leaf():
return True
else:
# Node class contains comparison methods
if (node.left and node.left >= node) or (node.right and node >= node.right):
re... |
29176f5531b8772f370f5a99ba7d441538fa2739 | khentatiana/Stepik_Automation_Selenium_Python | /Stepik_Auto_QA/3.2_step07_Составные сообщения об ошибках.py | 560 | 3.546875 | 4 | print("Let's count together: {}, then goes {}, and then {}".format("one", "two", "three"))
str1 = "five"
str2 = "six"
str3 = "seven"
print(f"Let's count together: {str1}, then goes {str2}, and then {str3}")
actual_result = "abrakadabra"
print(f"Wrong text, got {actual_result}, something wrong")
print(f"{2 + 3}")
ca... |
77071ab4925f8ddf52493a89dca3b875d5159a31 | TarasMaru/DQE_python | /HW#3/Hangman.py | 4,517 | 3.75 | 4 | import functools
from collections import Counter
from re import compile
def char_adviser(subset_inner):
numb_of_attempts: int = 0
loop_count: int = 1
word_most_common_inner: str = subset_inner.most_common(1)[0][0]
times_most_common: int = char_frequency_dict.most_common(1)[0][1]
sum_of_chars = sum... |
fa55513c09b8bd47ee419e9ca3757ecd028efa44 | isaacdolson/pythonHomework | /PyBank/main.py | 2,667 | 3.96875 | 4 | import os
import csv
#read in the file
csvPath = os.path.normpath(os.path.join("budget_data.csv"))
monthsOfData = 0
netProfit = 0
increaseMonth = ""
increaseValue = 0
decreaseMonth = ""
decreaseValue = 0
changes = 0
lastMonth = 0
with open(csvPath, newline='') as csvFile:
csvReader = csv.reader(c... |
aa8919d8ec2ff4d67868163f3d4ae3e924a23767 | moozalex/route_finder | /Graph.py | 981 | 3.65625 | 4 | # Alex Moozhayil
from Node import Node
from Edge import Edge
import heapq
class Graph:
""""This class creates a graph object."""
def __init__(self):
self.node_list = []
self.edge_list = []
self.node_set = set()
self.adjacency_list = {}
self.priority_queue = []
... |
b0a437c99473587da733b60c291ccbc7422569f4 | tomo19993/proj2 | /RegularHexagon.py | 862 | 3.703125 | 4 | from Polygon import Polygon
import math
class RegularHexagon(Polygon):
def __init__(self,left_bottom,base_length,fill_color,outline_color):
points=[left_bottom]
points.append((left_bottom[0],left_bottom[1]))
points.append((left_bottom[0]+0.5*base_length,left_bottom[1]+math.sqrt(2)/2*ba... |
b3404dbef1c5293f7a95388c0a8812d971da01a1 | IanEllimanJCU/cp1404practicals | /prac_04/lists_warmup.py | 1,058 | 4.09375 | 4 | def main():
numbers = [3, 1, 4, 1, 5, 9, 2]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(f"{5 in numbers}")
print(f"{7 in numbers}")
# "3" in numbers?
numbers = numbers + [6, 5, 3]
print(f"{numbers}")
numbers = [3, 1, ... |
c714ba33bb0c8a57994f9ed8023d02dafef9dbfe | IanEllimanJCU/cp1404practicals | /prac_03/password_check.py | 439 | 3.984375 | 4 | def main():
min_length = 6
password = get_password()
while len(password) < 6:
password = input("Password too short. Please input a password that's at least 6 characters long: ")
passwords_to_asteriks(password)
def get_password():
password = input("Please input a password at least 6 charact... |
7277a6a1b89a25fd4f3a3f089f5fb500b300f3ab | Mrbzs/advent-of-code | /2019/14/14.py | 2,458 | 3.515625 | 4 | import math
import os
inputFile = open(os.path.dirname(__file__) + '/input.txt', 'r')
lines = inputFile.readlines()
inputFile.close()
def solve():
reactions = {}
amounts = {}
# Preprocess into dict for faster location of product
for line in lines:
left, right = line[:-1].split(' => ')
... |
9f5f514e8e5a3fb5a8143e372980ea46ce665c60 | barlaensdoonn/UDP_broadcast | /receive.py | 974 | 3.59375 | 4 | #!/usr/bin/python3
# UDP socket multicasting - receive with socketserver
# 12/11/17
# updated 6/7/18
# code below taken directly from python docs
# https://docs.python.org/3.4/library/socketserver.html
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
"""
This class works similar to t... |
6e021bca9b0d13bb19a36040f9faf5a0104fd9de | YifanXia/algorithm_stanford | /Part1/SearchTreeHelper.py | 7,402 | 3.890625 | 4 | class Node:
def __init__(self, key):
self._key = key
self._parent = None
self._left_child = None
self._right_child = None
self._tree_size = 1 # the size of the tree rooted at this node
@property
def key(self):
return self._key
@key.setter
def key(sel... |
6e5a52fe3bedfb7a8b043e6819a81742fdce1a3e | YifanXia/algorithm_stanford | /Part1/HeapHelper.py | 3,288 | 3.875 | 4 | class MinHeap:
'''
Define a MinHeap data structure from scratch.
A MinHeap extracts the minimum value in logarithmic time
'''
def __init__(self):
self.data = [] # a list to store data
self.size = 0 # size of the heap
def build_heap(self, input_list):
self.size = len(inp... |
1143c8f5e1ba743d83e8fa8ebe1cd7eb51a41198 | ujwalsharma-pro/INVENTORY-MANAGEMENT-PROJECT | /InventoryManagment.py | 9,458 | 3.703125 | 4 | '''
MR.UJWAL SHARMA
ujwalsharma.pro1@gmail.com
9326303601
ETG-INTERNSHIP : PYTHON FOR AI/ML
'''
import json #importing json module in the program
x=1;T={};data={} #inititalizing 'T' & 'data' dictionary, x variable for the while loop
while(x==1):
ch=int(input(" PRESS : \n 1 : CREATE A NE... |
ff6dc81b4ea702b79d33d8a5c4e0f79c729c754d | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /1 Simple python programs/17 Print series of number (1+2+......+n).py | 120 | 3.5625 | 4 | n = eval(input('Enter Number: '))
series= ''
for i in range(1,n+1):
series+=str(i)+'+'
print(series[0:-1]+'=')
|
6b7e50162177119ec01067feef7fb86c99b0c44f | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /5 Python Programing Examples on Dictionary/2 Concatenate two dictionaries into 1.py | 354 | 3.875 | 4 | def Concatenate(dict1, dict2):
k=2
for key,value in dict2.items():
if key not in dict1.keys():
dict1[key]=value
else:
s= str(key)
s+=str(k)
k+=1
dict1[s]=value
return dict1
d1= {'name':'saif','age':21}
d2={'name':'baber','city':'ka... |
04ec6944c054194447f853865a5458f0a3ebf62c | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /1 Simple python programs/11 odd nums in given range.py | 157 | 3.9375 | 4 | def odd_numbers(Range):
for i in range(1,Range+1):
if i%2 != 0:
print(i,end=' ')
else:
print('')
odd_numbers(30)
|
22907b28f7147d4847d9102335cdbf80c656e509 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /1 Simple python programs/9 Read two numbers and print their Quotient and Remainder.py | 182 | 3.921875 | 4 | def Quotient_Remainder(num1,num2):
quotient=num1/num2
remainder=num1%num2
return "Quotient: {}\nRemainder: {}".format(quotient,remainder)
print(Quotient_Remainder(89,5))
|
d56c87c05783404424c8d23b2f8b673d5bf15f5c | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /2 Python Programming Examples on Mathematical Expressions/8 Table of given number.py | 114 | 3.59375 | 4 | def Table(num):
for i in range(1,10+1):
multiple=num*i
print(num,'x',i,'=',multiple)
Table(5)
|
33837815dda3fc2d3dd11a59e7537d5a42dd3ed2 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /4 Python Programming Examples on Strings/10 Take two string & display larger string.py | 366 | 4.03125 | 4 | def display_larger(str1, str2):
count1=0
count2=0
for i in str1:
count1+=1
for j in str2:
count2+=1
if count1> count2:
display = str1
elif count1==count2:
display= 'Both strings are of same length'
else:
display = str2
return display
s1= 'Hello'
s... |
a8b1e6d4f527941b81dc12e46ee4f785b91f6960 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /2 Python Programming Examples on Mathematical Expressions/25 Print Numbers in Range (1,Upper) without any loop.py | 119 | 3.53125 | 4 | def Printnumbers(upper):
if upper >0:
print(upper,end=' ')
Printnumbers(upper-1)
Printnumbers(20)
|
4ca228eb9e25632625d380b31ece408fe6d0cbb2 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /3 Python Programming Examples on Lists/6 2nd Largest number in list using BubbleSort.py | 299 | 3.953125 | 4 | def BubbleSort_2ndLargest(lst):
for i in range(len(lst)):
for j in range(len(lst)-i-1):
if lst[j] >= lst[j+1]:
lst[j],lst[j+1]=lst[j+1],lst[j]
second_largest= lst[-2]
return second_largest
lst= [10,1,24,6,7,8,3,5,2]
print(BubbleSort_2ndLargest(lst))
|
9829f567953ab3edb816302fb96aca03cc56ddd6 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /2 Python Programming Examples on Mathematical Expressions/22 Find Gravitational ForcrActing Between Two object.py | 380 | 4.03125 | 4 | def GravitationalForce(mass1, mass2, distance):
m1=mass1
m2= mass2
d= distance
constant = G = 6.37*10**-11
force = (G*m1*m2)/(d**2)
return force
m1= eval(input('Enter the mass of 1st object in kg: '))
m2 = eval(input('Enter the mass of 2nd Object in kg: '))
d= eval(input('Enter the distance betw... |
360ae82e367477afb77405d7b766238c4dd9e493 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /2 Python Programming Examples on Mathematical Expressions/13 Check number is Amstrong Number or not.py | 303 | 3.8125 | 4 | def Armstrong_number(number):
armstrong=0
num=number
length= len(str(number))
while num >0:
digit= num%10
armstrong+=(digit**length)
num=num//10
if armstrong == number:
res= True
else:
res=False
return res
print(Armstrong_number(35))
|
a28d29eafbc875f57f06227218daf6c8d6bb74b8 | Saifullahshaikh/-IPU-Intensive-Programming-Unit-01 | /1 Simple python programs/12 Sum of digits in a number.py | 112 | 3.8125 | 4 | def sum_digits(num):
Sum=0
for i in str(num):
Sum+=int(i)
return Sum
print(sum_digits(123))
|
7e0586bc46ce0616ae6acacd7557f2801a125ce6 | hakkigokgoz/python_dosyalarim | /deneme.py | 332 | 3.65625 | 4 | # -*- coding: utf-8 -*-
#ilk sayıyı ve x değişkeninde tut
x=input('Birinci sayıyı gir')
# x değişkenini str den int e çevir ve y değişkeninde tut
y=int(x)
#ikinci sayıyı al ve z değişkeninde tut
z=input('İkinci Sayıyı gir')
t=int(z)
#İki sayıyı çarp
sonuc=y*t
print('İki Sayının Çarpımı :' ,sonuc)
|
da59fba64b0ee3ed7abf9a628f938c717acd5d84 | youzerssif/Algorithms | /python_codes/decorateurs.py | 740 | 3.515625 | 4 | def verbose(fn): # fonction → fonction décorée
def decorated(*args, **kwargs):
print("Function: ", fn.__name__)
print("Arguments: ", args, kwargs)
result = fn(*args, **kwargs)
print("Result: ", result)
return result
return decorated
verbose_sum = verbose(sum... |
390d75853dc0e9333f257fb78a7508199974845f | imsreyas7/DAA-lab | /Algo_intro/fibo2.py | 244 | 4 | 4 | def fibo2(n):
if n<=1:
return n
else:
return(fibo2(n-1)+fibo2(n-2))
n=int(input("Enter a number: "))
print("The value is : ",fibo2(n-1))
"""
(base) C:\Users\sreya\Desktop\labs\DAA>python fibo2.py
Enter a number: 9
The value is : 21
""" |
8db19628f571ab9cb2e0babcb961974c8baaf99d | imsreyas7/DAA-lab | /Recursion/expo3.py | 263 | 4.21875 | 4 | def expo3(x,n):
if n=0:
return 1
else:
if n%2 ==0:
return expo3(x,n/2)*expo(x,n/2)
else:
return x*expo(x,n-1)
x=int(input("Enter a number whose power has to be found "))
n=int(input("Enter the power "))
print("The result is ",expo3(x,n)) |
60cb18f177e035f6261649450a6ff98d1ce01d7b | imsreyas7/DAA-lab | /Recursion/matpow2.py | 571 | 3.515625 | 4 | def mat_mul(a,b):
if(len(a[0])!=len(b)):
print("Invalid input")
return
c=[[0 for j in range(len(b[0]))]for i in range(len(a))]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
c[i][j]+=a[i][k]*b[k][j]
return c
def mat_power(x,n):
pdt=[[0 for j in range(len(x[0]))... |
cf2dc0b6a4236a9df49b1cf229d898b655db8bae | AffanKhurram/BudgetAlphaZero | /Board.py | 2,271 | 3.65625 | 4 | # @title TicTacToe thing
import numpy as np
class Board:
num_actions = 9
shape = (3, 3, 3)
name = "TicTacToe"
def __init__(self):
self.board = np.zeros((3, 3))
self.split_board = np.zeros((3, 3, 3))
self.move_history = []
self.split_board[:, :, 2] = 1
def check_wi... |
b38e84155c8576d20e882c1939b7f4391e39f8f6 | nanjiangshu/test_github | /app2/run.py | 761 | 4.0625 | 4 | #!/usr/bin/env python
"""A test python code"""
import math
class App2:
"""simple math"""
def __init__(self, x=10):
self.x = x
def sin(self):
"""sin"""
c = math.sin(self.x)
print(f"{__name__}: sin({self.x}) = {c}")
def cos(self):
"""cos"""
c = math.cos(... |
a99f1e9ebbae8dac5c967318b808c5cc6744c0ad | AKozhemyako/python_lesson02 | /min_numbers.py | 500 | 3.59375 | 4 | # 1. Даны 4 числа типа int. Сравнить их и вывести наименьшее на консоль.
# 2. Вывести на консоль количество максимальных чисел среди этих четырех.
import task_if_lib
a = 2
b = 1
c = 3
d = 3
print_min(10,20)
task_if_lib.print_min(10, 20)
min_local = task_if_lib.get_min(task_if_lib.get_min(a, b), task_if_lib.get_min(c... |
e321d7a736d29f2bef291bd5e6f72ccd237e7619 | smit-mehta/uk-leave-of-absences | /countries.py | 552 | 3.703125 | 4 | from country import Country
NON_CACHED_COUNTRY = "NonCachedCountry"
# Caching biggest possible "rectangular" boundary of coordinates for ten largest countries
# and UK such that all points within this rectangle belong to the said country.
CACHED_COUNTRIES = {
Country("United Kingdom", -1, 5, 10, 20),
Country("Ind... |
ad02d70583ed30bea2710fbc61df4a00680dfdc0 | Aksharikc12/python-ws | /M_2/Q_2.py | 1,407 | 4.53125 | 5 | '''2. Write a program to accept a two-dimensional array containing integers as the parameter and determine the following from the elements of the array:
a. element with minimum value in the entire array
b. element with maximum value in the entire array
c. the elements with minimum and maximum values in each column
d. t... |
3c0a1433e65d2430f183e66a3aa4542c1dec74ae | Aksharikc12/python-ws | /M_2/vowel.py | 236 | 3.625 | 4 | name = input("enter your name : ")
lst = ['a','e','i','o','u']
c = 0
for n in name:
if n in lst:
c+=1
print(c)
print(len(list(filter(lambda x:x in lst , list(name)))))
print(len(list(filter(lambda x:x in lst , name)))) |
134efc934b126030ab141151ca6b786e68dc8938 | Aksharikc12/python-ws | /M_1/Q_10.py | 256 | 3.734375 | 4 | '''a program to print the pattern.'''
max=5
for i in range(1, max + 1):
for j in range(max , i-1 , -1):
print(" ",end="")
for k in range(1 , i + 1):
print(k,end="")
for l in range(k-1,0, -1):
print(l,end="")
print() |
211f7d8c6027e43fa5933eb581ecee3a8daf0edb | Aksharikc12/python-ws | /M_1/Q_1.py | 413 | 4.25 | 4 | '''1. Write a program to accept a number and determine whether it is a prime number or not.'''
import math
num=int(input("enter the number"))
is_prime=True
if num<2:
is_prime=False
else:
for i in range(2,int(math.sqrt(num)) + 1):
if num % i == 0:
is_prime=False
break
if is_pr... |
50959738f8045b5b3d0beea7c9992cbbe820dc82 | murphy1/python_problems | /chapter6_string.py | 1,577 | 4.1875 | 4 | # file for Chapter 6 of slither into python
import re
# Question 1, user input will state how many decimal places 'e' should be formatted to.
"""
e = 2.7182818284590452353602874713527
format_num = input("Enter Format Number:")
form = "{:."+format_num+"f}"
print(form.format(e))
"""
# Question 2, User will input 2 ... |
f621953d0e8670718bd1a1848221456066e9fdb6 | Undiy/coursera-algo | /Part2/2. Cluster/hamming.py | 1,335 | 3.59375 | 4 | import unoinfind
import itertools
def load(file):
nodes = set()
file = open(file)
for line in file:
l = line.split()
if len(l) > 2:
nodes.add(int("".join(l), 2))
elif len(l) == 2:
radix = int(l[1])
file.close()
# print len(nodes)
#... |
731640dd4555e2a940ac2b7d5910d936cc49db77 | Undiy/coursera-algo | /Part1/5. Shortest path/run.py | 635 | 3.609375 | 4 | import shortest
def main():
graph = dict()
file = open("dijkstraData.txt")
for line in file:
pairs = line.split()
graph[int(pairs[0])] = [ (int(pair.split(",")[0]), int(pair.split(",")[1])) for pair in pairs[1:]]
file.close()
p = shortest.shortest_path(graph, 1)
... |
c1ec95c776e2a3d538e6fb48354d54a069c447b5 | isabellaleehs/Data_Visualization | /Choropleth map/make_map.py | 2,974 | 3.53125 | 4 | # Create choropleth map
#
# Date: Dec 2017
import plotly as py
import pandas as pd
import pycountry
def get_data(filename):
'''
Loads data from file and cleans it.
Inputs:
filename: file directory
Returns: a cleaned dataframe
'''
df = pd.read_csv(filename)
# Reset header row
... |
fe90c173f4b7d260fc4c2151e97cde53691ea4c0 | thongtran715/Coursera-Algorithm-Courses | /week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 460 | 3.828125 | 4 | # Uses python3
import sys
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
second = 1
for i in range(n - 1):
previous, current = current, previous + current
if i == 2:
second = current
return (current- second)%10
#
# if __name__ == '... |
c45e70ce98f3e35494df30f0594160bd2b25e986 | Ken-Alviola/statistics-exercises | /hypothesis.py | 941 | 3.953125 | 4 | # Helper function to evaluate hypothesis
def evaluate_hypothesis(null_hypothesis, alternative_hypothesis, alpha, p_value, t_value, tails = "two"):
print(f"t: {t_value}, p: {p_value}, a: {alpha}")
print()
def print_null_hypothesis():
print(f"We fail to reject the null hypothesis: {null_hypothesi... |
ab4a62168b00a00e875b690965cd5a1ed86c8ca7 | julesser/crocoddyl | /unittest/python/crocoddyl/differential_action.py | 13,141 | 3.5625 | 4 | import numpy as np
import pinocchio
from .state import StatePinocchio, StateVector
from .utils import EPS, a2m, randomOrthonormalMatrix
class DifferentialActionModelAbstract:
""" Abstract class for the differential action model.
In crocoddyl, an action model combines dynamics and cost data. Each node, in
... |
b8fe6d247887d1789f783476249710f64371c2f6 | mohakdev/Python_projects | /search.py | 7,136 | 3.84375 | 4 | def search(): #creating a function
a=input("Enter a car company brand: ")
a=a.lower()
if a=="audi":
print('''Audi AG is a German automobile manufacturer that designs, engineers,
produces, markets and distributes luxury vehicles.
Audi is a member of the Volkswagen G... |
455b9e49ece1882154dabd045e37d0bd931c5de5 | Basker12/Vectors | /Adding and subtracting vectors/Adding_and_subtracting_vectors.py | 668 | 3.75 | 4 | #Made by Basker12
#Adding and subtracting two vectors.
#Adding
while True:
v1 = input("Write a vector in the format of x,y: ")
v1 = v1.split(",")
v2 = input("Write a second vector in the format of x,y: ")
v2 = v2.split(",")
final_v1 = int(v1[0])+int(v2[0])
final_v2 = int(v1[1])+int(... |
c62da30af35b360a47090416b0eb9538bff0ebdd | EricHenry/algo_data_struct_exercises | /1_strings/1_2.py | 376 | 4.09375 | 4 | '''
Coding problem 1.2 from cracking the coding interview
Implemnt a function which reverses a string
'''
def reverse_str(str):
str_len = len(str)
rev_str = [None] * str_len
for idx in range(str_len):
rev_str[str_len - (idx + 1)] = str[idx]
return ''.join(rev_str)
assert(reverse_str('abcd... |
01f7fd443af4a4184d151de941efe9c1d454ae83 | jforan/507_Project2 | /SI507_HW4.py | 2,393 | 3.578125 | 4 | # SI 507 - Homework 4
# Note the changed name (Lab -> Homework)
# Instructions all provided in this file.
# IMPORTANT: Please read ALL of the instructions for each part before starting on it.
# Submit this edited code file (only) to HW 4 on Gradescope via Canvas to see test results!
## Your import statements for use... |
e20a5bfa81307584e69de33bbc0b4f22bfc09f6c | tommy-stone/Intro_CompSci_Python_Code | /Week_2/Problem Set/Problem_1.py | 753 | 3.65625 | 4 | #!/usr/balancein/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 16:43:10 2018
@author: tstone
balancealance: the outstanding balancealance on the credit card
annualInterest rate: annual intestest rate as a decimal
monthlyPaymentRate: minimum monthly payment rate as a decimal
"""
balance = 484
annualI... |
83b2663bf20b961eb4ac3273e59dbadcb852b9d5 | tommy-stone/Intro_CompSci_Python_Code | /Week_1/Problem Set 2.py | 258 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 13:28:18 2017
@author: tstone
"""
s = 'bobobooooobbbooobobbo'
count = 0
for vowel in s:
if vowel in 'bob':
count += 1
print("Number of times bob occurs is: " + str(count)) |
233d0acef4e23336c0707452ef36533d8aaa7a15 | aaronke/Leetcode_Python | /PathSumTwo.py | 857 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[i... |
72e9db643e37c5dd18fbd81082428d63b21a23d2 | igormarfin/HitFox_Case_Study | /scripts/ProblemA/ProblemA.py | 5,860 | 3.734375 | 4 | #! /usr/bin/env python
"""
This is the ProblemA class to generate divisors of numeric keys in a list:
Example Input:
[7,4,2,10,3,6,4,5]
Example Output:
{
2 => [1],
3 => [1],
4 => [1,2],
5 => [1],
6 => [1,2,3],
7 => [1],
10 => [1,2,5],
}
To test the class :
./%prog [--debug] [--tkinter] <args>
... |
0bd1ea3975e04caccb70a799ae6bb6e514991b83 | SubsonBigod/LeetCode | /t001-100/t081-100/t088.py | 930 | 3.90625 | 4 | class Solution:
""" 88
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
"""
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
... |
efbf153037dcaeda22c6e2a2066f345205f03e47 | SubsonBigod/LeetCode | /t001-100/t061-080/t070.py | 607 | 3.796875 | 4 |
import math
class Solution:
""" 70
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
"""
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
result = 0
for two_step in range(n//2+1):
one_step = n - 2*... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.