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
4a49105b56770352acac84a24eb4a18f0e88ed82
naeem91/dsand
/P1/union_intersection_linked_list.py
4,739
4.28125
4
""" Explanation: We're visiting nodes of linked lists and creating sets of their values, then doing union and intersection operations on those sets. For performing either union or intersection, both linked lists have to be traversed: list traversal => O(len(L1)+len(L2)) union => O(len(L1)+len(L2)) intersection => O...
934c73a140567ad51d51c1d9ba226ebcd5e4ca2d
naeem91/dsand
/P1/active_directory.py
4,355
4.09375
4
""" Explanation: Two strategies are used to speed up user group membership look up: 1. A group's users are kept in a set rather than in a list to make lookup time constant 2. A persistent caching can be used to store list of a user's groups. This cache can be built when doing lookups: for example in following hierar...
3f2884d5da68f9fc7f684e63ed5a8a2144f0f39f
agrepravin/algorithms
/Sorting/MergeSort.py
1,193
4.15625
4
# Merge sort follows divide-conquer method to achieve sorting # As it divides array into half until one item is left these is done in O(log n) time complexity # While merging it linear compare items and merge in order which is achieved in O(n) time complexity # Total time complexity for MergeSort is O(n log n) in all t...
612e527762f60567874da66187cdaecf1063874e
khch1997/hw-python
/timing.py
462
4.125
4
import time def calculate_time(func): """ Calculate and print the time to run a function in seconds. Parameters ---------- func : function The function to run Examples -------- def func(): time.sleep(2) >>> calculate_time(func) 2.0001738937 """ def wra...
1a8ed29399e907ff6a087fc2411ad7559adec42d
QuantTK/0-Coding-Challenge
/Task 0.9.py
227
3.859375
4
def get_vowels(string): vowels = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U"] lis = [] for i in string: for j in vowels: if j == i: lis.append(j) print(", ".join(lis))
ef3aadc606e9bdffa2a899afc4ee6d05dc354b51
alecmerdler/cs-444-group-119
/hw3/concurrency3/concurrency3.py
4,667
3.53125
4
from threading import BoundedSemaphore, Thread import random import os from time import sleep class Node: """ Represents a node in the singly-linked list. """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A singly-linked list data st...
6c0d5375fda176642668a007e65f8ae9f4c21e4a
josgard94/CaesarCipher
/CesarEncryption.py
1,915
4.53125
5
""" Author: Edgard Diaz Date: 18th March 2020 In this class, the methods of encrypting and decrypting the plain text file using modular arithmetic are implemented to move the original message n times and thus make it unreadable in the case of encryption, the same process is performed for decryption usi...
891ea5ad90826bfdd14b1eae9c3731c973047491
zhangyilang/RHMCTS
/policy.py
14,091
3.609375
4
from random import choice from utils import * def policy_evaluation_function(state): """ Return a list of the best n substates (n might change for different states) for current player given current state; :param state: [board, player], where board is a 2-d list and player is either 1 or 2; :return: a ...
8e10de5ca4c4d0250fc6af9dacbf42cdf5f3ca69
saurabhwasule/python-practice
/UD_Learn_python_with_70.plus_exercises_Complete/Excercises.py
6,702
4.15625
4
# # Print and input 1 # var=input("Enter a number to print:") #Get the input from the user # print('Entered number is %s'%(var)) #Print the output of the variable # print('You have entered'+var) #Print using addition of strings. # print('You have entered %s'%(var)) #Print using % method # print('You have entered {...
fc379013e4d07b335a0c54314a8a397e0e4446b5
saurabhwasule/python-practice
/Nice_training_material/core_python_hands-final/reference/advanced/count_dir_CLass_examples.py
11,247
3.546875
4
# frequency str = " I am Ok I am OK I am OK" import re pat = re.compile(r"\w+") alpha_d = dict() word_d = dict() for ele in str.lower(): if ele in alpha_d: alpha_d[ele] += 1 else: alpha_d[ele] = 1 for ele in pat.findall(str.lower()): if ele in word_d: word_d[ele] += 1 else: word_d[ele] = 1 sorted(alpha_d...
33cdd7e45ae98f3b27caf9ea61d45d67005225eb
RicardoParizotto/Seguran-a-2016-2
/cc/transposicao.py
379
4.09375
4
#! /usr/bin/env python3 import math if __name__ == '__main__': txt = input('Digite o texto a ser cifrado:\n') key = int(input('Digite a chave:\n')) for j in range(0, key): for i in range(0, math.floor(len(txt)/key)): print(txt[i*key+j],end="") #print() debug: mostra a matri...
f9b109cc9d356431ae79bf53b635889cd56465f3
Kertich/Linked-List
/linkedList.py
777
4.15625
4
# Node class class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.start = None # Inserting in the Linked List def insert(self, value): if self.start == None: self.start = Node(value) ...
ca30f5e6dc61c26aeeb23945ae49654c36d35ccb
Croxy/The-Modern-Python-Bootcamp
/Section 12: Lists/examples/whileLoop.py
92
3.625
4
numbers = [1,2,3,4] i=0 while i < len(numbers): print(numbers[i]*numbers[i]) i += 1
47321ae0df841cdc0c790d1692b65d9411aa8f7d
Croxy/The-Modern-Python-Bootcamp
/Section 10: Loops/examples/whileExample1.py
332
4.28125
4
# Use a while loop to check user input matches a specific value. msg = input("what is the secret password?") while msg != "bananas": print("WRONG!") msg = input("what is the secret password?") print("CORRECT!") # Use a while loop to create for loop functionality. num = 1 while num < 11: print(num) n...
c318abd7ede7ba7f9ceb80c33278cda7a38343b7
Croxy/The-Modern-Python-Bootcamp
/Section 11: GuessingGame/examples/guessingGame.py
693
4.0625
4
import random user_input = None computer_num = random.randint(1,10) while user_input != computer_num: user_input = int(input("guess a number between 1 and 10: ")) if user_input > 0 or user_input < 11: if user_input > computer_num: print("Too high, try again!") elif user_input < co...
c8a028c124a729656bc7cc2da192539c52b2bb11
EDAII/lista3-eda2
/main.py
1,128
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from ordena import quick_sort, bubble, insertion_sort, selection_sort from sortTimer import SortTimer import random lista = [] print("Escolha uma opção de vetor") print("1 - Aleatorio") print("2 - Inverso Ordenado") print("3 - Ordenado") o...
e5e2eda422140e081669a959423e2f7a8a1a4de4
mortlach/n-grams
/get_Ngram_Example.py
2,139
3.625
4
# This is a simple example script showing how to read in some cribs from the # n-grams list given the crib word lengths # Due to the size of the ngram data, it is worthwhile creating a bespoke # list of words to use, especially for short words # # clearly you can do more sophisticated cutting, faster fucitons etc .....
f52989542f51cab2cb412c85fc174c258a262991
chixinn/KaggleMyOwn
/Lecture_4/Lecture_4_Feature Selection.py
4,356
3.828125
4
##COPYRIGHT from 仲益教育 import sys sys.path.append("C://Users//Haixiang He//desktop//Kaggle//Lecture 2") #conda install mxltend --channel conda-forge #pip install package name import pandas as pd from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.metrics import r2_score from sklearn.mode...
127a3423cb2622dea30402f50bb0267dfc72ad6a
godinechan/Mushroom_House
/mushroom_house/game.py
13,064
4.0625
4
""" This file consists of the Game class, in which stores the attributes of the game as well as all functions required for the game. @author: godinechan """ import random from collections import Counter from string import ascii_uppercase from board import Board from card import Card from player import Player import con...
1783ab8da5879f9271a68c3a12c4cff94b11e453
aherdzik/adventofcode
/2020/day1/main2.py
400
3.640625
4
file1 = open('input.txt', 'r') Lines = file1.readlines() count = 0 newSet = set() # Strips the newline character for line in Lines: newSet.add(int(line)) for val1 in newSet: if val1 >= 2020: continue for val2 in newSet: reverse = 2020- val1- val2 if reverse <=0: ...
805fed31ef6cefe26aeb8ebfdce0684bc7d415d0
SharathKumar2036/Python-Basic-Programs
/Patterns/pattern4.py
187
3.96875
4
from __future__ import print_function n=int(input("Num:")) for i in range(n):#When value of i is 1 then in it prints one star for j in range(n-i): print('#',end='') print("\r")
dc65a78c1c941d9da104f82df7cdd09a9216167e
Ponkiruthika112/codes
/longest_palindromic_subsequence.py
255
3.75
4
def palindrome(s,i,sub,l): if i==len(s): if len(sub)!=0 and sub==sub[::-1]: l.append([len(sub),sub]) else: palindrome(s,i+1,sub,l) palindrome(s,i+1,sub+s[i],l) return l s=input() l=[] palindrome(s,0,"",l) l.sort(reverse=True) print(l[0][1])
a64be459b4a501a509ed45e7566a80bc492a4319
desarrollocancun/WebPayPLUS
/Python/3.0/AESEncryption.py
4,508
3.75
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Biblioteca para cifrado y descifrado de informacion con la biblioteca cryptography # arodriguez MIT # version 1.1 # Compatible con Python >= 3.0 # Basado en el modulo cryptography. Se instala con: pip install cryptography # Documentacion cryptography https://cryptogr...
cf047db7988d00f28a591d08aeb41bb5a131d4a5
tangcfrank/tang
/alex/dead loop.py
2,700
3.546875
4
import random import os,sys #随机产生7个数,并且产生的绿球不能重复 def numA(num): count = 0 a = [] while count < num: if num == 6: a.append(random.randint(1, 32)) if count > 0:#0 for each in a[:-1]: if a[len(a)-1] in a[:-1]: a.remove...
49ac2bc4948fcc5cb8d358434de1416dc47d3529
mspamelalea/Election-Analysis
/PyPoll_Challenge.py
5,050
3.71875
4
# Add dependencies. import csv import os # Assign a variable to load a file from a path. file_to_load = os.path.join("Resources/election_results.csv") # Assign a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_analysis.txt") # Initialize a total vote counter. total_votes...
ba30a449793ff270e61284e1d4598629647f5681
pradeepraja2097/Python
/python basic programs/arguments.py
543
4.1875
4
''' create a function for adding two variables. It will be needed to calculate p=y+z ''' def calculateP( y , z ) : return int( y ) + int( z ) ''' create a function for multiplying two variables. It will be needed to calculate p=y+z ''' def calculateResult( x, p ) : return int( x ) * int( p ) #Now this...
23f95e08d2678366d97400ade96b85453ce265e5
EdwinaWilliams/MachineLearningCourseScripts
/Python/Dice Game.py
484
4.28125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 22:18:01 2019 @author: edwinaw """ import random #variable declaration min = 1 max = 6 roll = "yes" while roll == "yes" or roll == "y": print("Rolling the dices...") dice = random.randint(min, max) #Printing the random number generated print("Yo...
ac9f0ab79e5724626e8095a8847c7f71746496b5
samargunners/LPTHW
/ex13.py
380
3.734375
4
from sys import argv script, first, second, third = argv print(">>> argv=", repr(argv)) print("The script is called: ", script) print("Your first variable is: ", first) print("Your second variable is: ", second) print("Your third variable is: ", third) print(f"{first} {second} {third}") yourname = input() print(f...
a07567a7a70c3d346971cd31e0af19a053287e2b
samargunners/LPTHW
/ex18.py
511
3.828125
4
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") #ok, that *args is actuallyy pointless, we can just do this def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") #this just takes one segment def print_one(arg1): pri...
0ab5807adca0c918e478edc69af24d46024abd33
shashank-22/Compititive
/Leetcode/2.py
554
3.703125
4
l1 = [1,3,4,5] l2 = [3,4,5,7,8] out = [1,3,3,4,5,5,7,8] def merge2lists(l1,l2): expexted_out = [] p1 = 0 p2 = 0 while(p1<len(l1) and p2<len(l2)): if(l1[p1]<l2[p2]): expexted_out.append(l1[p1]) p1+=1 elif(l1[p1]>l2[p2]): expexted_out.append(l2[p2]) p2+=1 else: expexted_out.append(l1[p1]) ex...
75f62ac04226e7cc3bd54e7d10aa11cc36e8120f
ajayrathour/ajay3yrs_assignment
/ajay3yrs1.py
1,197
3.75
4
import csv import random print "Enter no. of companies", comp_nos = raw_input() total_comp = int(comp_nos) ofile = open('company.csv', "ab",0) writer = csv.writer(ofile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) i = 1 comp_list1 = ['year','month'] while i <= total_comp: com_name = 'comp_'+str(i) ...
8b9211c362c98f702fc170babdae543d99dbd9dc
eth-ait/ComputationalInteraction17
/Andrew/First/code.py
3,218
4.03125
4
# PLEASE NOTE THAT THIS IS NOT ALL THE CODE USED WITHIN THE FIRST TUTORIAL, SEE TUTORIAL FOR FULL CODE. import numpy as np import random import matplotlib.pyplot as plt def __init__(self): self.deck_values = [0, 1, 2, 3] random.shuffle(self.deck_values) # randomise deck order self.num_draws = [0, 0, ...
af3ce5b9cdd631ba968e8b6791a3f907df1fe70d
Jake-Owen95/MachineLearningProjects
/linearRegression.py
1,541
3.734375
4
import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_diabetes from sklearn import linear_model #Loading diabetes dataset diabetes = load_diabetes() #Data split into testing and training data. diabetes_X = diabetes.data[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-20] di...
64ad87a08ca4ad93c3fd449d44fc47751f79ee7c
wcadmin1/Artifical-Intelligence-Ansaf-Salleb-Aouissi-Columbia-University-EdX
/Programming Assignments/Week 7/problem1_3.py
1,911
3.625
4
# -*- coding: utf-8 -*- import sys import numpy as np import csv from matplotlib import pyplot as plt def pla(inputFile, inputX, inputLabel): #Initialize a zero weight matrix weight = np.zeros(inputX.shape[1]) #Open csv file for writing file = open('output1.csv','w',newline='') write...
890220bcda034a12c9e2df948a67aac3c26d9352
SauravRJoshi/python-2
/question10.py
710
3.828125
4
def change_case(sample_str): snake = [sample_str[0].lower()] for c in sample_str[1:]: if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): snake.append('_') snake.append(c.lower()) else: snake.append(c) snake = ''.join(snake) kebab = [sample_str[0].lower()...
33770b127de5d40b6c3ec0e24b3d80672e308afe
SauravRJoshi/python-2
/question18.py
418
3.703125
4
import json input_dict = {'Name': 'Saurav Raj Joshi', 'age': 24} print('Converting dictionary to JSON ') def Py_to_Json(input_dict): json_format = json.dumps(input_dict) return json_format print(Py_to_Json(input_dict)) print('Converting JSON to Python format dictionary ') def Json_to_py(json_format): ...
7a48e69d0a8fc9b4c07b59dce065db940e5c894f
samundrak/python-test-codes
/game/class.py
633
4
4
class one: one = 1 two = 2 oneA = 0 oneB = 0 def __init__(self,x,y): self.oneA = x self.oneB = y def second(self): print self.one + self.two + self.oneA + self.oneB class two: one = 2 two = 3 def __init__(self,x,y): self.oneA = ...
3d8812ede5b75dd8cf8935ede71bc0eda78ca230
VitamintK/FrivolousStuffs
/word_maker.py
2,956
3.90625
4
"""i'm bored af and it's 4:01 am and I can't come up with anything to do so here's a random word. I think google captchas have something like this but better. It's pretty fun to just try to pronounce random words. next step: programmatically create a random language. start with allowable letters/phofhuneomes,""" cons...
d3d108692caf51ce2e0ff3a2404c2c18bd5d7eaa
TTXDM/firstGame
/test/test.py
1,346
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: eric_li # created: 2015/6/30 13:11 def checkPais(Pais):#检查每个玩家能够用到的牌 s_list=""; k_list=""; for str_i in Pais: pai_i=ord(str_i) for str_j in Pais: pai_j=ord(str_j) print chr(pai_i),chr(pai_j), s_list ...
bce9c3d4dab282927f2181bc3ca1981b57bbed58
weijiang1994/cookbook-code
/04迭代器与生成器/06暴露外部状态生成器.py
820
3.625
4
""" # coding:utf-8 @Time : 2021/06/08 @Author : jiangwei @mail : qq804022023@gmail.com @File : 06暴露外部状态生成器.py @Desc : 如果你想暴露一些生成器函数属性给外部调用者,可以通过生成器类来实现 @Software: PyCharm """ from collections import deque class LineHistory: def __init__(self, lines, histlen=3): self.lines = lines sel...
c6de227b08593cab2b198e5c5dee8f9f6d55269a
weijiang1994/cookbook-code
/04迭代器与生成器/09排列组合的迭代.py
359
3.96875
4
""" # coding:utf-8 @Time : 2021/06/08 @Author : jiangwei @mail : qq804022023@gmail.com @File : 09排列组合的迭代.py @Desc : 09排列组合的迭代 @Software: PyCharm """ from itertools import permutations items = ['a', 'b', 'c'] for p in permutations(items): print(p) # 得到指定长度的排列 for p in permutations(items, 2): pri...
fd3ad015d9464d777d6ddf08d6cd817deef2cff4
codefordream/machine-learning
/data_analysis/rain.py
1,605
3.890625
4
import pandas as pd #creating DataFrame data = {"Month":pd.Series(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]), "Rainfall":pd.Series([1.05,3.22,14.2,8.2,4.5,1.05,3.22,14.2,8.2,4.5,4.2,1.2]),} df = pd.DataFrame(data) #read csv file dfc = pd.read_csv(r'./rain.csv') print(dfc) #read json ...
c73314efe9470e286192c0b4c28a91eb4b2333ad
aastronautss/challenges-and-interview-questions
/recursion/8.3.py
610
3.984375
4
# A magic index of a list L is an index such that L[i] == i. Given a sorted # list of distinct integers, write a method to find a magic index, if one # exists, in list L. def magic_index(lst): return magic_index_mem(lst, 0, len(lst) - 1) def magic_index_mem(lst, start, end): if len(lst) == 0: return N...
eaf004e146f5f0cb7e3b15cda012cc01fdaad203
aastronautss/challenges-and-interview-questions
/recursion/8.4.py
207
3.796875
4
# Write a function to compute a power set of a given set. # def powerset(seq): # lst = list(seq) # result = [lst] # if len(lst) == 0: # return result # return result + powerset(lst)
339ffbf7ac0f9779f107176cc74c5833a600701e
Janna112358/Gloomhaven
/Gloomhaven.py
2,791
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 13 13:40:41 2019 @author: jgoldstein """ ### docstring convenience stuff ### # so we don't repeat bits of docstring many times, use this decorator # to add standard bits of docstring for parameters and return values def add_doc(doc): def decora...
3a34aecac0c66e47694c67d0867fee5b16ebd9ad
MakeSchool-17/twitter-bot-python-gordoneliel
/BinarySearch.py
543
3.796875
4
''' Binary Search ''' def binarySearch(list, data): mid = len(list) // 2 if len(list) <= 0: return False if list[mid] == data: return list[mid] else: if list[mid] > data: return binarySearch(list[: mid - 1], data) elif list[mid] < data: return b...
69237dabe784446234868c8f59c6e1b0173c8df5
hfu3/codingbat
/logic-1/date_fashion.py
719
4.28125
4
""" You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very styli...
14bcd4bc57e577054ba749327a53cb67329d907e
hfu3/codingbat
/warmup-2/string_bits.py
241
4.09375
4
def string_bits(str): """ Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo" """ b = "" for i in range(len(str)): if (i%2)==0: b += str[i] return b
5da48e942d1c5e70a86953f059ea8d9f88123f54
alonsovidales/cracking_code_interview_1_6_python
/20_10.py
1,430
3.515625
4
# Given two words of equal length that are in a dictionary, write a method to # transform onewordintoanotherwordbychangingonlyoneletteratatime Thenewwordyou # get in each step must be in the dictionary # EXAMPLE # Input: DAMP, LIKE # Output: DAMP -> LAMP -> LIMP -> LIME -> LIKE import collections class SuperDict(obje...
357471fe299e6a8be3349a1f3fd99144c9c59ae8
alonsovidales/cracking_code_interview_1_6_python
/4_3.py
1,189
3.765625
4
# Given a sorted (increasing order) array, write an algorithm to create a # binary tree with minimal height # 1, 4, 5, 6, 8, 9 class BTree(object): class Node(object): def __init__(self, v, l=None, r=None): self.v = v self.l = l self.r = r def __init__(self): ...
76876c39712167ab42e5c98facaadeed9461a1f5
alonsovidales/cracking_code_interview_1_6_python
/9_3.py
1,088
3.59375
4
""" Given a sorted array of n integers that has been rotated an unknown number of times,giveanO(logn)algorithmthat ndsanelementinthearray Youmayassume that the array was originally sorted in increasing order EXAMPLE: Input: nd 5 in array (15 16 19 20 25 1 3 4 5 7 10 14) Output: 8 (the index of 5 in the array) """ def...
d8eae3aee53a32409d56bec3ccbc0192fac4e098
alonsovidales/cracking_code_interview_1_6_python
/other_google/quick_sort.py
866
3.859375
4
def quick_sort(arr, in_lo=0, in_hi=-1): if in_hi == -1: in_hi = len(arr)-1 if in_lo >= in_hi: return arr print "IN:", arr[in_lo:in_hi+1], in_lo, in_hi pivot = arr[in_lo] hi = in_hi lo = in_lo+1 while lo < hi: print "IN loop:", lo, hi while arr[lo] < pivot a...
7c59f7673112831e51cb8d071c45d47d61c21dee
alonsovidales/cracking_code_interview_1_6_python
/9_5.py
1,020
4.21875
4
# Given a sorted array of strings which is interspersed with empty strings, # write a meth- od to nd the location of a given string # Example: nd "ball" in ["at", "", "", "", "ball", "", "", "car", "", "", # "dad", "", ""] will return 4 Example: nd "ballcar" in ["at", "", "", "", "", # "ball", "car", "", "", "dad", ...
4edfcf39b850896308108dbe96c22bd66e9bde77
alonsovidales/cracking_code_interview_1_6_python
/19_1.py
189
4
4
# Write a function to swap a number in place without temporary variables def swap(x, y): x[0] ^= y[0] y[0] ^= x[0] x[0] ^= y[0] x = [21] y = [19] swap(x, y) print x[0], y[0]
7c02b1144ac4b645bd3ea4301d0a6a96028eaf38
alonsovidales/cracking_code_interview_1_6_python
/5_1.py
548
3.875
4
""" You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) EXAMPLE: Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100 """ def mix_nums(n, m, i, j): ...
b27b299e701278707a7e0c0ee9dbe8e3ea9e8ab8
syy1023/python
/prac5.py
709
3.921875
4
''' Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char. str1='ooxxc8occbxxx' def xo(s): s = s.lower() return s.count('x') == s.count('o') Instructions Output Take 2 strings s1 and s2 including only letter...
4505f8a1fe1c9cc5b04a326896c1648ec5415fee
jmockbee/While-Blocks
/blocks.py
390
4.1875
4
blocks = int(input("Enter the number of blocks: ")) height = 0 rows = 1 while rows <= blocks: height += 1 # is the height +1 blocks -= rows #blocks - rows if blocks <= rows: break # while the rows are less than the blocks keep going. # if the rows become greater than the blocks...
466b64842d716527add6746952cb0634f360d8b8
ioannispol/Py_projects
/maths/calculus.py
418
3.96875
4
""" Python Calculus calculator""" import math import sympy from sympy import Symbol, Derivative # create a simple function def f(x): return x ** 2 f(4) print(f(4)) # Define a derivative def der(f, v): h = 0.00000000001 top = f(v + h) - f(v) bottom = h slope = top / bottom return float("...
e9bb62ab1fceeb98599946ef6a0c00650baa5d29
ioannispol/Py_projects
/maths/main.py
2,337
4.34375
4
""" Ioannis Polymenis Main script to calculate the Area of shapes There are six different shapes: - square - rectangle - triangle - circle - rhombus - trapezoid """ import os import class_area as ca def main(): while True: os.system('cls') print("*" * 30) print("...
aa86193a5239085d28c8ddde2033d0f667cece32
SiriReddi/GameofThrones_Python
/got_demo.py
2,312
3.578125
4
from pprint import pprint from characters import characters numofA = [] for character in characters: if character['name'][0] == 'A': numofA.append(character['name']) print("Total number : ", len(numofA)) #if character['name'].startswith('A') == True: # pprint(character['name']) # print(len(...
be878729d8a821fadc9b7f8553f82834891787d9
wiznikvibe/python_mk0
/leap_year.py
287
4.09375
4
year = int(input("Which year do you wanna check? \n ")) if year % 4 == 0: if year % 100==0: if year % 400==0: print("Leap year") else: print("Not a leap year") else: print("Leap year") else: print("Not a leap year")
e467818f8fe5e8099aaa6fb3a9c10853ff92b00b
wiznikvibe/python_mk0
/tip_calci.py
610
4.25
4
print("Welcome to Tip Calculator") total_bill = input("What is the total bill?\nRs. ") tip_percent = input("What percent tip would you like to give? 10, 12, 15?\n ") per_head = input("How many people to split the bill?\n") total_bill1 = float(total_bill) (total_bill) tip_percent1 = int(tip_percent) per_head1 = i...
98f1771b852bd068028e1525c1aeb28e932988fb
wennerma/Financial-Tools
/inputController.py
1,425
3.703125
4
from debtClass import * from investmentClass import * class Inputer: def debtInfo(self): debtEntry = input("Enter debt name, principal, apr, term: ") debtVar = [] debtVar = debtEntry.split(',') debt = Debts(debtVar[0], float(debtVar[1]), float(debtVar[2]), int(debtVar[3])) r...
d8f0afeb7da9f81c831cf489c82e0a58167b4da3
frankTheCodeBoy/DATA_SCIENCE_MACHINE_LEARNING_ANALYSIS
/reinforcement_learning.py
1,063
3.65625
4
"""Exploring Reinforcement Learning""" #Import the libraries import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("data/Ads_CTR_Optimisation.csv") dataset.head(10) #Use Thompson Sampling to resolve exploration-exploitation dilemma import random N = 1000 d = 10 ads_selected = [] numbers_of_reward...
d39a851102e92099fa4420679b345f777d791f6f
rdewanje/ml-training
/python/nn_tools.py
10,052
3.984375
4
'''Tools for creating a neural network model and evaluating it ''' from sklearn.model_selection import train_test_split from keras.layers import Dense from keras.layers import Dropout from keras.layers import BatchNormalization from keras.activations import elu from keras.layers import ELU from keras.optimizers import ...
5fd0237a47e9c17c7367f732d574db6e554d17bb
berkai/vendingmachine
/machine/calculator.py
1,614
3.8125
4
from utils.logging import Logger from configs import AppConfig from random import randint class Calculator(object): def cashback_calc(self, snack_price, amount): ''' :param snack_price: price of the willing to buy item :param amount: amount of inserted coin :return: coins list of...
76b89b575354bfb38e85e4c172707cf25a2adbdd
TiagoArrazi/WebService-Tiago
/WebService/services/classifiy_pwd/src/utils/classifier.py
3,095
3.9375
4
import string import itertools class Classifier: """ RULES: - At least 8 characters - At least 1 lower case character - At least 1 upper case character - At least 1 number - At least 1 special character - No more than 2 consecutive characters - No seque...
6326e97e68b34eaded98fd36dfa607e8d5d22dd2
dshulgaster/revbash
/main.py
1,730
3.6875
4
def main( room ): # room - номер комнаты, которую ищем assert room <= 2_000_000_000, 'номер команты слишком большой' floor = 0 # номер этажа, на котором находится комната order = 0 # порядковый номер комнаты на этаже cur_room = 0 # номер текущей просматриваемой комнаты side = 0 # содержит сторон...
0bb83b864cf5c6cc4de4360095cccdf518d1c49e
vladknezdata/python_py_me_up
/PyBank/main.py
1,809
3.59375
4
import csv import os filepath = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__))),"..","Resources","budget_data.csv") output_path = os.path.join(os.path.join( os.path.dirname(os.path.abspath(__file__)),"..", "Resources", 'FinancialAnalysis.txt')) with open(filepath, newline='') as csvfile: ...
189b0e92f4b4f46962c0b238197dbd596ba53f0c
hossainlab/dataviz
/book/_build/jupyter_execute/plotly/4.LineCharts.py
7,766
3.71875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import plotly.graph_objs as go import numpy as np import plotly.offline as offline offline.init_notebook_mode(connected=True) # ## Style Line Plots # We have seen how line plots can be plotted. Now we see how those can be formatted # ### Download data set # Europe i...
aaa0db61582cf6ce5c3fe1e2840a8d0303d32a96
hossainlab/dataviz
/book/_build/jupyter_execute/plotly/3.Histogram.py
5,416
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import plotly.plotly as py import plotly.graph_objs as go import numpy as np import plotly.offline as offline offline.init_notebook_mode(connected=True) # #### Create a list of 200 random numbers # In[2]: random_numbers = np.random.randn(200) # #### Produce a hi...
b13bebfb8f785247d3d5de286de5f15bf218d005
hossainlab/dataviz
/book/_build/jupyter_execute/plotly/5.BubbleChart.py
3,466
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import plotly.plotly as py import plotly.graph_objs as go import pandas as pd import plotly.offline as offline offline.init_notebook_mode(connected=True) # #### A regular 2D scatter plot # In[2]: x = [1, 2, 3, 4] y = [2, 4, 1, 5] trace = go.Scatter(x=x, ...
35af1eacb07944c1daa23de48ceb930e81673b08
hossainlab/dataviz
/book/_build/jupyter_execute/seaborn/9-DemandForecasting.py
2,568
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import seaborn as sns import pandas as pd import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # We have seen from the flowchart about the Seaborn approach to Machine Learning Problems. Let's try to practically see how this turns out. ...
eda4504c4758656e0d1dac2162da15746785a776
hossainlab/dataviz
/book/_build/jupyter_execute/matplotlib/07_PuttingItTogether.py
3,700
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd matplotlib.interactive(True) plt.ion() matplotlib.is_interactive() # ### Dataset # This contains the closing price of 10 stocks on the first trading day of each month from Jan 20...
2dd21cce24bb7578752bf7f0ea18b545196f1b05
edwhelan/DC-Python107
/letter_histogram.py
373
3.875
4
disect_this = input('Please enter a word: ') results = {} #Loop through all letters for letter in disect_this: # if the letter is already in the dictonary if letter in results: results[str(letter)] = results[str(letter)] + 1 # if not add it with initial value of one else: results[str(lette...
8ec6abba71009e4d012e933e55930b782b7ed07c
JakobYde/Robotics_Vision_AI_Group_Project
/Tools/Video to frame/SThreader.py
1,500
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 21:31:16 2018 @author: SimonLBS """ import threading from queue import Queue class SThreader: def __init__(self, f): # Create the queue and threader self.q = Queue() self.funktion = f self.joinR = False self....
46cd8e04080c89302e12f65e60a85b9aca111f5c
Uguronaldoo/BBY162
/uygulama04.py
650
3.921875
4
1) metin = "Açık bilim, araştırma çıktılarına ve süreçlerine herkesin serbestçe erişmesini, bunların ortak kullanımını, dağıtımını ve üretimini kolaylaştıran bilim uygulamasıdır." metin [0:21] 2) liste = ["Açık Bilim", "Açık Erişim", "Açık Lisans", "Açık Eğitim", "Açık Veri", "Açık Kültür"] for x in liste : print(x)...
5c5794edb1a2483fe197012a3636b1eb6c2578ad
elibonneh/newtest
/elib2c.py
2,336
4
4
# answerA x = 10 y = 20 if x > y: print("BIG") else: print("SMALL") # answerB loops for x in range(5): print(x) # answerC a = 1 b = 2 c = 3 d = 4 if a > b: print("summer") elif a < b: print("winter") elif c == d: print("fall") else: print("spring") # answerD count = 1 while count < 11: ...
8447389bc3cd0823613e64f77c6c02f364f2dc1f
kambalagurunathreddy/CompetitiveProgramming
/Exams/Week4/2.py
381
3.734375
4
def CountingBits(num): bitarray=[] for x in range(num+1): count=0 while(x>0): t1=x&1 if(t1==1): count+=1 x=x>>1 bitarray.append(count) return bitarray print(CountingBits(15)) print(CountingBits(16)) print(CountingBits(1)) print(Cou...
d8b68b455a23fbc7336746e5b0038283db842229
MatejRojec/UVProjekt
/model.py
21,141
3.5625
4
''' Popravljena verzija ''' import math # Class Zgodovina je namenjen konsistentmem beleženju vektorev, matrik in permutacij, # ki jih je uporabnik vpisal (vsak uporabnik ima svoj dnevnik). class Zgodovina: def __init__(self): self.zgodovina_matrik = [] self.zgodovina_vektorjev = [] sel...
cbe14056628e012cc298fbc70c92d3a61e678205
jap97/Book-Database
/Book_Database_FE.py
3,420
4.03125
4
""" Book Database that store information like Book Title, Author, Borrowed, Lent, Name, Date User can view all records View Borrowed View lent Search an entry Add an entry Update entry Delete entry close """ from tkinter import * import Book_Database_BE def get_selected_row(event): global selected_tuple inde...
0e4cf1b1837a858cfb92830fa38c93879980b80c
sifisom12/level-0-coding-challenges
/level_0_coding_task05.py
447
4.34375
4
import math def area_of_a_triangle (side1, side2, side3): """ Calculating the area of a triangle using the semiperimeter method """ semiperimeter = 1/2 * (side1 + side2 + side3) area = math.sqrt(semiperimeter* ((semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - side3))) ...
4c9f4a62a94d2be21d09265e188ae113c4a3bae8
crisog/algorithms-class
/queues/first_problem.py
869
4.125
4
import time # Esta es la clase que define la cola # En este caso, la cola solo cuenta con una lista de elementos y dos funciones. class Queue: def __init__(self): self.items = [] # Esta función es para encolar elementos. def enqueue(self, item): self.items.insert(0, item) # Esta func...
9d4c439622db533e267720b4a208e2645926c50e
carolinedreis/listinha-par-imparexer
/lista.py
199
3.9375
4
lista= [[], []] for u in range (1,6): numero=int(input('Digite um numero: ')) if numero / 2 ==0: núm[0].append(numero) else: núm[1].append(numero) print ('-= *) print(f' 'todos os numeros: {núm})
3ca625667bf396ffac88095ac91304ceb55e090d
cgleason3462/python-challenge
/PyPoll/main.py
2,563
3.921875
4
import os import csv #route to correct csv pollData = os.path.join("..", "election_data.csv") txtFile = "Poll_data.txt" #Open csv data with open(pollData) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") header = next(csvreader) #Create lists to store data from csv totalVotes = [] c...
d27e2ba6ab69174cf82ba6e051c578273a395571
thalesnunes/Algorithm-Toolbox_Coursera
/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py
521
3.9375
4
# Uses python3 from sys import stdin def get_fibonacci_last_digit(n): if n < 1: return 0 if n == 1: return 1 prev = 0 curr = 1 for _ in range(n - 1): prev, curr = curr % 10, (prev + curr) % 10 return curr % 10 def fibonacci_sum_squares_naive(n): vert = get_f...
249eb4b2466e7db1f0389ad4170ea26abbdefc93
thalesnunes/Algorithm-Toolbox_Coursera
/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/fibonacci_last_digit.py
305
3.96875
4
# Uses python3 import sys def get_fibonacci_last_digit_naive(n): if n <= 1: return n seq = [0, 1] while len(seq) <= n: seq.append(seq[-2]%10+seq[-1]%10) return seq[-1] % 10 if __name__ == '__main__': n1 = int(input()) print(get_fibonacci_last_digit_naive(n1))
110ca5d0377417a8046664b114cfd28140827ed4
christinalycoris/Python
/arithmetic_loop.py
1,741
4.34375
4
import math print ("This program will compute addition, subtraction,\n" "multiplication, or division. The user will\n" "provide two inputs. The inputs could be any real\n" "numbers. This program will not compute complex\n" "numbers. The program will run until the user\n" "chooses to terminate the program. Th...
83ab47cfd6dd6ada617ade9e83fefa8a34cb3fe4
adityaramteke/hacknlearn
/Functions/03_cm_conversion.py
209
3.71875
4
def cm(feet = 0, inches = 0): """ Convert a lenght from feet and inchess to centimeter. """ inches_to_cm = inches * 2.54 feet_to_cm = feet * 12 * 2.54 return inches_to_cm + feet_to_cm cm(2,3)
47e486c1e0aaddc1e4e31a56cb7b4535b46f8c56
leth02/Kattis_Solutions
/gerrymandering.py
1,151
3.515625
4
# Problem name: Gerrymandering; Difficulty: 1.4 line = input() line = line.split(" ") P = int(line[0]) D = int(line[1]) district = {} total = 0 waste_A = 0 waste_B = 0 answer = "" for i in range(P): line = input() line = line.split(" ") distr = line[0] A_vote = int(line[1]) B_vote =...
0d5b83b8d474cf4379fef2905877d96b3cc5214e
kjanjua26/Octofying-COVID19-Literature
/code/classification_death_recovery/preprocess_data.py
3,397
3.53125
4
''' This code file is to preprocess the pandas .csv file made and return the arrays required for training. ''' import pandas as pd import numpy as np from tqdm import tqdm from tensorflow.keras.utils import to_categorical from sklearn.model_selection import train_test_split basepath = '/Users/Janjua/Desktop/Pr...
ab280e21ff6c10d76c5b997c0507f8c3095ddb79
zoubohao/UC_Davis_STA_CS_Coureses
/ECS 32B/Exam1.py
421
3.5
4
def prod_first_k(vals, k): prod = 1 try: for i in range(k): prod *= vals[i] except: print("k is out of index.") return prod def foo(dic:dict): num = 0 for key in dic: if key > dic[key]: num += 1 return num if __name__ == "__main__": p...
248c561ca6856cae765a3e5010e30a90f9e7c28d
zoubohao/UC_Davis_STA_CS_Coureses
/ECS 32A/ECS32A/Ass1/sum_prod.py
196
4.21875
4
fir_num = int(input("Enter first integer: ")) sec_num = int(input("Enter second integer: ")) print("The sum is {}".format(fir_num + sec_num)) print("The product is {}".format(fir_num * sec_num))
f7aafe512f5f10c95305aed1848c3acbde8a231b
zoubohao/UC_Davis_STA_CS_Coureses
/ECS 32A/ECS32A/Ass3/part2.py
127
4.09375
4
n = int(input("Enter N: ")) sumN = 0 for i in range(1,n + 1): sumN = sumN + i ** 2 print("The sum is: {}".format(sumN))
3abd270887ce65d51707153ca409d6a838336d4e
DaryaKatalnikova/Structured-programming
/лаб 5/лаб 5.6.py
703
3.734375
4
arr=[] brr=[] min=0 jmax=0 imax=0 max=0 n=int(input("Введите количество строк")) m=int(input("Введите количество столбцов")) for i in range (0,n): arr.append([]) for j in range (0,m): arr[i].append(int(input("Введите элемент матрицы"))) for i in range (0,n): min = arr[i][0] jmax=0 for j in r...
dfd62eb606777c78030ed13d8acb5a870e7bc1a1
DaryaKatalnikova/Structured-programming
/тестовые/Ex5.py
99
3.625
4
x=int(input("Введите число")) for i in range (1,x+1): if (x%i==0): print(i)
efef68f8b11ccd74e36ec1698836a2d5b3ccc4dd
DaryaKatalnikova/Structured-programming
/тестовые/Ex2.py
278
3.96875
4
a=int(input("Введите первое число")) b=int(input("Введите второе число")) f=int(input("Введите третье число")) if ((a>f)and (a>b)): print(a) else: if ((b>a)and(b>f)): print(b) else: print(f)
c8835b457c4541d7922cd0a7854109b3d42174e0
DaryaKatalnikova/Structured-programming
/лаб 2/лаб 2.3.py
217
4.0625
4
x=float(input("Введите координату х")) y=float(input("Введите координату y")) if (y>=-1)and(y<=1)and(((x<=y)and(x>=-y))or((x>=y)and(x<=-y))): print("yes") else: print("no")
0dadba8c77eacc6ed946109b7ae9b0ad53f2230f
ikostan/ProjectEuler
/Problems_1_to_100/Problem_16/problem_16.py
353
3.671875
4
#!/usr/bin/python import time import math from utils.utils import print_time_log def find_the_sum(number: int, power: int): start_time = time.time() powered_number = int(math.pow(number, power)) n_list = [int(i) for i in str(powered_number) if i != '0'] result = sum(n_list) print_time_log(start...
2801b56fcbc6eab0ce4707324cebca1897b76038
ikostan/ProjectEuler
/Problems_1_to_100/Problem_6/problem_6.py
550
3.9375
4
#!/usr/bin/python import time import math from utils.utils import print_time_log def square_diff(start, end): start_time = time.time() result = int(square_of_sums(start, end) - sum_squares_of_numbers(start, end)) print_time_log(start_time, result) return result def sum_squares_of_...