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
d11e3a13abf887f2d150f6c23aa269f90bec5833
ctl106/AoC-solutions
/2020/12/solution2.py
1,787
3.765625
4
#!/usr/bin/env python3 import sys from math import atan2, sin, cos, radians ACTIONS = { "north": "N", "south": "S", "east": "E", "west": "W", "left": "L", "right": "R", "forward": "F" } def rotate(point, direct, deg): if direct == ACTIONS["right"]: deg = 360 - deg rad = radians(deg) rpoint = atan2(p...
73d430c4889d663384edfed2301d211f1fea41eb
Namrata-Choudhari/FUNCTION
/naman.py
5,983
3.796875
4
# print ("NavGurukul") # def say_hello(): # print ("Hello!") # print ("Aap kaise ho?") # say_hello() # print ("Python is awesome") # say_hello() # print ("Hello…") # say_hello() # print("namrata") # #length # name_list=["fiza","shivam","imtiyaz","deepanshu","rahman"] # print(len(name_list)) # def definition_s...
f73472838e6ab97b564a1a0a179b7b2f0667a007
Namrata-Choudhari/FUNCTION
/Q3.Sum and Average.py
228
4.125
4
def sum_average(a,b,c): d=(a+b+c) e=d/3 print("Sum of Numbers",d) print("Average of Number",e) a=int(input("Enter the Number")) b=int(input("Enter the Number")) c=int(input("Enter the Number")) sum_average(a,b,c)
8cf7d33af26683fb2439610a1eb725e4299c3a0b
alters-mit/sticky_mitten_avatar
/sticky_mitten_avatar/transform.py
1,428
3.6875
4
import numpy as np class Transform: """ Transform data for an object, avatar, body part, etc. ```python from sticky_mitten_avatar import StickyMittenAvatarController c = StickyMittenAvatarController() c.init_scene() # Print the position of the avatar. print(c.frame.avatar_transform....
e1f42b2a424458a27f783078cfa99b8fa4e2bfb1
cairnsh/diffusion-limited-aggregation-simulator
/util_sequence.py
753
3.59375
4
import numpy as np # this is 1/ζ(2) = 6/pi^2 = 1/(1 + 1/4 + 1/9 + ...). INVERSE_ZETA_2 = 6 / np.pi**2 def _slowly_increasing_sequence(): "A sequence that sums to 1, but decreases slowly." index = 1 next_highest_power_of_2 = 2 lg_nhp2 = 1 while True: yield 2 * INVERSE_ZETA_2 / next_highes...
b6c0dc8523111386006a29074b02d1691cf1e054
shivigupta3/Python
/pythonsimpleprogram.py
1,709
4.15625
4
#!/usr/bin/python2 x=input("press 1 for addition, press 2 to print hello world, press 3 to check whether a number is prime or not, press 4 for calculator, press 5 to find factorial of a number ") if x==1: a=input("enter first number: ") b=input("enter second number: ") c=a+b print ("sum is ",c) if x==2: print(...
9aa1b81bcb80494ea9b0c0b4a728a3981723fa43
eecs110/winter2019
/course-files/practice_exams/final/dictionaries/01_keys.py
337
4.40625
4
translations = {'uno': 'one', 'dos': 'two', 'tres': 'three'} ''' Problem: Given the dictionary above, write a program to print each Spanish word (the key) to the screen. The output should look like this: uno dos tres ''' # option 1: for key in translations: print(key) # option 2: for key in translations.keys(...
1422c7ddfe16c6e81586dde3db6509e61bea09da
eecs110/winter2019
/course-files/lectures/lecture_11/04_dictionary_lookup_from_file.py
687
3.875
4
import json import sys import os # read lookup table from a file: dir_path = os.path.dirname(sys.argv[0]) file_path = os.path.join(dir_path, 'state_capitals.json') f = open(file_path, 'r') capital_lookup = json.loads(f.read()) def get_state_capital(lookup, state): return lookup[state] # use lookup table to ans...
f00691a55b3785740316a226fef0c469e6df69a0
eecs110/winter2019
/course-files/lectures/lecture_11/07_twitter_data_print_all_status_updates.py
525
3.625
4
import urllib.request import json import pprint # module that makes it easier to print and look at dictionaries # Challenge: write a program that prints all of the status updates search_term = input('Please enter a search term (defaults to "northwestern"): ') if search_term == '': search_term = 'Northwestern' ur...
1f9e30f1591d59011b140c9ef8801fd51468b92a
eecs110/winter2019
/course-files/practice_exams/midterm/exam1_answers.py
3,235
4.09375
4
def _print_title(title): print('\n') print('#' * len(title)) print(title) print('#' * len(title)) def problem_1a(): # infinite loop: _print_title('Problem 1.a.') print('infinite loop!') return # i = 0 # while i < 3: # if i % 2 == 0: # continue # print...
40609fa2337181ed35ca0138a9f77309582b594d
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/14_delete.py
382
3.5625
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute( 'DELETE from airlines WHERE id = ?;', (999,) ) conn.commit() # don't forget to save! # Verify that it worked! cur.execute('SELECT * FROM airlines WHERE id = ?;', (999,)) res...
f008005f7a3fb2e5625b59469a773c95db17fc39
eecs110/winter2019
/course-files/practice_exams/midterm/conditionals/exercise_03.py
460
3.515625
4
def print_message(key): if key == 0: print(key, ':', 'zero') elif key == 1: print(key, ':', 'one') elif key < 10: print(key, ':', 'less than 10') elif key == 10.0: print(key, ':', 'equal to 10.0') elif key > 10: print(key, ':', 'more than 10') else: ...
ae5cc492fa7ce14c1345c0c97f322723ae8781ba
eecs110/winter2019
/course-files/lectures/lecture_05/d2_my_module.py
1,340
3.609375
4
''' Things to notice: 1. These are all function defintions, but there are no function calls. In other words, none of these functions will run unless they are invoked. 2. Modules can import other modules. Note that this module is making use of the os module ''' import os def get_hypotenus...
bb101394bc45bedac101c7f5b4d55a57d8283005
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/11_query_group_by_having.py
383
4.03125
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute(''' SELECT country, count(country) as airline_count FROM airlines GROUP BY country HAVING airline_count > 60 ORDER BY airline_count desc; ''') results = cur.fetchall...
ade76ca3d9e3af9cf6b296c611ba3f591eba4bd3
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/01_list_available_tables.py
420
3.578125
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") # put the results of your query into the results variable: results = cur.fetchall() cur.close() conn.close() print(results) # ju...
d6312ccdac607574037b7e0c7fcd3bf1d58b515f
eecs110/winter2019
/course-files/practice_exams/midterm/operators/exercise_02.py
112
3.828125
4
# What will the output of this program be? result = 2 ** 2 * 3 // 5 + 2 print(result) print(type(result)) # int
0fa9fae44540b84cb863749c8307b805e3a8d817
eecs110/winter2019
/course-files/lectures/lecture_03/demo00_operators_data_types.py
327
4.25
4
# example 1: result = 2 * '22' print('The result is:', result) # example 2: result = '2' * 22 print('The result is:', result) # example 3: result = 2 * 22 print('The result is:', result) # example 4: result = max(1, 3, 4 + 8, 9, 3 * 33) # example 5: from operator import add, sub, mul result = sub(100, mul(7, add(8...
b485405967c080034bd232685ee94e6b7cc84b4f
eecs110/winter2019
/course-files/practice_exams/final/strings/11_find.py
1,027
4.28125
4
# write a function called sentence that takes a sentence # and a word as positional arguments and returns a boolean # value indicating whether or not the word is in the sentence. # Ensure that your function is case in-sensitive. It does not # have to match on a whole word -- just part of a word. # Below, I show how I w...
d33973dc396594314d8c3d4c47c971df79b655fa
anoopo/PracticePython
/RockPaperScissors.py
1,804
4.0625
4
"""Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) Remember the rules: Rock beats scissors Scissors beats paper Paper beats rock """ def winner(user1, ...
85c1ce46a0f2c9f8b3fcae258d9d786032bcc04c
gabrielle-nunes/exercicios-em-py
/Exercícios em Python/Fatura simples.py
997
3.921875
4
##Exercício simulando uma fatura. fatura = [] total = 0 continuar = 's' valid_preco = False while continuar == 's': prod = input("Digite o nome do produto: ") while valid_preco == False: ##Este While faz a conversão do preço para float através do Try. preco = input("Digite o valor do produto: ") ...
f7e7bf0141b7aace572206a7647f640233d477b9
kei52/kei_test
/image_processing/script/histogram.py
455
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import rospy mu, sigma = 100, 15 print "mu:{0},sigma{1}".format(mu,sigma) x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(1,1,1) #binsの設定 bins=100 ax.hist(x, bins) print "bins{0}".format...
fdc2fb28653de3edb53589ef5753ca547a98f9cd
tbrendel/beyond-blocks-competition
/q3.py
375
3.625
4
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def lpf(x): lpf = 2; while (x > lpf): if (x%lpf==0): x = x/lpf lpf = 2 else: lpf+=1; print("Largest Prime Factor: %d" % (lpf)); def main(): x = long(raw_input("Input long int:")) lp...
c2c41dbf8728fe5c3e4fd44f46620938ef8b9398
amandameganchan/advent-of-code-2020
/day23/day23code.py
1,791
3.609375
4
#!/bin/env python3 import sys import re from collections import defaultdict def solution(filename): data = [] with open(filename) as f: for x in f: data.extend(list(x.strip())) data = list(map(int, data)) return collectLabels(playGame(data)) def collectLabels(final_cups): # start at 1 and collect cups cloc...
924a34f570b3d5f11f8941d2245f8c85b6509a54
amandameganchan/advent-of-code-2020
/day08/day8code2.py
1,975
3.671875
4
#!/bin/env python3 """ change one jmp instruction to nop or one nop instruction to jmp in order to fix the instructions and let the program terminate without getting into an infinite loop """ import sys import re from collections import defaultdict def solution(filename): # read in input data as tuples of instruct...
40c91a64b489ecc92af2ee651c0ec3b48eba031e
amandameganchan/advent-of-code-2020
/day15/day15code.py
1,999
4.1875
4
#!/bin/env python3 """ following the rules of the game, determine the nth number spoken by the players rules: -begin by taking turns reading from a list of starting numbers (puzzle input) -then, each turn consists of considering the most recently spoken number: -if that was the first time the number has been spoke...
1313502aaf91d18e16dee34d46296c53c17b2d26
AlexSChapman/GeneFinder
/gene_finder.py
7,966
3.625
4
# -*- coding: utf-8 -*- """ GENE FINDER PROJECT 1 @author: ALEX CHAPMAN """ import random from amino_acids import aa, codons, aa_table from load import load_seq dna_master = load_seq("./data/X73525.fa") def shuffle_string(s): """Shuffles the characters in the input string NOTE: this is a helper functio...
1747b7161f1f43f059290c8f5f132d5e211b265c
nriteshranjan/Deep-Learning-with-PyTorch
/Intro to PyTorch - Working with single layer Neural network.py
1,211
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 14:57:32 2020 @author: rrite """ #Working with single layer neural network import torch def activation(x): return (1 / (1 + torch.exp(-x))) #Generating some random number torch.manual_seed(7) #manual_seed : Sets the seed for generating random numbers. #Features a...
4a0cd5391dd2af4b16f229dd21829703adedad04
Tejjy624/PythonIntro
/areacodeDemo.py
963
3.953125
4
# main function first building the dictionary # and then calls a function to lookup the dictionary def main(): areaCodeToState = readAllAreaCodes() # print(areaCodeToState) lookupAreaCodes(areaCodeToState) def readAllAreaCodes(): mydict = {} infile = open("areacodes.txt") for linerecord in inf...
1321c47e1ea033a5668e940bc87c8916f27055e3
Tejjy624/PythonIntro
/ftoc.py
605
4.375
4
#Homework 1 #Tejvir Sohi #ECS 36A Winter 2019 #The problem in the original code is that 1st: The user input must be changed #into int or float. Float would be the best choice since there are decimals to #work with. The 2nd problem arised due to an extra slash when defining ctemp. #Instead of 5//9, it should be ...
d019aa1049824a7b977095881b9e5fc2d68ae4dd
Tejjy624/PythonIntro
/HW5pt2.py
1,413
3.828125
4
# Assignment 5 #Tejvir Sohi #ECS 32A Fall 2018 # function that reads population file and builds dictionary def makePopDictionary(): inf = open("world_population_2017.tsv","r") mydict = {} for line in inf: line = line.strip() lineitems = line.split('\t') country = lineitem...
56c48e3280da40b79d589a2cbd7028af0e57d2ca
luojiyin1987/codewars-python
/big_int.py
2,047
3.84375
4
# -*- coding: utf-8 -*- def arabic_multiplication(num1, num2): num1_list = [int(i) for i in str(num1)] num2_list = [int(i) for i in str(num2)] int_martix = [[i * j for i in num1_list] for j in num2_list] str_martix = [map(convert_to_str, int_martix[i]) for i in range(len(int_martix))] ...
819ea31423272f5f95569add5a54e6771a3b3ff1
elohalili/python-course
/03_loops.py
1,158
3.765625
4
#loops item = 'item' for item in range(0, 10): print(item) print(item) print('___________________________') my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total = 0 for num in my_list: total += num print('The total is: ', total) print('___________________________') for i in enumerate({'name': 'Elo', 'age': 23...
4d6ebcb9aa8cea289eed76c0c44a940d291fc75a
elohalili/python-course
/01_data_types.py
675
3.796875
4
# something = input('Tell me something:') # print('\'' + something + '\' is all you got ?') # print(type(something)) # print('You can do better than this :D ') # print(bin(15)) # name = 'Name' # surname = 'Surname' # age = '23' # birht_year = input('What year were you born? \n') # age = 2020 - int(birht_year) # pri...
953f9e50f7a1676a0256401697402d64a3ea66e6
elohalili/python-course
/05_oop.py
1,218
3.671875
4
class PlayerCharacter: ''' PlayerCharacter Docstring: this part should be the documentation for this class ''' #Class Object attribute (static) membership = True # this is the constructor # self it's the same equivalent to 'this' in js code def __init__(self, name, age=0): #...
021f1522ab76c4b8da74cb29360c7bcfe8fc33f3
mere-human/core-python-ex
/7/7.10/rot13.py
1,430
3.984375
4
#!/usr/bin/env python3 ''' 7.10 Encryption. Using your solution to the previous problem, and create a "rot13" translator. "rot13" is an old and fairly simplistic encryption routine whereby each letter of the alphabet is rotated 13 characters. Letters in the first half of the alphabet will be rotated to the equivalent l...
001a5bc5b5e3cd0355d90d29800fd842fb23ec08
mere-human/core-python-ex
/13/13.20/time60.py
3,808
4.15625
4
''' 13-20. Class Customization. Improve on the time60.py script as seen in Section 13.13.2, Example 13.3. a. Allow "empty" instantiation: If hours and minutes are not passed in, then default to zero hours and zero minutes. b. Zero-fill values to two digits because the current formatting is undesirable. In the case be...
f78ccdea33a9a4e5d6bfed05913070eaa143e956
mere-human/core-python-ex
/9/9.18/findbyte.py
784
4.03125
4
''' 9-18. Searching Files. Obtain a byte value (0-255) and a filename. Display the number of times that byte appears in the file. ''' import sys def main(): if len(sys.argv) != 3: raise Exception('2 arguments for file name and byte value (0-255) are expected') file_name = sys.argv[1] byte_val = in...
606626a3d339adf0eb09008d2004f797f1dcf652
Beeze/AI-class-Projects
/p2/frogs_toads.py
7,494
4.09375
4
import a_star import math ''' Spaces is an class which holds all the logic for altering each space in our puzzle. ''' class Spaces(object): def __init__(self, spaces): if isinstance(spaces, Spaces): self.spaces = spaces.spaces else: self.spaces = spaces ''' ...
1d5f8fbdafe41e9b090afb61a83894df598e5574
smithdanielle/p4n2014
/code/ex2Functions.py
897
3.59375
4
# Load psychopy modules from psychopy import visual, event, core # Initialise stimuli win = visual.Window(size=[500, 500]) textStim = visual.TextStim(win) # Messages welcome = 'hi and welcome to this experiment' instruction = 'really, there\'s not much to do. We just show a bunch of messages. Press RETURN to continue....
4745ae44a167d49647d44c2a57dcacc9ed27b75e
cwz3/hangman
/Hangman.py
5,622
4.375
4
''' Description: You must create a Hangman game that allows the user to play and guess a secret word. See the assignment description for details. @author: charles cwz3 ''' def handleUserInputDifficulty(): ''' This function asks the user if they would like to play the gam...
6b41212668d616636c972ffe7487e84dee359ac2
lucaalexandre/Estudo_de_Revisao_parte1
/Exercicio5.py
87
3.578125
4
idade = int(input("Digite sua idade: ")) nova = "parabens" + idade + "anos" print(nova)
eac8927556f8341bdefa530491ce46571a3cf018
Saurav-Paul/Codeforces-Problem-Solution-By-Saurav-Paul
/A - Hotelier.py
355
3.546875
4
room = [0]*10 def putInLeft(): for i in range(0,10): if room[i]==0: room[i]=1 break def putInRight(): i = 9 while i>=0: if room[i]==0: room[i]=1 break i -= 1 n = int(input()) s = input() #print(room) for x in s: if x=='L': putInLeft() elif x=='R': putInRight() else : room[int(x)]=0 ...
6c31e0d57b3e232465391bc8455a311dc03a5658
kadhumalrubaye/datastructure
/selection_sort.py
677
3.75
4
#min #compare #swap #[6,1,8,3,10,5] # def swap(a,b): # temp=a # a=b # b=temp #[9,1,8,2,7,3] def selection_sor(lst): length=len(lst) # min=min(lst) #[9,1,8,2,7,3] #[9,1,8,2,7,3] #[1,8,2,7,3,9] pass1 here we need min #-------------------- #i #[9,1,8,2,7,3] min =9 ...
5f6c090cb83401fae49f3d09aa692d4a0cc450cf
Mgomelya/Study
/Алгоритмы/Быстрая_сортировка.py
890
4.09375
4
from random import randint def partition(array, pivot): less = [i for i in array if i < pivot] # элементы array, меньшие pivot center = [i for i in array if i == pivot] # элементы array, равные pivot greater = [i for i in array if i > pivot] # элементы array, большие pivot return less, center, grea...
44d18b17cdd57a20036f12ec231ce8d9ec1f7157
Mgomelya/Study
/Алгоритмы/Очередь.py
2,073
4.1875
4
# Очередь основана на концепции FIFO - First in First out class Queue: # Очередь на кольцевом буфере, Сложность: O(1) def __init__(self, n): self.queue = [None] * n self.max_n = n self.head = 0 self.tail = 0 self.size = 0 # В пустой очереди и голова, и хвост указываю...
db41b3479156bb3f7cf464aa33b72cb8ad94c128
Mgomelya/Study
/Алгоритмы/Лексикографическая_сортировка.py
2,869
4.09375
4
print("апельсин" < "арбуз") # True st = 'A B C Hello world!' for i in st: print(f'Порядкой номер в Юникоде символа "{i}" - {ord(i)}') print([2, "апельсин"] < [2, "арбуз"]) # Длина слов чисел: ноль, один, два, три ... digit_lengths = [4, 4, 3, 3, 6, 4, 5, 4, 6, 6] # Компаратор [ - <длина слова>, <само число>] ...
46de0528be699ffe3a1e28e0d6f8aa32bbcf463f
Mgomelya/Study
/Поиск_согласных_гласных.py
1,280
3.78125
4
str1 = 'asdxzczxaaaaaaaaa' str2 = 'adsszxxzcxzc' key = 'C' def func(str1, str2, key): if key == 'C': vowels_1 = 0 consonants_1 = 0 vowels_2 = 0 consonants_2 = 0 for i in str1: letter = i.lower() if letter == "a" or letter == "e" or \ ...
81548f1facdeeb06bdfe0ede204f1718d0315b59
Mgomelya/Study
/кол-вопрограммистов.py
527
3.65625
4
n = int(input()) b = n%10 if 0 <= n <= 1000: if 111<=n<117 or 211<=n<217 or 311<=n<317 or 411<=n<417 or 511<=n<517 or 611<=n<617 or 711<=n<717 or 811<=n<817 or 911<=n<917: if 9<=n%100<=19: print(n, "программистов") elif b == 1: print(n, "программист") elif 2<=b<=4: print(...
169a92be719041be83c4a446467626148d4ca1d2
Mgomelya/Study
/Алгоритмы/Связный_список.py
1,794
4.28125
4
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def print_linked_list(node): while node: print(node.value, end=" -> ") node = node.next print("None") # У каждого элемента есть значение и ссылка на следующий элемент списка n3 = No...
8a0f6c4cb3f44d3ed5e008c276ad1242ad9837e5
brillianti/Leetcode
/两数之和.py
1,253
3.625
4
''' #要求: # 给定一个整数数组 nums 和一个目标值 target # 请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 # 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 #给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum ''' nums = [2, 7, 11, 15] target = 9 def twoSum(nums,target): n = len(nums) # 获取...
c8784fb4c3ffb191d8ccc59330856ca3eedbdbbb
brillianti/Leetcode
/回文字符.py
688
3.71875
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ numbers = '1234567890' letters ='abcdefghijklnmopqrstuvwxyz' s=s.lower() #s = s.lower() 全部转小写// s= s.upper() 全部转大写 res='' for i in s: if i in num...
b7b7ff8b95c868475054dd56673d3001e824cde9
luisfe12/Seguirdad
/lab_2/desicfrado_vignere.py
2,497
3.609375
4
def Cifrado_solo_letras(cifrado): contador=0 for i in cifrado: if i == ' ' or i == '\n': continue contador+=1 return contador def modulo_descifrado(p_k, p_c): modulo = p_c - p_k modulo = modulo % 27 return modulo def Clave_completa(clave, modulo...
06ce5b06faf63d5bdebbdb68cf51bf1a6caf2263
hoshitk/pyscripts
/fileio.py
1,056
3.546875
4
# 今のワーキングディレクトリ(作業中のフォルダ) # を調べるために OSモジュールを importします import os # 今のワーキングディレクトリを得て画面に表示します print(os.getcwd()) # 日本語ファイル.txt という名称のファイルを作成し、内容を書き出します f = open('日本語ファイル.txt','w') f.write('日本語\n日本語\n日本語\n ') f.close() # 日本語ファイル.txt を読み込み用にopen して、その内容を表示します f = open('日本語ファイル.txt','r') s = f.read() ...
4abcf19a4d16b07d86789a5e0a63101f15066270
jamesedwarddillard-zz/nfpguesses
/bls_reader/bls_reader.py
2,083
3.609375
4
""" Creating a function which reads in html of a BLS report website and returns the key monthly jobs added as a Report data class """ from bs4 import BeautifulSoup from bls_report_classes import * def nfp_table_finder(report_soup): """ Identifies and returns the proper table on the Employment Situation Release """ ...
11fccca54ba988e9c869f3ade9719e99e7dcf174
JordanRex/yaaml
/src/modules/misc.py
13,080
3.6875
4
# misc functions ############################################################################################################################### ## EDA ############################################################################################################################### import math import numpy as np import ...
61a4b7daf5eb813d75f7998723a80603bd0113c6
zoharh20-meet/y2s19-mainstream-python-review
/part2.py
524
3.921875
4
# Part 2 of the Python Review lab. def encode(x, y): isprime(x,y) if 1 < y < 250 and 500 < x < 1000 : return x*y coded_message = decode(643,5) else: print ("Invalid input: Outside range.") def isprime(x,y): for i in range(2,y): if (y % i) == 0: print (y, "is not a prime number") y+=1 else: pr...
4bef41844a271ef1c0766b6d868bff3a8a96430f
MrAliTheGreat/DesignAlgorithms
/Divide&Conquer/3.py
2,014
3.53125
4
import math def divide_by_degree(coordinates): new_subtree = [] min_y_coordinate = min(coordinates , key = lambda y: y[1]) for coordinate in coordinates: if(coordinate == min_y_coordinate): continue degree = math.atan( (coordinate[1] - min_y_coordinate[1]) / (coordinate[0] - min_y_coordinate[0]) ) * (180 / ...
54a62e36a803799a34caa232742c614c41f05ed0
shindekalpesh/streamlit-bmi
/app.py
2,816
3.59375
4
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import accuracy_score,mean_absolute_error,mean_squared_error import streamlit as st df = pd.read_csv("weight-height.csv") df['Gender'] = df['Gender'].rep...
9ba449e05088c2b51010759f48484b37a3153008
AvaniAnand/Python
/BingoGame.py
909
4.09375
4
print("Welcome to the Bingo Game...\n") print("In the game of Bingo, when a player enters a number") print("it is checked against the following list:") n_bingolist = [7,26,40,58,73,14,22,34,55,68] print(n_bingolist) print("if the number exists in the above list it is crossed out") print("When all the numbers have been ...
d04ead124cbccf3a0a48022ff53e9a9ba5c472e6
archit-55/Python
/problem4.py
298
3.859375
4
#!/usr/bin/python3 import os import string username=input("Enter username:") flag=0 for i in list(username): if i not in string.ascii_letters : print("Incorrect Username!") flag=1 if flag==0 : os.system('sudo useradd'+username) os.system('sudo passwd'+username)
eb0494758c0e4976095ade36025341d9cb3a7131
melnikovay/U2
/u2_z8.py
692
4.15625
4
#Посчитать, сколько раз встречается определенная цифра в #введенной последовательности чисел. Количество вводимых чисел и цифра, #которую необходимо посчитать, задаются вводом с клавиатуры. n = int(input('Введите последовательность натуральных чисел ')) c = int (input ('Введите цифру от 0 до 9 ')) k = 0 while n >...
a1dd8790cc6d7ed8a519d9cb009616e3897760d7
wlizama/python-training
/decoradores/decorator_sample02.py
651
4.15625
4
""" Decorador con parametros """ def sum_decorator(exec_func_before=True): def fun_decorator(func): def before_func(): print("Ejecutando acciones ANTES de llamar a función") def after_func(): print("Ejecutando acciones DESPUES de llamar a función") def wrapper(*a...
1c8b501916260c15d10c94a76ad1868eaccccbf1
wlizama/python-training
/aleatorio.py
1,461
3.765625
4
import random RSTART = 0 RLIMIT = 1024 CNUMS = 1024 def adivinaAleatorio(): numberFound = False randomNumber = random.randint(RSTART, RLIMIT) while not numberFound: numberInput = int(input("intenta un número: ")) if numberInput == randomNumber: print("¡¡¡Encontraste el númer...
a0cfb09711960eb43ed313ce44a408033a67fd39
wlizama/python-training
/Algoritmos/ordenamiento_x_seleccion.py
832
3.65625
4
ARRAY = [48, 84, 2, 12, 54, 10, 32, 44, 1, 78, 65, 8, 27, 81, 76, 62, 15] def swapArray(arr, idx_ant, idx_new): val_ant = arr[idx_ant] arr[idx_ant] = arr[idx_new] arr[idx_new] = val_ant return arr def selectionSort(arr): idx_ini = 0 max_idx = len(arr) for idx_pos_sort in range(idx_ini, ma...
3ab3f91e0eb91e39c3c0436abd372260af0d39a7
Moyosooreoluwa/Simple-SnakeGame-with-Python-Pygame
/SnakeGame.py
4,643
3.6875
4
# I imported the libraries I was going to use. import pygame import time import random # Always have to initialise pygame. pygame.init() # Here I stored the scientific "RGB" format of a number of colours so that if needed I can easily call them as their # colours instead of having to type out the "RGB" form...
0d86df6c0184fc21149405f1a387d36a74173d1f
murrayblake/Computational-Thinking-Project
/Utilities.py
2,163
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 22 15:12:39 2021 @author: Blake Murray & Matt Deiss """ from tkinter import * from tkinter import ttk import pandas as pd import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt import csv def getwi...
fe98d96ca3777e610bb0dd3c99a79319d335924f
s1s1ty/JobShop
/jobshop/simulated_annealing.py
3,713
3.546875
4
from .helper import * import math import random import time class SimulatedAnnealing(object): def __init__(self): pass def __random_schedule(self, j, m): schedule = [i for i in list(range(j)) for _ in range(m)] random.shuffle(schedule) return schedule def __cost(self, j...
1b56fdccad3fbbe05698205721c3bddc9247b71b
JamesVera-Soto/BumbleBee
/speachTextAnalyze.py
436
3.609375
4
""" Speech Recognition text2emotion """ import speech_recognition as sr import text2emotion as te r = sr.Recognizer() with sr.Microphone() as source: print('Speak Anything: ') audio = r.listen(source) try: text = r.recognize_google(audio) print('You said: {}'.format(text)) emot...
11b8a8611760549c100779031f905f45e6f83c04
Rupali59/ProgramSnippets
/minimum_path_to_destination.py
3,006
3.734375
4
# PROBLEM STATEMENT - Given the distance matrix, find the shortest distance and path traced from source to destination. import math import os import random import re import sys def distance_to_destination(source, destination, path_array, distance_covered, path_travelled): # Not the most optimum solution if(so...
89f97d630f3c3c3e4614033c66233bf3facd2997
noelledaley/hb-homework
/skills-dictionaries/skills.py
12,050
4.5625
5
# To work on the advanced problems, set to True ADVANCED = True def count_unique(input_string): """Count unique words in a string. This function should take a single string and return a dictionary that has all of the distinct words as keys, and the number of times that word appears in the string as v...
6da9e9bc2050310c5d6bde6a217378a12bc16e8f
GaganDeepak/PreOpenMarketAnalysis
/2.EveExec.py
990
3.75
4
#!/usr/bin/env python3 #This Program get the market close data for the pre-open stocks for that particular date import pandas as pd from datetime import date from nsepy import get_history #read the pre-open market file to get the stocks symbol pom = pd.read_csv('pom.csv') #create empty dataframe hist = pd.DataFrame() m...
2aed12b43eb3230b69717d981e1a86d33d788c05
mariachefneux/python-challenge
/PyPoll/main.py
2,317
3.890625
4
# Modules import os import csv import sys # Set path for file csvpath = os.path.join('election_data.csv') # Open the CSV with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Read the header row first csv_header = next(csvreader) # Define variables votes_di...
4b11d8d1ea2586e08828e69e9759da9cd60dda23
petermooney/datamining
/plotExample1.py
1,798
4.3125
4
### This is source code used for an invited lecture on Data Mining using Python for ### the Institute of Technology at Blanchardstown, Dublin, Ireland ### Lecturer and presenter: Dr. Peter Mooney ### email: peter.mooney@nuim.ie ### Date: November 2013 ### ### The purpose of this lecture is to provide students with an ...
4abddbae92428bd77a8833967dae19b4e24c4d05
petermooney/datamining
/plotExampleBarChart.py
3,159
4.6875
5
### This is source code used for an invited lecture on Data Mining using Python for ### the Institute of Technology at Blanchardstown, Dublin, Ireland ### Lecturer and presenter: Dr. Peter Mooney ### email: peter.mooney@nuim.ie ### Date: November 2013 ### ### The purpose of this lecture is to provide students with an ...
0db7dc9e7553294cc3f09dd5261cd6bbddbaa317
PDXDevCampJuly/Nehemiah-Newell
/Python/Dice/test_die_roll.py
1,759
3.890625
4
__author__ = 'Nehemiah' import unittest from dieClass import Die class die_roll_test(unittest.TestCase): """Test the functionality of the die class roll function""" def setUp(self): self.possible_values = [1,2,3,"Dog",'Cat','Hippo'] self.new_die = Die(self.possible_values) print(self....
c4a42b89e15d93444771c65bcfd8663cda3e2efe
PDXDevCampJuly/Nehemiah-Newell
/Python/Dice/angry_dice.py
4,580
3.953125
4
# Create and run a game of angry dice from dieClass import Die #Create an Angry Dice object class Angry_Dice: #Set up a game, taking no parameters def __init__(self,): # Declare a master list of die values self.masterlist = ["1","2","ANGRY","4","5","6"] # Declare the dice self.angryDieA = Die(self.masterlist...
6187d788dd3f6fc9b049ded6d08189e6bb8923ed
lflores0214/Sorting
/src/iterative_sorting/iterative_sorting.py
1,583
4.34375
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements print(arr) for i in range(0, len(arr) - 1): # print(f"I: {i}") cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 ...
ccb6ca40ad86383d8b42521700846b66f2210cf3
tianzhuzhu/mystock
/utils/PC_util.py
450
3.515625
4
import ctypes import os # 获取计算机名 def getname()->str: pcName = ctypes.c_char_p(''.encode('utf-8')) pcSize = 16 pcName = ctypes.cast(pcName, ctypes.c_char_p) try: ctypes.windll.kernel32.GetComputerNameA(pcName, ctypes.byref(ctypes.c_int(pcSize))) except Exception: print("Sth wrong in...
83f3810eed3b82a8c9d238e9c8ac7f0d770c9d94
ZaytsevDmitriy/Task-9.1
/main.py
1,819
3.640625
4
import requests from pprint import pprint Super_hero_list = ['Hulk', 'Captain America', 'Thanos'] class super_hero(): def __init__(self, name): self.name = name # self.intelligence def super_hero_request(self): name = self.name url = ("https://superheroapi.com/api/2619421814940...
0e6b4293d300816f8d79931a295a6609d366c41e
vinodhinia/CompetitiveCodingChallengeInPython
/SortingWithLambdaFunctions/SortingArrayWithParity.py
137
3.5625
4
def sortArrayPairing(A): A = A.sort(key=lambda a: a % 2) print(A) return A arr = [3, 1, 15, 2] print(sortArrayPairing(arr))
168a9554f9d16b23e68dac5a254354c0c9e4be10
vinodhinia/CompetitiveCodingChallengeInPython
/Stacks/MinStackOptimal.py
1,172
4.15625
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min_stack = [] def push(self, x): """ :type x: int :rtype: void """ if len(self.stack) == 0 and len(self.min_stack) == ...
c9b45ba49dab86e76c7153be439c407e7131d244
vinodhinia/CompetitiveCodingChallengeInPython
/GroupAnagrams.py
462
3.609375
4
class Solution: def groupAnagrams(self, strs): if strs is None or len(strs) ==0: return strs str_dict = {} for str in strs: key = ''.join(sorted(str)) if key in str_dict: str_dict[key].append(str) else: str_dict[...
941f2f73af14bba0a991a49ba8e2e1f8740ce1cc
vinodhinia/CompetitiveCodingChallengeInPython
/UniqueEmailAddress.py
1,071
3.53125
4
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ # 1. Anything after + and before @ should be ignored # 2. '.' must be ignored result = set() if emails is None: return emails for email i...
1883f0aa23cbe35756581d33ff30405dc27bb3e9
vinodhinia/CompetitiveCodingChallengeInPython
/ReverseString.py
550
3.765625
4
class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ if s is None or s.strip() == "": return s start = 0 end = len(s) - 1 str_arr = list(s) while start < end: str_arr[start], str_arr[end] = str_arr[end], str_...
a216f38152ebac94d682b1a3a5a255cb4ee1dc49
SHASHANK992/Python_Hackerrank_Challenges
/HACKERRANK_PYTHON_LIST.py
1,527
3.671875
4
times = int(input()) list=[] permanent=[] before=[] for i in range(0,times): permanent.append(str(input())) for i in range (0,times): temporary = permanent[i] temporary = temporary.lower() temporary2 = str() #print(before) if(temporary.find("insert",0,len("insert"))!=-1): values = [] ...
9695efec2afdef9c42b85dd77f3939881dce21f6
yufeialex/all_python
/python_study/my/老王练习/基础篇7.py
412
3.84375
4
# coding=utf-8 ''' 今天习题 1: a = 'pyer' b = 'apple' 用字典和format方法实现: my name is pyer, i love apple. 2:打开文件info.txt,并且写入500这个数字。 ''' a = "pyer" b = "apple" print("my name is {name},i love {love}".format(name=a, love=b)) print("my,name is %(name)s, i love %(love)s" % {"name": a, "love": b}) # 2 file = open("info.txt", ...
48b6f785674c52f25f732acd4759782ceebfb8ff
yufeialex/all_python
/qiyi/dictTest.py
2,285
3.640625
4
# https://segmentfault.com/a/1190000010567015 dict1 = {"lo": "beij"} dict2 = {"mm": "shang"} # 方法1,不好 # 在内存中创建两个列表,再创建第三个列表,拷贝完成后,创建新的dict,删除掉前三个列表。这个方法耗费性能,而且对于python3, # 这个无法成功执行,因为items()返回是个对象。 # 你必须明确的把它强制转换成list,z = dict(list(x.items()) + list(y.items())),这太浪费性能了。 # 另外,想以来于items()返回的list做并集的方法对于python3来说也会失败,而且,并...
e721f3f8984fbbd9c897ecf57ba9886be925483b
yufeialex/all_python
/python_study/my/老王练习/基础篇18 周末习题.py
3,624
3.65625
4
# coding=utf-8 ''' 1. 已知字符串 a = "aAsmr3idd4bgs7Dlsf9eAF", 要求如下 1.1 请将a字符串的大写改为小写,小写改为大写。 ''' a = "aAsmr3idd4bgs7Dlsf9eAF" print(a.swapcase()) ''' 1.2 请将a字符串的数字取出,并输出成一个新的字符串。 ''' b = [s for s in a if s.isdigit()] print(''.join(b)) ''' 1.3 请统计a字符串出现的每个字母的出现次数(忽略大小写,a与A是同一个字母),并输出成一个字典。 例 {'a': 4, 'b': 2} ''' a = a.low...
c87c16ed09866d18fdde4ed2d4566f989bd14393
polowis/text-based-rpg-game
/inventory.py
1,241
3.609375
4
import random class Inventory: def __init__(self, player, app): self.player = player self.bag = ['Potions', 'Postions'] self.size = 300 self.app = app def viewInventory(self, player, app): """View Inventory""" if len(self.bag) < 1: self.app.write("T...
e5ebc43703c0fa54cda0b5fdaa1a140684a919df
Sami-AlEsh/Sudoku-Solver
/Solver/fast_solve.py
5,058
3.515625
4
# written by Nathan Esau, Aug 2020 import copy def get_possible_values(board, row, col): possible_values = [1,2,3,4,5,6,7,8,9] tl_row = row - row % 3 tl_col = col - col % 3 for i in range(9): if len(board[row][i]) == 1: # entry already solved if board[row][i][0] in possible_values: ...
4f1406893d411044dfcc19054483be5693419bc5
atshaman/SF_FPW
/C1/T191/figures.py
1,208
4.09375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """Описание классов геометрических фигур в рамках учебного задания 1.9.1""" import math class Rectangle: def __init__(self, width, height): self.width = width self.height = height @property def width(self): return self._width @width.s...
1f6b68866dc8e31c50294b16b27645a468a72341
mohammadzainabbas/AI-Decision-Support-Systems
/Lab 02/Tree (2).py
399
3.53125
4
class Tree(): def __init__(self): self.left = None self.right = None self.data = None root = Tree() root.data = "root" root.left = Tree() root.left.data = "left" root.right = Tree() root.right.data = "right" root.left.left = Tree() root.left.left.data = "left left" root.left.r...
e6a7ed26ea39b14e337cfdcf969829df9803dbaf
mohammadzainabbas/AI-Decision-Support-Systems
/Lab 05/Task_2.1 Tree Structure.py
1,128
3.8125
4
class Tree(): def __init__(self, val): self.data = val self.left = None self.right = None def PreOrder(self, root): if root: print(root.data) self.PreOrder(root.left) self.PreOrder(root.right) def PreOrderList(self, root, list): ...
34517c82223ec7e295f5139488687615eef77d56
devineni-nani/Nani_python_lerning
/Takung input/input.py
1,162
4.375
4
'''This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python.''' #input() use roll_num= input("enter ...
43a9b64fb9048e9556066a8afe3b738d28d3d96a
devineni-nani/Nani_python_lerning
/Data Types/data_type.py
167
4.3125
4
'''Getting the Data Type You can get the data type of any object by using the type() function: Example Print the data type of the variable x:''' x = 5 print(type(x))
99af00d1ed58d0acd6873db13ebe0d1bec920812
mpaluta/Ant-Colony-Optimization
/devices/device.py
857
3.5
4
import numpy as np import random # Define class for type 1 devices class Device: # Initialize class object with power level, duration of required power usage, time at which # task was assigned, window over which task must be completed, and time step for analysis def __init__(self, powerLevel, duration, step = 60):...
a33aab465be9a23389d4750218b42021b3aebcb4
LoboAnimae/Computer-Graphics
/Lab_2.5_Filling_Polygon/lib/contourcounter.py
738
3.609375
4
def greatercounter(contourp:list, point:list, index:int): """Allows to know the number of points in front of the given point. Args: contourp (list): List of all the points point (list): X-Y-Values array of a singular point index (int): 0 if working on X. 1 if working on Y. Return...
1d4acda0c046f66dc43f33c3f57b623112815811
Rashid2410/test2
/task_j.py
455
3.875
4
class Things: color = "red" def __init__(self,n,t): self.namething = n self.total = t th1 = Things("table", 5) th2 = Things("computer", 7) print (th1.namething,th1.total) # Вывод: table 5 print (th2.namething,th2.total) # Вывод: computer 7 th1.color = "green" # новое свойство объекта th1 print (th1.color) #...
1f96007044613e93a28ccf7937af87536698ef09
albert-cheung/Automation-Projects
/Autosys_Automation_Project/copy_file.py
1,102
3.5
4
#Purpose of this query is to take a large number of queries and parse them out into digestable chunks. lines = [] #Strips a list of customer_ids pasted individually on the .txt file with open("customer_ids.txt") as file: for line in file: line = line.strip() lines.append("'" + line + "'") lines_l...
463fbd192d59cb8c75c7c69839be80c168ec43fb
Dragonriser/DSA_Practice
/Dynamic Programming/IntelligentGirl.py
517
3.828125
4
#QUESTION: Given a string of integers, find the number of even integers present from each index to the very end. Example: Input: 574674546476 Output: 7 7 7 6 5 5 4 4 3 2 1 1 #CODE: def findCount(s): dp = [0]*len(s) if int(s[0]) % 2 == 0: dp[-1] = 1 for i in range(len(s) - 2, -1, -1): if i...