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
76c657aebecfdf6fe6b415a4d82adffc75dc0516
AkeelAli/coursera-algorithms-1
/programming_question_6/two_sum_sorted_array.py
2,688
4
4
def binary_search(arr, start, end, num): size = (end-start) + 1 if (size == 2): if (arr[start] == num): return start elif (arr[end] == num): return end else: return -1 elif (size == 1): #start == end if (arr[start] == num): re...
ca62fc9b6c382b9d0066e187353d038202d494f4
anandtakawale/classcodes
/optimizations_sem8/dichotomousSearch.py
1,325
3.671875
4
import texttable def dichotomousSearch(f, a, b, d, n): """ Returns minima of function f using dichotomous search (a, b): initial interval of uncertainty d: differnce between positions of two experiments n: number of function evaluations n should be even L_n = L_0 / 2**(n/2) + d / L_0 *(1 - 1 / ...
afa0a8a76248a73be56eec3d388a23ec11945f96
anandtakawale/classcodes
/optimizations_sem8/fibonacci.py
2,787
4.15625
4
import texttable import math def fibonacciMethod(f, a, b, epsilon): """ Returns minima of the function """ #calculating number of iterations fn = (b - a) / epsilon n = fibFinder(fn) print n k = 0 table = texttable.Texttable() table.add_row(["Iteration", "a", "b", "x1", "x2", "f(...
dba312aa517f4a91cfb35f5518736a5b2bfc6d68
mnthnx64/steganograhpy
/Simple Steganography/decoder.py
875
3.96875
4
""" Python program to realize the decoding part of stenography. :Author: Manthan C S :GitHub: mnthnx64 """ import cv2 import numpy as np class Decoder: """ Decodes a stenographic image back into text using basic subtraction logic of ascii values. :functions: decode() """ text = list() ...
35cd0814bb7aaedc923c533943637886830c0593
AshVijay/Leetcode_Python
/496.py
2,433
4.125
4
""" 496. Next Greater Element I Easy 1103 1685 Add to List Share You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is t...
3f7390aaa104f23b2a665f45c61435cfab2e9a77
AshVijay/Leetcode_Python
/283.py
697
3.890625
4
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] """ class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums...
f6c938ff8a0ea4e990f8f4b37a43dbcbeda3fc14
AshVijay/Leetcode_Python
/347.py
1,038
3.875
4
""" Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O...
fb9a75124521e1b05db94225920e9796127cddd3
AshVijay/Leetcode_Python
/49.py
713
4
4
""" Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: """ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anag_dict = {} if strs == []...
1cb3663248133e46badb65a4c0f2d76a021cd013
hrkngt/towerOfHanoii
/test.py
151
3.828125
4
name = "Haruki" age = 22 print("My name is ", name) print("I'm", age, "year old.") for i in range(5): age+= 1 print("I'm now", age, "year old.")
2ed9aace099f34e3deacc7b0a309ef34258820ab
zhoujunjie-xixi/learning-record
/day4/func_test3.py
332
3.609375
4
# *args只接收位置参数,输出为元组形式 def test1(x, *args): print(x) print(args) test1(1, 2, 3, 4, 5, 6) # **kwargs只接收关键字参数,输出为字典形式 def test2(**kwargs): print(kwargs) # test2() takes 0 positional arguments but 5 were given # test2(1,2,3,4,5) test2(name="bob", age=23)
420772525d7183ab837153dfa66cb2f575b765f9
zhoujunjie-xixi/learning-record
/day8/正则1(处理字符格式).py
608
3.5625
4
import re # match 匹配从左到右依次进行 第一个不符合直接pass # . 匹配任意1个字符(除\n) res = re.match(".","happy") print(res.group()) res = re.match("...","ha") # 匹配至少三个(除\n) # return None # \d 匹配数字,即0~9 # \D 匹配非数字 res = re.match("\d\D","1abc") #注意区分 "\" 和 "/" print(res.group()) # \s 匹配空白 # \S 匹配非空白 res = re.match("\s\s\s123"," 123abc") ...
3280f8455676884c49c501378003f2a5617322f9
zhoujunjie-xixi/learning-record
/day3/deepcopy.py
394
3.890625
4
import copy name1 = ["alex","xiaoming","xiaohua",["xiaohua","xiaojin"]] name2 = name1 name3 = name1[:] name4 = name1.copy() name5 = copy.deepcopy(name1) name1[2] = "小明" name1[3][1] = "小华" #正常的浅copy只copy一层,如果还有嵌套,copy的是地址,所以没有真正地copy第二层,需要使用深copy print(name1) print(name2) print(name3) print(name4) print(name5)
114ec4d0d0cf918a5263eee658734c99a1ad4900
zhoujunjie-xixi/learning-record
/day7/property2.py
567
3.625
4
class Dog(object): def __init__(self, name): self.name = name self.__food = None @property def eat(self): print(" %s is eating %s" % (self.name,self.__food)) @eat.setter def eat(self,food): print(" %s is eating %s" % (self.name,food)) @eat.deleter def eat(...
c1b6b7dc4b7e16878546e91dfd4f1175e0e44b50
Tadrop/30_days_of_code
/day10.py
362
3.984375
4
def fibonacci(number): if not isinstance(number,int): return 'Invalid' elif number <0: return 'Wrong input' a,b=0,1 while a<10000000000000000000000000000000000000000000000000000000000000000000000000: a,b=b,a+b if number == a: return True print(fibonacci(13)) p...
70ac588cf1ba0c9fd8db5fe5688ed44730e73efe
Tadrop/30_days_of_code
/day9.py
484
4.21875
4
def fibSum(number): if not isinstance(number,int): return 'Invalid input, number must be positive integer' if number == 0 : return 0 elif number < 0: return "Invalid, number can't be negative" elif number > 0: pass num =0 a,c=0,1 while c>=number: ...
162f361ed3ce82b5e1e2c20669d824b69723f1b0
arthurxuwei/Study
/coding/python/basic/funcprogram.py
508
3.78125
4
def outer(): i = 10 def inner(): return i return inner print outer()() def outer(): i = 10 return (lambda : i) print outer()() print map(lambda x : x**2, [1,2,3,4,5,6]) print map(lambda x,y: x + y, [1,2,3], [4,5,6]) print map(None, [1,2,3], [1,2,3]) #equal print zip([1,2,3], [1,2,3]) print filter(lam...
a362e4e8e932d5cd9c0adca6626fe00e98ffea52
arthurxuwei/Study
/coding/python/basic/generator.py
311
3.765625
4
[i for i in range(20) if i&1!=0] def get(): yield 0 yield 1 yield 2 generator = get(); print generator.next() print generator.next() print generator.next() def fibonacci(): a = b = 1 yield a yield b while True: a, b = b, a+b yield b for num in fibonacci(): if num > 100: break print num,
ebe73e7608d8ef284b5afd55318f1cfc56228c4b
vignesh-beep/vp...
/vikey9.py
147
3.859375
4
n13,n12=input().split() n13=int(n13) n12=int(n12) if(n13>n12): diff=n12-n13 else: diff=n13-n12 if(diff%2==0): print('even') else: print('odd')
01c7434702fa590b57c75ad76095266778fa4fc4
szgula/Programming-assignments
/robot.py
9,371
3.8125
4
import pygame from definitions import * from objects import * class Robot: def __init__(self, x, y, direction, energy, cargo): self.x = x self.y = y self.direction = direction self.color = GREEN self.energy = energy # steps left in this level self.cargo = ...
a2ed5fadd9ec223f62a358e1b4b4bf24dbf5b2f4
Where-does-the-tide-fall/The-crawler-program
/study_GUI/tk_18.py
368
3.5
4
from tkinter import * master = Tk() thelB = Listbox(master, selectmode=EXTENDED, height=11) thelB.pack() # thelB.insert(0, '新年快乐') # thelB.insert(END, '牛年大吉') for item in range(11): thelB.insert(END, item) # thelB.delete(0) thelButton = Button(master, text='删除它', command=lambda x=thelB: x.delete(ACTIVE)) thelB...
0f70ca8411eb3bdc3509549ff0b820111b9580db
Where-does-the-tide-fall/The-crawler-program
/study_GUI/tk_删除填充.py
456
3.71875
4
# Tk删除填充 from tkinter import * root = Tk() w = Canvas(root, width=200, height=100) w.pack() line_1 = w.create_line(0, 50, 200, 50, fill='blue') line_2 = w.create_line(100, 0, 100, 100, fill='yellow', dash=(4, 4)) rect1 = w.create_rectangle(50, 25, 150, 75, fill='black') w.coords(line_1, 0, 25, 200, 25) w.itemconfi...
d73d70107545c2682eb1c52df10b8dd58eb38aad
Where-does-the-tide-fall/The-crawler-program
/study_GUI/tk_04.py
334
3.5
4
from tkinter import * root = Tk() photo = PhotoImage(file='photo3.gif') theLabel = Label(root, text='学习Python\n 真是太开心了', justify=LEFT, image=photo, compound=CENTER, font=('镇魂手书', 30,), fg='black') theLabel.pack() mainloop()
8f79a266b688746efd3f07e9d54b808d153c2488
bikash77715/PizzariaPy
/OrderHandler.py
3,674
3.796875
4
import Order, Pizza, logging logging.disable(logging.INFO) logging.basicConfig(level = logging.INFO, format = '%(levelname)s-%(message)s') class OrderHandler: def __init__(self): self.newOrder = Order.Order() self.toppings = ["Bacon", "Olives", "Ham", "Mushrooms", "Pineapple", "Salami", "Anchovies"] # add...
fdaa948cbdcf1f44018aaed8e492e70d6acd8a14
anastasija-grekova/Convert-array-into-heap
/build_heap.py
1,814
3.578125
4
# python3 class HeapBuilder: def __init__(self): self._swaps = [] self._data = [] self._size = 0 def read_data(self): n = int(input()) self._data = [int(s) for s in input().split()] assert n == len(self._data) def write_response(self): print(len(se...
c2f7de13519097b7c27efadee043df59cfda2a7e
Theoreticism/trivial-purfuit
/src/entry_view.py
1,308
3.53125
4
from src.models.Color import Color def create_entry_view(tk, entry_frame): """ Method to create the name entry view :param tk: Object representing Tkinter :param entry_frame: Tkinter Frame object """ helvetica_20 = tk.font.Font(family='Helvetica', size=20, weight='bold') # player name la...
80c70ddc2a5f144314acc68f929a2ef70418c90d
EstherAmponsaa/cssi
/week3/test.py
1,309
4.28125
4
#print('Hello CSSI') #name ='Bill' #name = 55 #print(name) #name = raw_input('Enter your name:') #print('Hi there..') #print(name) #print('na'*16) # print('BATMAN!') #print('Pow!'*3) #user_input = raw_input('Enter anything:') #print('You entered a ', (type(user_input)) #print('raw_input gives us strings') #num1 = raw...
8aabefe65e37fd1b223d5910875332a193e9ce02
EkaterinaBazhanova/Python
/Les3Ex4_2.py
1,059
4.25
4
def my_func_2(x, y): """Выволняет возведение действительного положительного числа в отрицательную целую степень циклом с помощью *.""" power = 1 n = abs(y) + 1 for i in range(1, n): power = power * (1/x) return round(power, 4) def check(): """Проверяет правильность ввода данных пользова...
7f62950ad9d5f71e296aefba3d4cf0cdcb61b9de
luctivud/Coding-Trash
/UditGupta_Py_P.py
682
3.71875
4
''' PROGRAM FOR BINARY SEARCH NAME : UDIT GUPTA R.NO : 1803210166 SEC : CSE_A ''' def binarysearch(arr, val: int, r: int, l: int = 0) -> int: while l <= r: mid = l + (r - l) // 2; if arr[mid] == val: return mid elif arr[mid] < val: l = mid + 1 else: ...
69c2bc890089754abd6ca0021ba726b2ebe7844b
Abinesh1991/Numpy-tutorial
/NumpyTutorial8.py
755
4.28125
4
""" Python, Numpy and Probability Random using numpy """ import numpy as np outcome = np.random.randint(1, 7, size=10) print(outcome) # generated 5*4 matrix using the random number range from 1 - 7 """ output: [[4 4 5 4] [4 4 5 2] [3 3 3 4] [3 5 4 5] [6 1 2 6]] """ print(np.random.randint(1, 7, size=(5, 4))) #...
409cb01cecf4af685af65480648c49c8efaf57c0
Abinesh1991/Numpy-tutorial
/NumpyTutorial5.py
2,239
4.1875
4
""" Data type object 'dtype' is an instance of numpy.dtype class. It can be created with numpy.dtype. """ import numpy as np # sample example with int16 data type i16 = np.dtype(np.int16) print(i16) lst = [[3.4, 8.7, 9.9], [1.1, -7.8, -0.7], [4.1, 12.3, 4.8]] A = np.array(lst, dtype=i16) print(A) "...
f6d990350bce450c6e70d479399b9a60191058fb
Helianus/Python-Exercises
/src/SquareHard.py
229
3.828125
4
# Square a integer, the hard way n = int(input("Input an integer: ")) ans = 0 iterStill = abs(n) # n^2 = n + n + .. + n = n(n) while (iterStill != 0): ans += abs(n) iterStill -= 1 print(str(n), "*", str(n), "=", str(ans))
8b57cdcbba3d3c0f7d0203ec3be8e29167c11a8d
Helianus/Python-Exercises
/src/SumOfNumbers.py
452
4.25
4
#Given two integers a and b, which can be positive or negative, # find the sum of all the numbers between including them too and return it. # If the two numbers are equal return a or b. # Note: a and b are not ordered! def get_sum(a, b): sum = 0 if a == b: return a elif a > b: for i in ra...
0dd8bda64e43cea077ab8a390b1f58b1fe75d101
Helianus/Python-Exercises
/src/PairRoot.py
238
4.15625
4
# 0 < pwr < 6 and root^pwr = user input n = int(input("Enter an integer: ")) root, pwd = 0, 0 while root <= n: pwd += 1 if pwd == 6: pwd = 1 root += 1 if root ** pwd == n: print(root, "^", pwd, "is", n)
11ef074543b310af32ce9d0b43a2a23111422650
mor16fsu/bch5884
/tempconversion.py
286
4.25
4
#!/usr/bin/env python3 #github.com/mor16fsu/bch5884 import math x=float(input("Please enter a value in degrees Farenheit to convert to degrees Kelvin:")) print (type (x)) x=float(x) y=math.floor(x-32)*5/9+273.15 print (y) print ("The calculation is complete: Degrees Kelvin")
0f5a128975fbf274ce34e15fa199ee07d6bf911f
samhithaaaa/Trees-2
/pathsum.py
1,957
3.96875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """Recursive solution""" #Accepted by leetcode #Time complexity - O(n) since we are traversing through every node #Space complexity - O(n)because of...
c15e820cc3437d0ac50ca768eb0a33181a1a3573
EmanuP/AccountManager
/Deposit.py
767
3.5
4
import sqlite3 import Login import CurrentBalance def deposit_on_account_balance(conn, usr, deposit): """ Check for the existence of a specified user in the database :param conn: the Connection object :param id_pub: user :param deposit: amount to deposit :return: True if transaction preceeded ...
a346f1099bd0cf86790b21d970fa72ede2864751
39xdgy/Playground_py
/new_f.py
357
4.0625
4
print("Whatever") x = 3 ##print(x) a = 88 b = 3.5 c = True d = "test" ##print(type(b)) ## this is for ..... y = 5 ** 2 x = 5 % 2 ##print(x) x = 2 #print(x == 1) if(x == 1): print("yes") elif(x == 1): print("second yes") else: print("Wrong") for whatever in range(1,10): print("this is a loop") ...
694745056f269b3940e1352062a959e035c65053
khvr/LeetCodeAlgo
/AddTwoNumbers.py
1,357
3.9375
4
#python code to stringify linked list def linked_list_str(l): if l is None: return ''; return str(l.val)+'->'+linked_list_str(l.next) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNu...
b31e15e56a368e9348dff60ef59cf8cadf93e10c
panc0046/python_lab9
/lab9_task1.py
852
3.59375
4
import csv # Read first file and write all data in csv file boys_file=open("2000_BoysNames.txt","r") #create new csv file csv_file_boy = open("Names_Boys.csv","w") write_csv = csv.writer(csv_file_boy) write_csv.writerow(('First Name', 'Count')) for lines in boys_file.readlines(): stripped = lines.strip() new_...
37fc75aff6cf6e34025c950e19ac1522a16907e9
davidcse/LanguageModel-Ngrams
/perplexity.py
4,815
3.703125
4
from sys import argv import math from functools import reduce # Dictionaries storing file probability data. unigram_data_dict = {} bigram_data_dict = {} # Uses the perplexity formula, provided that you give it a calculated sum probability component for the formula. # Also, needs the sequence length, N, to take the nt...
002701d570bbb7035194481d19dce9a2e462d260
dchavarria/Cryptography
/CaesarCipher.py
2,520
4.0625
4
import sys def encode(plaintext, key): ciphertext = '' for c in plaintext: if 65 <= ord(c) <= 90: ciphertext = ciphertext + chr(((ord(c)-65+key) % 26) + 65) elif 97 <= ord(c) <= 122: ciphertext = ciphertext + chr(((ord(c)-97+key) % 26) + 97) else: ciphertext = ciphertext + c print print 'Key: %d' % ...
ff8f6736337c4d9a9e36471efbe60f6e73766ce8
christiangalleisky/DailyCodingProblems-700---750
/DCP_724.py
710
3.890625
4
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right PLUS = "+" MINUS = "-" TIMES = "*" DIVIDE = "/" def evaluate(root): if root.val == PLUS: return evaluate(root.left) + evaluate(root.right) elif root.val == MINUS: ...
c773e1256620eebcd865d2b54d65c4e99c9d9b9c
Sandy4321/machine_learning_notes
/python2/fun/monty_hall.py
4,041
3.890625
4
from __future__ import division import random def test(): choices = ['goat', 'goat', 'bingo'] # player picks one randomly player_pick = choices.pop(choices.index(random.choice(choices))) # now host picks one which is a goat - no need for this # host_pick = choices.pop(choices.index('goat')) ...
c40f02ed6ae09320221ce9d5f8ebefd7b38e0563
syedmuhammadhassanzaidi/CampaignMonitor
/CampaignMonitorTechTask/PythonScripts/task4.py
455
4.03125
4
def find_duplicates(input): dup_list = [] counter = 1 for i in input: num_rep = input.count(i) if (num_rep >= counter): counter = num_rep dup_list.append(i) return set(dup_list) """ Test cases """ input = [5, 4, 3, 2, 4, 5, 1, 6, 1, 2, 5, 4] #input = [1, 2, 3, 4,...
6db4d82f13ebcf3bb99365d2b8af9ff458ca5961
puhelan/150
/1. DS/1.1.py
1,364
4.3125
4
''' 1.1 _______________________________________________________________________________ Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? _______________________________________________________________________________ Notes: 1. with hash map...
636fc16a160c136d215719f6b408c08efa9c1698
shivzy400/StoreAPI
/create_table.py
441
4.09375
4
import sqlite3 connection = sqlite3.connect('data.db') cursor = connection.cursor() query = 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY , username text , password text)' # here id will be autoincremented so no need to specify id while inserting data cursor.execute(query) query = 'CREATE TABLE IF NOT EXIS...
3591c3ed006a778c64fed1e67f0dfd9021a1f6d6
Shirbhateritwik47/AI_programs-
/Postive_nos.py
163
3.8125
4
list1 = [12,-7,5,64,-14] for i in list1: if i >= 0: print(i) list2 = [12,14,-95,3] for i in list2: if i >= 0: print(i)
d02bec19ec77f522fdc569d1fa623abee0c70c78
ellio-hub/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/5-print_comb2.py
162
3.59375
4
#!/usr/bin/python3 for i in range(99): if (i < 10): j = 0 else: j = '' print("{}{}, ".format(j, i), end='') print("{}".format(i + 1))
9b9376bd07e9f0a1d2842219d50d7de4ba877d08
miki1029/Python_Basic
/Jump/Chap06_IO/Sec02_IO.py
1,860
3.96875
4
# -*- coding:utf-8 -*- """ 2) 입력과 출력 사용자 입력 어떤 변수에 사용자로부터 입력받은 값을 대입하고 싶을 때는 어떻게 해야 할까? input의 사용 >>> a = input() Life is too short, you need python >>> a Life is too short, you need python >>> input은 입력되는 모든 것을 문자열로 취급한다. """ temp = 'abcd' a = raw_input() print(a) """ input(prompt) 사용자로부터 입력을 받을 때 “숫자를 입...
02bb4766a189f74df008c73e007d61c9a7842984
humanbeing-dev/Tkinter
/tkinter_examples/keyboard_binding.py
1,411
3.625
4
import tkinter as tk # root = tk.Tk() # root.title("Keyboard binding") # root.geometry("300x300") class Binder: def __init__(self, master=None): self.master = master self.myButton = tk.Button(master, text="Click Me") self.myButton.pack(pady=20) # self.myButton.bind("<Button-3>", s...
2ac5a785071d0fa8a85e296e2bf643f835fdc331
humanbeing-dev/Tkinter
/tkinter_examples/remove_label.py
811
3.578125
4
import tkinter as tk root = tk.Tk() root.title("Removing labels") root.geometry("300x300") def remove_label(): myLabel.pack_forget() # myLabel.destroy() # myLabel.grid_forget() button1['state'] = tk.NORMAL button2['state'] = tk.DISABLED print(button1.winfo_exists()) def myClick(): hello...
74a603afe47a532b0c2d218433aed92b88f95af8
humanbeing-dev/Tkinter
/tkinter_examples/database.py
5,094
3.53125
4
from tkinter import * from PIL import ImageTk, Image import sqlite3 root = Tk() root.title("Sliders") root.iconbitmap("logo.ico") root.geometry("300x500") # Databases # Create a database or connect to one conn = sqlite3.connect('address_book.db') # Create cursor c = conn.cursor() # Commit Changes conn.commit() # ...
c984e1c86831c0dfb7bfde8c60d82d7d705391d3
vdovkin/Algoritms-MIPT
/lab1/ex5.py
283
3.90625
4
import turtle turtle.shape("turtle") N = 10 step = 20 i = 0 while N > 0: i += 1 n = 4 while n > 0: turtle.forward(step) turtle.left(90) n -= 1 turtle.penup() turtle.goto(-5 * i, -5 * i) turtle.pendown() step += 10 N -= 1
f7ca740e573b3b7d85ccf221d73680e7771cb9be
vdovkin/Algoritms-MIPT
/lab8/Cantor set.py
379
3.78125
4
import turtle def cantor(n, l, x=-200, y=200): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(l) if n == 0: return step = l / 3 cantor(n - 1, step, x=x, y=y - 50) cantor(n - 1, step, x=x + 2 * step, y=y - 50) # turtle.penup() # turtle.goto(START_POINT) # ...
9358142ca4d8351054c867886ef52a7c4c903080
vdovkin/Algoritms-MIPT
/lab1/ex3.py
115
3.53125
4
import turtle turtle.shape("turtle") N = 4 while N > 0: turtle.forward(100) turtle.left(90) N -= 1
db7c018802ea6157c8f37df493259da8c79ca7db
RandallWert/RandomSelector
/RandomSelector.py
4,183
3.859375
4
# Program for selecting items at random from a .txt file # from tkinter import * from tkinter import ttk from tkinter import filedialog import random import time def selectAnother(event): # Clear the display of the previous selection: canvas.delete("selectionText") canvas.delete("selectionTextRect") c...
c4a9e4e441886e7ef7b181c670185dd5954c06de
omarcoaur3lio/dotfiles
/.config/polybar/scripts/weather.py
1,066
3.53125
4
#!/usr/bin/env python import urllib.request try: city = "Criciuma" api_key = "642a76e68929c32f7bdee0ed86ed30a3" weather = eval(str(urllib.request.urlopen( "http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}".format(city, api_key)).read())[2:-1]) info = weather["weather"][0]["descri...
9d977a95f51ec4f424e506438034542378d767be
Larryjianfeng/tricks
/py_classes.py
1,682
3.75
4
from functools import wraps class father: x = 1 def __init__(self, y, z): self.y = y self.z = z class child(father): x = 1 def __init__(self, y, z): super().__init__(y, z) self.w = self.y + self.z # print(dir(father(1, 2))) # print(dir(child(1, 2))) class meta(typ...
1e96763245ab65c1568641a3395421d5d778a65f
olber027/AdventOfCode2020
/Day_16/Part2.py
3,018
4.1875
4
''' Now that you've identified which tickets contain invalid values, discard those tickets entirely. Use the remaining valid tickets to determine which field is which. Using the valid ranges for each field, determine what order the fields appear on the tickets. The order is consistent between all tickets: if seat is t...
805e93a3a488efd8fe6ba4a32c2e7e5d897cd984
olber027/AdventOfCode2020
/Day_06/Part2.py
1,684
4.09375
4
''' As you finish the last group's customs declaration, you notice that you misread one word in the instructions: You don't need to identify the questions to which anyone answered "yes"; you need to identify the questions to which everyone answered "yes"! Using the same example as above: abc a b c ab ac a a a a ...
2acdf995ae4a9ccf2712c4871a61a4071de34627
olber027/AdventOfCode2020
/Day_05/Part2.py
1,436
3.734375
4
''' Ding! The "fasten seat belt" signs have turned on. Time to find your seat. It's a completely full flight, so your seat should be the only missing boarding pass in your list. However, there's a catch: some of the seats at the very front and back of the plane don't exist on this aircraft, so they'll be missing from ...
a4373ec4c48caccf545df482ac8279493922c233
MahanMehrvarz/where-ShHe-Goes
/program.py
3,020
3.59375
4
from utility import * count=0 last_message=finding_last_message() last_id=finding_last_id() d1=5 d2=20 while True: location=get_location() c=False a=False b=False d=False print location print "1st while" print "first location", location while last_id!=finding_last_id(): print...
23f640fe1d871a6deecf0b8aa85a5992f10d98f1
alexa984/python101
/week8/deep_find.py
388
3.609375
4
def deep_find(data, key): for k, v in data.items(): if k==key: return v elif type(v) is list: for i in v: temp=deep_find(i, key) if temp is not None: return temp elif type(v) is dict: temp = deep_find(v,...
92ff3253fdd43dda288cfef40b972eb4fae425b2
alexa984/python101
/week4/CarRacing/car_tests.py
524
3.875
4
import unittest from car import Car class TestCar(unittest.TestCase): def test_create_valid_car(self): car = Car('Volswagen', 'Passat', 230) def test_create_car_with_invalid_speed(self): with self.assertRaises(AssertionError): car = Car('VW', 'Passat', 'NaN') def test_car_str(...
86ab251e5fe3d3b21be5e7438cb0a2f667746c92
alexa984/python101
/design patterns/computer_factory.py
888
3.578125
4
class Computer: _RAM = 0 _HDD = 0 _CPU_cores = 0 def __str__(self): return "RAM: {}GB, HDD: {}GB, CPU: {} cores". format(self._RAM, self._HDD, self._CPU_cores) def get_RAM(self): return self._RAM def get_HDD(self): return self._HDD def get_CPU(self): return...
9a4db451c2354ede9b14c55edac9a4788dc53552
alexa984/python101
/week2/gas_stations.py
392
3.875
4
def gas_stations(distance ,tank_size, stations): result = [] distance_traveled=0 while True: if distance_traveled + tank_size >= distance: break gas_station = max([station for station in stations if station <= distance_traveled + tank_size]) result.append(gas...
3bceef2d5c52ad9cc865e9784590151d91b14ba0
alexa984/python101
/week2/elevator_trips.py
588
3.640625
4
def elevator_trips(people_weight, people_floors, elevator_floors, max_people, max_weight): trips = 0 current_weight = 0 start = 0 for index, person_weight in enumerate(people_weight): current_weight+= person_weight if current_weight > max_weight or len(people_weight[start:index]) >= max_...
7edf3e2666a3fbbb26fcb00356d91d97e10cb287
alexa984/python101
/week4/CarRacing/driver.py
268
3.859375
4
from car import Car class Driver: def __init__(self, name, car): if type(car) == Car: self.name = name self.car = car else: raise TypeError() def __str__(self): return self.name + ' ' + str(self.car)
242e707001cdde5545e114b2cbfacda90d05abfb
song-na-min/py_lab2
/my_pkg/binary.py
277
3.9375
4
#!/usr/bin/python3 def binary(num): d_num=0 b_str=str(num) for i,digit in enumerate(b_str): d_num+=int(digit)*pow(2,len(b_str)-1-i) o_num=oct(d_num) h_num=hex(d_num) print("oct>",o_num) print("dec>",d_num) print("hex>",h_num) if __name__== '__main__': print(" :")
7d3de3b59c6008d7e57adf548cb3d8263f6ba806
gad26032/python_study
/lesson_8_9/homework.py
230
3.640625
4
secretword = 'мир' letter = '' blanks = '_' * len(secretword) word = input("Введите букву") for i in range(len(secretword)): if secretword[i] in letter: blanks = blanks[:i] + secretword[i] + blanks[i+1:]
29526fcdd60504828e5543c926f5f7435a3991e6
mattrost/Graph-Implementation
/ud_graph.py
14,407
3.96875
4
# Course: CS261 - Data Structures # Author: Matthew Rost # Assignment 6: Graph Implementation (Portfolio Assignment) # Description: Implementation of an Undirected Graph using adjacency # list. This data structure will have the following methods: # add_vertex(), add_edge(), remove_edge(), remo...
cdacc8f0adeea4aab139c8bb9d714415fc294c9a
BryceBoley/PythonExercises
/Exercise_2.py
1,059
4.28125
4
# getting user input and checking that it is a number and not zero gas = input("\nWelcome to the fun conversion tool!\n\nPlease enter a number to represent gallons of gasoline: ") while not gas.isdigit() or int(gas) == 0: gas = input("A number you numskull, not a letter or zero!\nEnter your number") # math for con...
244a026864a7ba0b7b5f0b10214aff44bcc9540d
cedouiri/holbertonschool-higher_level_programming
/0x0B-python-input_output/9-add_item.py
469
3.609375
4
#!/usr/bin/python3 import sys load_from_json_file = __import__("8-load_from_json_file").load_from_json_file save_to_json_file = __import__("7-save_to_json_file").save_to_json_file """ a script that adds all arguments to a Python list, and then save them to a file """ filename = "add_item.json" try: p_list = load_f...
17d7c768f024c4031342edc3ac239551149393f0
cedouiri/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
356
3.8125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) s = "Last digit of" ld = number % 10 if number < 0: ld = abs(number) % 10 ld *= -1 if ld > 5: print(s, number, "is", ld, "and is greater than 5") elif ld == 0: print(s, number, "is", ld, "and is 0") else: print(s, number, "is", ...
2a34b1d2d20411963f6ede7a02fe22e6463f27d9
cedouiri/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
194
4.03125
4
#!/usr/bin/python3 def uppercase(str): for i in str: num = ord(i) if num > 96 and num < 123: num -= 32 print("{}".format(chr(num)), end='') print("")
862b50bff7df27dd18422a063ac15fa17e53cda7
cedouiri/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
167
4
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): for values in sorted(a_dictionary): print("{}: {}".format(values, a_dictionary.get(values)))
f5219a45a921b7aaf15fc4ed6283a937f04eef66
himraj123456789/competitive-programming-
/mini max.py
578
3.671875
4
def count_valleys(n,t): t=str(t) i=0 sum1=0 valley=0 while(i!=len(t)): x=t[i] if(x=='U'): temp=sum1 sum1=sum1+1 if(sum1==0 and temp ==-1): valley=valley+1 if(x=='D'): te...
4ff5960dcadb19840c5b87efff87a21d9e544234
himraj123456789/competitive-programming-
/plus_minus.py
715
3.734375
4
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): arr.sort() pos=0 neg=0 zero=0 for i in range(0,len(arr)): if(arr[i]>0): pos=pos+1 if(arr[i]<0): neg...
758bf5f539da43778f4222d9f4a7cd59384e36a8
GBLMalachias/ValidadorCPF
/Validador_CPF.py
2,584
3.78125
4
""" Validador de CPF! """ def valida_digitos(cpf_novo): soma = 0 regressivo = 11 qtd = len(cpf_novo) if qtd == 9: for n in range(qtd): regressivo -= 1 mult = int(cpf_novo[n]) * regressivo soma = soma + mult elif qtd > 9: for n in...
66a8eaf6df6215fb7cb642e43bf74f36b6570fdb
CogitoNTNU/vicero
/vicero/algorithms/mcts.py
3,899
3.5625
4
import numpy as np import math import pydot # for visualizing the tree # MCTS (Monte Carlo Tree Search) is an algorithms # that plans ahead, estimating Q-values based on # "rollouts", which are simulated episodes. # This specific implementation is written for two-player # zero-sum games, but should be generalized to...
7a92d1f4692def8f391d1b7c0dd6b08db5941f9f
yobleck/vroom
/car.py
3,257
3.703125
4
import math; pi = math.pi; import time; class car(): def __init__(self): self.position = (200,200); #meters self.rotation = (1,0); #2D vector self.turn_speed = 2*pi; #m/s self.velocity = 100; #2D vector m/s self.mass = 1000; #kg self.size = (20,30); #px ...
cc4246fccbfe84ceb83502c871d8d10ca85e1625
pphubgit/python-2110101
/recursive-ME/recursive-test-no-time.py
2,080
3.75
4
#From internet #ให้สุ่มจำนวน 3 หลักขึ่นมาโดยจะหยุดสุ่มเมื่อซ้ำจำนวนเดิม แล้วให้แสดงค่าที่ซ้ำออกมา #normal process ''' 1.สุ่มตัวเลข 2.เอาเลขที่สุ่ม ไปค้นใน set 3.เช็คว่าซ้ำหรือไม่ ถ้าซ้ำ ให้น้ำค่านี้ไปใช้ ถ้าไม่ซ้ำ ให้ สุ่มเลขใหม่อีกครั้ง 4.เอาเลขที่สุ่มได้จากข้อ 4 ที่อยู่ในเงื่อนซ้ำกับของเดิม ไปเช็คกับ database ...
f17af59f6fce32e5f27d6b2e15cf5108bfff0356
pphubgit/python-2110101
/clique-clip-lecture/final/48-tuple.py
321
3.953125
4
#Tuple สร้างแล้วเปลี่ยนไม่ได้ programmer เรียก a=(1,2,3,4) a[0]--> 1 a[1:3] --> (2,3) list_of_tuple=[] list_of_tuple.append(a) --> [(1,2,3,4)] list_of_tuple.append((1,2)) --> [(1,2,3,4),(1,2)] #หลายชนิดตัวแปร g=('what',12,2.04)
c93dc777cf687fa36d79db956d9cf9292eaff5f8
pphubgit/python-2110101
/clique-clip-lecture/final/52-get-key-value-item-from-dicy.py
440
4.3125
4
#key value item in python s.keys() #--> คืน list ของ key ออกมา s.values()#--> list ของ values ออกมา s.items() #--> list ของ [(key,value),(key2,value2)] ออกมา #ประโยชน์ for key in s.keys(): # ถ้าไม่ได้ใส่ เป็น for a in s เหมือน for a in s.keys() print(key) for (k,v) in s.items(): print('key=',k,'value=...
787588c98bcf82a3c9cdae1fffcc67310a6af064
pphubgit/python-2110101
/CH03_02.py
138
3.5625
4
n=int(input()) avg=0.0 kb=input() kb=kb.split() total=0 for i in range(0,n): total=total+float(kb[i]) avg=total/n print(avg)
adf742422726144d7869bbe27983cf9f9b8f7724
poschi3/AdventOfCode2015
/day02/day02.py
1,023
3.5625
4
class Present: def __init__(self, l, w, h): self.l = l self.w = w self.h = h def area(self): a1 = self.l * self.w a2 = self.w * self.h a3 = self.h * self.l extra = min(a1, a2, a3) return 2 * a1 + 2 * a2 + 2 * a3 + extra ...
e664639f6f39b53c6bc1793021fc631cff5bcbee
EthanPassinoFWCS/Chapter15Anthis
/TIY8.py
1,253
3.625
4
from plotly.graph_objs import Bar, Layout from plotly import offline from random import randint class Die: """A class representing a single die.""" def __init__(self, num_sides=6): self.num_sides = num_sides def roll(self): return randint(1, self.num_sides) # Create a D6 die_1 = Die(...
6ca4f41580395cfaabebda4f0a52cf9feea225f1
houssemFat/useful
/convert_text_file_to_json.py
952
4.09375
4
""" Code that convert a txt file line by line file to json format example of text file `Reading# Mote-ID Humidity Tepmrature Label 1 1 45.93 27.97 0 1 1 45.93 27.97 0 ...` """ import json data = { 'head' : [], 'data' : [] } # split line def push_line (line) : line_data = line.split () #print line_data...
1429b690d10a055ef3dfcdb7fd855470b5c4a310
Teldrin89/DBPythonTut
/LtP11_custom_exception.py
991
4.15625
4
# it is possible to create a custom exception - it has to be # inherited from the exception class # create a new class for handling custom made exception - use # inheritance of exception build in class class DogNameError(Exception): # initialize the class with init function def __init__(self, *args, **kwargs)...
50b4bc46338d0e7ff766988ea9ed05f565aaa7a0
Teldrin89/DBPythonTut
/Problem_23.py
1,445
4.28125
4
import re # Problem 23: # Use regular expressions to match email addresses # from the list with set rules for what is an email # address (just find how many there are): # 1. 1 to 20 lowercase and uppercase letters, numbers, # plus ._%+- symbols # 2. An @ symbol # 3. 2 to 20 lower case and uppercase letters, numbers...
21c8f84e8b76eff91026f0c155d2a552952b8edb
Teldrin89/DBPythonTut
/LtP13_list_comprehension.py
1,970
4.8125
5
# list comprehension is going to execute an expression # against an iterable - much as "map" and "filter" # while a list comprehension is powerful it has to be used # with cautious to not get overcomplicated # use different methods to obtain the same list # of values: multiplication by 2 using map and lc # a) map prin...
1eea9b6469b1a647a4ee2787e55574b09d18448f
Teldrin89/DBPythonTut
/LtP18_re_cheat_sheet.py
1,307
3.765625
4
# import re # [] : Match what is in the brackets # [^ ] : Match anything not in the brackets # ( ) : Return surrounded submatch # . : Match any 1 character or space # + : Match 1 or more of what proceeds # ? : Match 0 or 1 # * : Match 0 or More # *? : Lazy match the smallest match # \b : Wo...
4630af63f57140b7e4538125cf84551019ea4cf1
Teldrin89/DBPythonTut
/LtP2.py
197
4.125
4
# Introduction to loops: for for i in [2, 4, 6, 8, 10]: print("i = ", i) # This for loop will go from 0 to 9 (10 integers) for i in range(10): print("i = ", i) i = 2 print((i % 2) == 0)
bc22d61afc37ca167a7550f922397c394f9c4d9a
Teldrin89/DBPythonTut
/Problem17.py
1,317
4.375
4
# Problem 17: # - create a file named "mydata2.txt" - put any type of data # - use methods from LtP8 how to open a file without "with" # (open in "try" block) # - catch FileNotFoundError # - in "else" print contents of the file # - in finally print out some msg that will always be on screen # - try to open nonexisten...
58684c61c8d6dcecc16fb15542f46ef9a6dcffe0
Teldrin89/DBPythonTut
/LtP14_threads_example.py
2,750
4.40625
4
# example of threads usage: whenever threads are used # it is possible to block one of the threads - the # real world script that can utilize this option # will cover a modeling of bank account: let's say # that there is 100$ in the account but there are 3 # different people that can withdraw money from that # account,...
02fa6674a462400000f759f068dea40195c9cf3b
Teldrin89/DBPythonTut
/Problem3.py
281
3.984375
4
# Problem3: Print odds from 1 to 20 # Use for loop and range (also if and modulus) # For loop to run through list from 1 to 21 for i in range(1, 21): # Use modulus to check that result is NOT EQUAL to 0 if i % 2 != 0: # Print the odds print(" i = ", i)
56ecd290945ebaceecad8e9ea69386558474eb74
Teldrin89/DBPythonTut
/LtP1.py
999
4.25
4
# Ask the user to input their name and assign # it to a variable named name name = input('What is your name ') # Print out hello followed by the name they entered print('Hello ', name) # Ask the user to input 2 values and store them in variables # num1 and num2 num1, num2 = input('Enter 2 numbers: ').split() # Co...
6611c326107ab4cf310d86b41fcada7de86da8d3
Teldrin89/DBPythonTut
/Problem2.py
625
4.03125
4
# Problem2: If age is 5 - go to kindergarten # Ages 6 through 17 goes to grades 1 through 12 # If age is greater then 17 say go to college # Try to complete with 10 or less lines # My solution, DB seem to be similar - one more variable defining # grade in his solution age = eval(input("Please provide your age: ")) if ...
45f2072b3cf0ab1858f85048ebf2c1672e904e6c
Teldrin89/DBPythonTut
/LtP6_lists.py
1,900
4.21875
4
import random import math # list generated similar as to in problem 11 num_list = [] for i in range(5): num_list.append(random.randrange(1, 10)) # sorting list num_list.sort() # reverse sorting num_list.reverse() # change value at specific index -in this example it inserts # number "10" at index 5 num_list.inser...
f1cd6489d228c328b9ff9fc8d43d7a4b570870ab
saiyandapalli/CapitalOne-BikeData
/Source Code/CapitalOne+Data+Analysis.py
17,324
3.53125
4
# coding: utf-8 # # Capital One: Bike Data Analysis # ## Cleaning and Exploring Data with Pandas # ### Author: Sai Yandapalli # # # **Introduction** # # Bike shares are becoming increasingly common in cities in the United States. Commuters have been using bike sharing as a method of transportation for the flexibil...