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
e10b36808bb9a703b75562ef0606fe05f8c1d475
dindamazeda/intro-to-python
/lesson5/2.zip.py
522
3.75
4
fish_meals = ['šaran', 'smuđ', 'pastrmka', 'som', 'oslić'] drinks = ['crveno vino', 'belo vino', 'pivo', 'rakija', 'viski'] for fish, drink in zip(fish_meals, drinks): print('Fish {} goes well with {}'.format(fish, drink)) letters = ['a', 'b', 'c', 'd', 'e', 'f'] numbers = [4, 9, 10, 5, 8, 7, 2, 1] roman_numbe...
05cb1521168d0320f080cd8c25137ea9ef6e91b9
dindamazeda/intro-to-python
/lesson2/exercises/3.number-guessing.py
821
4.1875
4
# Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage) # Go through the list and on every iteration as a user to guess a number between 0 and 10 # At end the program needs to print how many times the user had correct and incorrect guesses # random_numbers = [5, 1, 3,...
227d3c1780cca1ea0979d759c9a383fcdafb2314
dindamazeda/intro-to-python
/lesson1/exercises/6.more-loops_dm.py
612
4.3125
4
# write a loop that will sum up all numbers from 1 to 100 and print out the result ### example ### # expected result -> 5050 sum = 0 for numbers in range(1, 101): sum = sum + numbers print(sum) # with the help of for loop triple each number from this list and print out the result numbers = [5, 25, 66, 3, 100, 34]...
5d3b2c9784126340b8e97a0883723db6e72efd8f
dindamazeda/intro-to-python
/lesson3/8.list-index.py
378
3.953125
4
companies = ['Google', 'Facebook', 'Yahoo', 'Microsoft', 'AirBnb'] index_of_google_in_the_list = companies.index('Google') print(index_of_google_in_the_list) print(companies[index_of_google_in_the_list] == 'Google') where_is_yahoo = companies.index('Yahoo', 0, len(companies)) print('Yahoo is on index {}'.format(whe...
fccc72af94e809451be61c0ea1c4d34c9abf11fc
micalon1/small_tasks
/part7.py
88
3.734375
4
n = int(input("Enter N: ")) a = 0 b = -1 while a < n: print(b) b -= 2 a += 1
bb941f4da9976abb554a43fe2d348ec956587cf1
micalon1/small_tasks
/part5.py
760
4.125
4
shape = input("Enter a shape: ") s = "square" r = "rectangle" c = "circle" if shape == s: l = int(input("What is the length of the square? ")) print("The area of the square is {}.". format(l**2)) elif shape == r: h = int(input("What is the height of the rectangle? ")) w = int(input("What is the ...
108bccecfb837792c9fb195598ef5c09ba8c0aa1
sejaljain/coms4701
/image_classification_CNN.py
5,769
3.65625
4
''' It seems that classification into 10 categories can be interpretted as a series of binary classification problems which would imply that classification across 10 categories is more difficult than binary classification. For example, if there were only 3 categories: a, b, c, then the problem could be interpretted as...
1f43a015852ca887eec9a0ac14e2b64d22ddb0af
conorhoughton/teaching_misc
/python_workshop/code/star.py
398
4.03125
4
from turtle import * tom=Turtle() for i in range(0,10): tom.forward(100) if i%2==0: tom.right(144) else: tom.left(72) #this hides the turtle tom.hideturtle() #these two lines are for saving the image ts = tom.getscreen() ts.getcanvas().postscript(file="star.eps") #this is needed in some...
1cec5b85c917421872f6db5d3045cad00e75e327
miguelcapaz7/MP3-Player
/song.py
2,564
3.578125
4
from audio_file import AudioFile from sqlalchemy import Column, Text class Song(AudioFile): """Represents a song track that is a subclass of AudioFile Author: Miguel Capaz ID: A01167207""" """ ORM: map db columns to instance variables in this class """ album = Column(Text) genr...
b2c4410ad1562e891b473ea388a7c898b83126df
jdiethelm/python_public
/backend.py
1,657
3.734375
4
import sqlite3 import csv import pandas as pd class Database: def __init__(self,db): self.conn=sqlite3.connect(db) self.cur=self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") self.c...
16d3aa6f15237a8210e85e18af868d2d04cd53c4
shanchu815/calculator-2
/calculator.py
2,117
3.9375
4
"""CLI application for a prefix-notation calculator.""" from functools import reduce #reduce(lambda a, b: a+b, lis) #reduce(lambda a, b: b = int(b), lis) ??? from arithmetic import (add, add_infinite, subtract, multiply, divide, square, cube, power, mod) # Replace this with your code "repeat...
c381fe1827473d9d60d0476dcfbe9485d4750262
LRL/scb
/python_package/lesson_03.py
5,986
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/18 13:45 # @Author : Lemon_Tricy # @QQ: 2378807189 # Copyright:湖南省零檬信息技术有限公司 # python:列表,字典,元组,集合 ''' 列表(list):[],多个元素之间用逗号隔开 1、元素可以是任意数据类型:整型(int),浮点型(float),布尔型,字符串,列表.... 2、取值: 也可以通过索引取值,从0开始 取多个值:切片 3、 列表额元素可以被改变的!! 增删改操作 增加:append insert 删除: 修改...
4907ee37c7d9841a113be45d99d1bf33c9ad3262
nikolajchonev2020/Paython-Coursework
/application/main.py
1,556
3.90625
4
from Teacher import * def heppy_teacher(): teach.birthday() teach.print() def teacher_teaches(): teach.teach() def teacher_print(): teach.print() def teacher_pay_amount(): amn = float(input("How Teacher pay: ")) teach.pay(amn) teach = None teach_name = "" teach_city = "" ...
d0d8247108b34b278fc5286851693ecfdf20e821
borowiecmichal/Prework_dod
/z8.py
243
3.765625
4
'''napisz funkcja która bedie wyliczać pierwiastek liczby, z zadaną dokłdnościa''' def root(num, rnd): return round((num**(1/2)), rnd) x = int(input("Oblicz pierwiastek z: ")) y = int(input("Z dokładnoscią: ")) print((root(x,y)))
5b7be8d073a5d8fa58c53664e68065249f34350c
mnojha/sales-tax
/receiptDetails.py
1,640
3.921875
4
basic_sales_tax = 0.1 imported_sales_tax = 0.05 sumit=0 def main(): imported_item1 = float(input("Enter price of imported perfume : ")) non_imp_item = float(input("Enter price of perfume : ")) medical_item = float(input("Enter price of headache pills : ")) imported_item2 = float(input("Enter price of imported choco...
7bd385f1465918ac1c73311062647516a0d8ce74
ritesh2k/python_basics
/fibonacci.py
328
4.3125
4
def fibonacci(num): if num==0: return 0 elif num==1: return 1 else: return fibonacci(num-1)+fibonacci(num-2) #using recursion to generate the fibonacci series num=int(input('How many fibonacci numbers do you want? \n')) print('Fibonacci numbers are :\n') for i in range(num): print(fibonacci(i) , end=' ') p...
7c3e9c6db39509af1c38818f60a5b9c9697697c4
ritesh2k/python_basics
/sentence_capitalization.py
429
4.3125
4
def capitalization(str): str=str.strip() cap='' for i in range(len(str)): if i==0 or str[i-1]==' ':cap=cap+str[i].upper() #checking for the space and the first char of the sentence else: cap=cap+str[i] #capitalizing the character after space #cap =[words[0].upper()+words[1:]] print ('The result i...
4ed4ec3ddacc74b93c28a1f6c395743be9939789
ritesh2k/python_basics
/binary.py
193
4.3125
4
def dec_to_binary(num): binary='' while(num>0): binary=str(num%2)+binary num=num//2 print (binary) num=int(input('Enter the decimal number to convert to binary')) dec_to_binary(num)
8f6b7e83e69398fd932b598f687bc7cd8f4d35b1
Sheldon21/SzaboDora_beadandok
/beadando_masodikFeladat.py
632
3.828125
4
import string def From10to(number, b): if number>=0 and 1<b<11: converted = '' while number > 0: converted=str((number%b))+converted number //= b return converted #....... def FromOtherTo10(number, b): if 1<b<11: return int(number, b) #.....
f345a11ad432fdee517837ff3e3d84df0a72de54
andrehp/pyecc
/point_simple.py
1,174
3.515625
4
from utils import modinv class Curve: pass class Point: def __init__(self, xx=0, yy=0, zz=0): self.x = xx self.y = yy self.z = zz def __eq__(self, other): return (self.x == other.x and self.y == other.y and self.z == other.z) def __ne__(self, other): return no...
0b9ffe29f31ba084dd0d68f1cba09be2556cd7bf
huebnerbryan/Repo_Lab_3
/Counting_words.py
1,190
3.84375
4
## Name: Bryan Huebner ## Date: 15 October 2014 ## Class: T_GIS 501 ## Description: Script for counting words in a text file. Lab_3_text = open('E:\\GIS_501\\Labs\\Lab_3\\GIS_is_the_best.txt') # open path file_list = Lab_3_text.read() # read text file system_count, science_count, total_words = 0,0,0 # words...
5b63eeafb6113d540ff3894f82fc52d7f84e3be9
dforoni/estrutura-de-dados
/src/VetorNaoOrdenadoVsVetorOrdenado.py
3,887
3.5625
4
# Vetor não ordenado import numpy as np class VetorNaoOrdenado: def __init__(self, capacidade): self.capacidade = capacidade self.ultima_posicao = -1 self.valores = np.empty(self.capacidade, dtype=float) def imprime(self): if self.ultima_posicao == -1: print('O vetor está vazio') else: ...
7a6c27963f8e1adcba4b636cd29fdf598acdde0b
YeasirArafatRatul/Python
/reverse_string_stack.py
492
4.125
4
def reverse_stack(string): stack = [] #empty #make the stack fulled by pushing the characters of the string for char in string: stack.append(char) reverse = '' while len(stack) > 0: last = stack.pop() #here the pop function take the last character first thats why ...
817a383769b024049a81ad3e76be36231099462d
YeasirArafatRatul/Python
/reverse_string_functions.py
340
4.625
5
def reverse_string(string): reverse = "" #empty for character in string: """ when we concate two strings the right string just join in the left string's end. """ reverse = character + reverse return reverse string = input("Enter a string:") result = reverse_string(st...
fca8276d6e4f3589c2c80b9429b3b4738cdc581e
YeasirArafatRatul/Python
/find the word with prefix string.py
344
3.96875
4
#a functin that returns the strings which start with the given prefix def function(a_list,prefix): n = len(a_list) output_list = [] for i in range(0,n): if a_list[i].startswith(prefix): output_list.append(a_list[i]) return output_list List = ['abcd','safj','aue','adfa'] pre = 'a' pr...
e9cf8c2d5b0a2059bb30a0bc6b6726da8d22eb6e
YeasirArafatRatul/Python
/DummyExercises/multiple decorator in string.py
408
3.71875
4
def upper_d(func): print("I am upper_d") def inner(): print("I am inner") str1 = func() return str1.upper() return inner def split_d(func): print("I am split_d") def wrapper(): print("I am wrapper") str2 = func() return str2.split() return wrapper...
cbdeffd1b67544da6840a2bd731c981c2a5a46c4
YeasirArafatRatul/Python
/DummyExercises/map().py
326
3.8125
4
def celcius_to_fahrenheit(temp_in_celcius): temp = (temp_in_celcius*1.8)+32 return temp list_of_temp = [20,22,24,32,35,28,30] for i in list_of_temp: print(type(i)) print(celcius_to_fahrenheit(i)) print(list(map(celcius_to_fahrenheit,list_of_temp))) print(list(map(lambda x: (x*1.8)+32, list_of_te...
523ea30823aebbc80a7bfd1cdd62967b34a179f3
YeasirArafatRatul/Python
/climbingTheLeaderboard.py
490
3.796875
4
import math import os import random import re import sys # Complete the climbingLeaderboard function below. def climbingLeaderboard(scores, alice): scores = sorted(list(set(scores))) print(scores) index = 0 rank_list = [] n = len(scores) for i in alice: while (n > index and i >= score...
1a47200450265fd915c606ee463cd513d446bacb
YeasirArafatRatul/Python
/DummyExercises/DelayMultiplicationTable.py
125
3.609375
4
import time for a in range(1,11): print('\n') time.sleep(3) for b in range(1,11): print(a,"x",b,"=",a*b)
1fbe75ce3515b54e2183ee4da6a1177aaad953c5
YeasirArafatRatul/Python
/DummyExercises/coursera_digits_in_number_coursera.py
286
3.609375
4
def digits(n): count = 0 if n == 0: return 1 while (n > 0): n = n // 10 count += 1 return count print(digits(25)) # Should print 2 print(digits(144)) # Should print 3 print(digits(1000)) # Should print 4 print(digits(0)) # Should print 1
c631b11574b23cbfb30f1e34799f5476bcc29eef
YeasirArafatRatul/Python
/DummyExercises/decorator with arguments.py
326
3.828125
4
def decorator(func): def square_func(a,b): x = a**2 y = b**2 value = func(x,y) return value return square_func @decorator def function(a,b): return a+b if __name__ == "__main__": first_num = int(input()) second_num = int(input()) print(function(first_num,second_...
f7a6cd7717a980dc91ecea4376121aebefa62e33
YeasirArafatRatul/Python
/SortingAlgorithms/HR BIG SORTING.py
472
3.984375
4
def bigSorting(unsorted): unsorted.sort() return (unsorted) #different def bigSorting2(unsorted): unsorted.sort(key = lambda x : (len(unsorted),x)) return(unsorted) if __name__ == "__main__": data_list = [] # number of elemetns as input n = int(input()) # iterating till the rang...
c3e0d4f07ab4a29eb4c1fec2b2cba711f7da7f5e
YeasirArafatRatul/Python
/DummyExercises/ARGPARSE for Command Line interface.py
860
3.6875
4
import argparse import sys def calc(args): if args.operation == 'add': return args.x + args.y elif args.operation == 'sub': return args.x - args.y elif args.operation == 'mul': return args.x * args.y elif args.operation == 'div': return args.x / args.y def main(): ...
824f7cfbad46b89014266702fa240a9db8454111
YuanLIAOcode/Leetcode
/Hash Table/349.intersection_of_two_array.py
387
3.953125
4
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1 = set(nums1) nums2 = set(nums2) return list(nums1 & nums2) num1 = [1,2,2,3,4,2,5,8,9,1,10] num2 = [2,3,4,2,5,6...
8bbc410621ef4f7d11f6d27d44db659b7abac1d2
OmriMeshulam/FizzBuzz-Challenge
/Python/FizzBuzz.py
667
3.84375
4
# Fizzbuzz in Python. # # This is the straightforward, traditional version with nested # if-statements. # class FizzBuzz(): """Class doing FizzBuzz.""" def do_fizzbuzz(self, m): """Return m, fizz, buzz or fizzbuzz as appropriate.""" if (m % 15) == 0: return 'fizzbuzz' elif ...
fa482a5261adff46f2c2bc649be121eb850178d0
tnotstar/tnotbox
/Python/Learn/Pytest0/portfolio.py
442
3.5
4
# -*- coding: utf-8 -*- class Portfolio(object): """A simple stock portfolio""" def __init__(self): self.stocks = [] def buy(self, name, shares, price): """Buy `shares` shares of `name` at `price`""" self.stocks.append([ name, shares, price ]) def cost(self): """What w...
f0186ab2b92bc2042edfe88b6d03091e6b9326d8
tnotstar/tnotbox
/Python/Learn/FreeCodeCamp/Tkinter/03_buttons.py
327
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tkinter import * root = Tk() def on_click_me(): label1 = Label(root, text="Look! I clicked a button!") label1.pack() # this one creates a button button1 = Button(root, text="Click Me!", pady=2, command=on_click_me, fg="red") button1.pack() root.mainloop()...
ffad7b18dc87b03c33146a7c60f1e79e3044c85c
tnotstar/tnotbox
/Python/Stdlib/zipfile/read.py
188
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 from zipfile import ZipFile with ZipFile("example.zip") as zip: buffer = zip.read("spanish/example2.txt") print(buffer.decode()) # EOF
2c5b1e85b26ea93a1f6636758db8889b28b7798a
tnotstar/tnotbox
/Python/Learn/LPTHW/ex06_dr01.py
822
4.5
4
# assign 10 to types_of_people types_of_people = 10 # make a string substituting the value of types_of_people x = f"There are {types_of_people} types of people." # assign some text to some variables binary = "binary" do_not = "don't" # make a string substituting last variable's values y = f"Those who know {binary} and...
d854d2f8e29e061f085af15ac1da61b4cf9a6283
wendotdot/my-first-blog
/tutorial.py
280
4.21875
4
if 5 > 2 : print("5 is greater than 2") else : print("5 is not greater than 2") name = "Wendy" def hi(name): #print("Hi There") #print("How are you?") if name == "Ola": print("Hi Ola!") elif name == "Sonja": print("Hi Sonja!") else: print("Hi Anonymous") hi(name)
833d91dfe8f65ce41b7dfa9b4ae15632a03e6170
undefinedmaniac/AlexProjects
/Basic Python Concepts/if statements and loops.py
1,580
4.40625
4
# If statements are used to make decisions based on a conditional statement # for example, the value in a variable could be used variable1 = True variable2 = False if variable1: print("True") # else if statements can be added to check for additional conditions if variable1: print("Variable 1 is True") elif ...
514d48a3226c0a919ea44c5c35ab2e004c25e8e0
Raghaava/algorithms
/heap/MinHeap.py
1,671
3.828125
4
# pow(2, h+1)-1 is size of the tree # log n is the height of the tree. # o(n log n) time and space complexity. def heapify(arr): n = len(arr) # indices floor(n/2+1) -> n are leave nodes # in any complete/almost complete binary tree. # iterate through all parents from last parent to first. for in...
7bdf34c295940f90e253ef63501e5f83a56a8b2e
JerryHaaser/Sprint-Challenge--Hash
/hashtables/ex3/ex3.py
837
4.03125
4
def intersection(arrays): """ YOUR CODE HERE """ num_dict = {} result = [] # sort arrays arrays = sorted(arrays, key=lambda x: len(x)) # iterate through lists # compare first value to all other values # if all list contain this value, append to result for element in a...
971247c94cba717a85b4d900b0f93ae2bb6338a1
radek-coder/simple_calculator
/run_it.py
636
4.21875
4
from addition import addition from multiplication import multiplication from division import division from subtraction import subtraction num_1 = int(input("Please insert your first number: ")) num_2 = int(input("Please insert your second number: ")) operation = input("Please insert your operation ") if operation == ...
65d1733f98ffe14c674786b766f8e2eec6d62ce7
JTermens/APA-Project-Networks
/networktools.py
27,444
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #-------------------------------------------------------------------------------------------------- # APA PROJECT LIBRARY NETWORKTOOLS # # This code is degined to generate and filter graphs, search communities on it with the Louvain or # bining algorithm, characterize the ...
76939a88c6f677fa60c7da942087b108f1f09ee1
wesley4546/twitter_annotation
/source/annotator_program.py
2,152
3.5
4
import webbrowser import pandas as pd import csv from source.questionnaire import questionnaire """ This function is made to take in the annotation_(name).csv file and a output file name then do the following: 1. Open the twitter user 2. Start the questionnaire 3. Append the output annotation file """ def annot...
b325c01d8bc8b355884a07a09ec164e636a62545
rpivo/codewars-answers
/what-is-between.py
125
3.765625
4
def between(a, b): arr = [] for num in range(min(a, b), (max(a, b) + 1)): arr.append(num) return arr between(1, 3)
f88b699c69329d90c31d9b9d18ca19bb7f671090
Arl-cloud/Python-basics
/basics5.py
2,327
4.28125
4
#For loops: How and Why monday_temperatures = [9.1, 8.8, 7.6] print(round(monday_temperatures[0])) #print rounded number with index 0 #in 1st iteration, variable temp = 9.1, in the 2nd iteration 8.8 for temp in monday_temperatures: print(round(temp)) #executed command for all items in an array print("Done") ...
221da6841c1d2054768256096d52c5c2552bb6a6
pwgraham91/Python-Exercises
/move_zeroes.py
1,523
4.03125
4
""" Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extr...
ae35bfc0d8c5057a7d70cf79a272a353a0f15cf4
pwgraham91/Python-Exercises
/shortest_word.py
918
4.34375
4
""" Given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types. """ def find_short_first_attempt(string): shortest_word_length = None for word in string.split(' '): len_word = len(word) if shortest_wor...
4ab03d28d3a11121c0f0cd9b31419a159cdce6c2
pwgraham91/Python-Exercises
/binary_search.py
1,008
3.609375
4
def run(list, target): minimum_index = 0 max_index = len(list) - 1 if list[max_index] == target: return max_index while minimum_index <= max_index: middle_index = (minimum_index + max_index) // 2 middle_value = list[middle_index] if target > middle_value: if...
3a613065567496a21da68b7769a2309bce8e5353
pwgraham91/Python-Exercises
/program_alarm/alarm.py
1,793
3.59375
4
""" https://adventofcode.com/2019/day/2 """ def solve(): with open("./input.txt") as steps_text: steps = [int(x) for x in steps_text.readline().split(",")] steps[1] = 12 steps[2] = 2 current_step_index = 0 while True: current_step = steps[current_step_index] ...
ea4642f55685a6d262806b3859e0c43abd109313
pwgraham91/Python-Exercises
/buy_toys.py
524
3.75
4
""" https://www.hackerrank.com/challenges/mark-and-toys/problem """ def max_toys_sorted(prices, money): prices.sort() i = 0 for i, value in enumerate(prices): if money >= value: money -= value else: return i else: return i + 1 assert max_toys_sorted([1...
dc9a10c8f8f1cd1c46f78c475ed1ca57cc381ee1
pwgraham91/Python-Exercises
/process_binary.py
494
4.15625
4
""" Given an array of one's and zero's convert the equivalent binary value to an integer. Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1 """ def binary_array_to_number(array): output = '' for i in array: output += str(i) return int(output, 2) assert binary_array_to_...
fd618e63697645261a0ac3c6da904a60099ee877
pwgraham91/Python-Exercises
/count_x_o.py
619
4.09375
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 other characters as well. You are only concerned with whether it has the same number of Xs and Os. """ def count_xo(string): count_x = 0 count_o =...
5177272e7491e085f112c5c55e36cf8ace45b80a
pwgraham91/Python-Exercises
/excel_conversion.py
1,232
4.0625
4
""" Microsoft Excel numbers cells as 1...26 and after that AA, AB.... AAA, AAB...ZZZ and so on. Given a number, convert it to that format and vice versa. """ import string alphabet = string.ascii_uppercase def _generate_prefix(indices): try: return ''.join([alphabet[index] for index in indices]) exce...
8239cd4085eb2ce30204f157a14016ca1aa2bc68
pwgraham91/Python-Exercises
/repeated_string.py
2,007
4
4
""" Lilah has a string, , of lowercase English letters that she repeated infinitely many times. Given an integer, , find and print the number of letter a's in the first letters of Lilah's infinite string. For example, if the string and , the substring we consider is , the first characters of her infinite string. T...
9b8ee1df25e986a9ad3abd9134abda3f6d3970f5
pwgraham91/Python-Exercises
/sock_merchant.py
990
4.71875
5
""" John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are socks with colors . There is one pair of color and one of colo...
db157f825a747fb490d160f5e2bdcb9bf3ace3bd
pwgraham91/Python-Exercises
/linked_list_any_combo_palindrome.py
877
4.03125
4
from linked_lists import LinkedList """ determine if any combination of the linked list is a palindrome """ def is_any_combo_ll_palindrome(linked_list): num_letters = 0 unaccounted_letters = set() while linked_list is not None: num_letters += 1 current_value = linked_list.val if cu...
b1a8e3a0b595a2672b5fef53cad1c7dec44258d3
pwgraham91/Python-Exercises
/median.py
321
3.65625
4
__author__ = 'petergraham' def median(data): data.sort() if len(data) % 2 == 0: under = data[int(((len(data) - 1) / 2.0) - .5)] over = data[int(((len(data) - 1) / 2.0) + .5)] return (under + over) / 2.0 else: return data[len(data) / 2] print(median([3, 6, 20, 99, 10, 15])...
e12ae1d6ba16317a15a16cdce3aca15fa1e19cf6
pwgraham91/Python-Exercises
/most_wanted_letter.py
625
3.859375
4
__author__ = 'petergraham' def get_most_common_letter(text): letter_count = {} current_high_letter = { 'letter': None, 'count': 0 } for letter in text: lower_letter = letter.lower() letter_count[lower_letter] = 1 + letter_count.get(lower_letter) if letter_count.get(low...
b5e9953ef13586c8e6fe62b7c890a91c5e215c6d
pwgraham91/Python-Exercises
/cake_thief.py
3,337
4
4
""" Write a function max_duffel_bag_value() that takes a list of cake type tuples and a weight capacity, and returns the maximum monetary value the duffel bag can hold. cake_tuples = [(7, 160), (3, 90), (2, 15)] capacity = 20 # Returns 555 (6 of the middle type of cake and 1 of the last type of cake) max_duffel_bag...
f63823f16068b16083e1b30cd20a4d10d34df116
Augustlongpeaceful/SplunkforAviatrix
/bin/external_lookup.py
2,625
3.875
4
#!/usr/bin/env python from __future__ import print_function import csv import sys import socket """ An adapter that takes CSV as input, performs a lookup to the operating system hostname resolution facilities, then returns the CSV results This is intended as an example of creating external lookups in genera...
b7e2e4c96499ad5d2944e92ed9497b40c9331cbd
enisteper1/ML_with_and_without_sklearn
/Multinomial_Logistic_Regression/MultinomialLR.py
1,111
3.53125
4
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB import matplotlib.pyplot as plt import numpy as np import pandas as pd def main(): # Because of y is between 0-10 Multinomial Logistic Re...
f31caceed9451184e2abd5f28c6cbb4695f07f72
enisteper1/ML_with_and_without_sklearn
/K-Means/K-Means_with_equations.py
3,893
3.546875
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from math import sqrt class KMeans: # Get cluster number and initialize variables def __init__(self, cluster_num=3): self.cluster_num = cluster_num # List of clusters self.cluster_list = None # List of centro...
202ee467a957d9eb8c4ce5cad6fc450ad9cb2dcf
AvaniKale20/VectorInPython
/Matrix.py
666
3.875
4
from numpy import * import numpy as numpy matrixOne = numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) print matrixOne print print ("size of matrix", matrixOne.size) print # Addition of matrix matrixTwo = numpy.array([[1, 2], [1, 2]]) print ("matrix two with 2*2 diamentional") print matrixTwo matrixThree = numpy.array...
730de4969e4e6d63437fb80ec301e3711eed2daa
stevenolay/Building-Data-Structures-From-Scratch
/HashTable-Using-LinkLists/linkedlist.py
3,201
3.921875
4
class ListNode(object): def __init__(self, key, val): self.val = val self.key = key self.next = None class LinkedList(object): def __init__(self): self.root = None def __str__(self): curr = self.root collect = [] while curr: collect.append([curr.key,curr.val]) curr = curr.next return str(coll...
8a886e4fc45907c8ff1be76f6549283d005b57bd
victorcwyu/python-playground
/learn-python/string-formatting.py
677
4.03125
4
name = "John" print("Hello, %s!" % name) age = 23 print("%s is %d years old." % (name, age)) mylist = [1, 2, 3] print("A list: %s" % mylist) # %s - string (or objects with a string representation, like numbers) # %d - integers # %.<number of digits>f - floating point numbers with a fixed amount of digits to the right o...
7c9c234858d6903b255c291661ae61787f7c8a4f
victorcwyu/python-playground
/learn-python/functions.py
1,273
4.375
4
# divide code into useful blocks # allows us to order code, make it more readable, reuse it and save time # a key way to define interfaces to share code # defined using the block keyword "def", followed by the function name as the block name def my_function(): print("Yolo") # may receive arguments (variables pass...
f515c806b5240f92a077dd7ded268eaa19e8edd2
victorcwyu/python-playground
/python-crash-course/string-replacement.py
512
4.125
4
# exercise: use Python's string replace method to fix this string up and print the new version out to the console journey = """Just a small tone girl Leaving in a lonely whirl She took the midnight tray going anywhere Just a seedy boy Bored and raised in South Detroit or something He took the midnight tray going anywhe...
84bd0d4db2706319680706e1cd0621ed313fa034
Utkarshkakadey/Assignment-solutions
/Assignment 1.py
1,053
4.40625
4
# solution 1 # Python program to find largest # number in a list # list of numbers list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the last element print("Largest element is:", list1[-1]) #solution 2 a=[] c=[] n1=int(input("Enter number of elements:")) for i in range(1,n1+1...
36ca26358ff16d783d4b7bc0b24e2768879ef9b4
NadezhdaBzhilyanskaya/PythonProjects
/Quadratic/src/Bzhilyanskaya_Nadja_Qudratic.py
2,751
4.125
4
import math class Qudratic: def __init__(self, a,b,c): """Creates a qudratic using the formula: ax^2+bx+c=0""" self.a = a self.b = b self.c = c self.d = (b**2)-(4*a*c) def __str__(self): a = str(self.a) + "x^2 + " + str(self.b) + "x + " + str(se...
0efad83c1e7142b03ef44c356cafb7743de6be53
Vitaliy8791/Py_H_W_4
/hw_4_1.py
2,664
3.71875
4
from string import whitespace, punctuation, ascii_letters, digits enter_num = [] enter_char = [] fltterstr = whitespace + punctuation + digits def clear_word(enter_string, filt): # функция проверяет текст на символы не из английского алфавита enter_char = [] enter_list = list(enter_string) # преоб...
5e5ea71504ba621e9009754c393340dd7b7bcc5d
Dlac/Python-For-Everybody
/exer46.py
491
4.09375
4
#Rewrite your pay computation with time and a half #for overtime and create a function called computepay #which takes two parameters (hour and rate) #hours 45 #rate 10 # pay 475 def computepay(h,r): if h<=40: p = r* h else: p = r * 40 + (r * 1.5 * (h - 40) ) return p try: inp = raw_input("Enter Hours: ") h...
683cac050f6bd485b6f54c15a8fa7a44a6e9354a
kreddy0404/Text-Generator-NLP
/Topics/Operations with dictionary/Extreme Points/main.py
435
3.84375
4
# The following line creates a dictionary from the input. Do not modify it, please test_dict = json.loads(input()) # Work with the 'test_dict' min_value = min(test_dict.values()) max_value = max(test_dict.values()) min_key = "" max_key = "" for key in test_dict.keys(): if test_dict[key] == min_value: min_...
f2b7692d139cfd94450008244a6f61068ff8893a
eliasKA/streamlit_fifa
/src.py
1,346
3.53125
4
import pandas as pd import numpy as np import streamlit as st st.title('Premier League: Interactive Data Analysis') df_epl = pd.read_csv('Data/epl_data.csv') df_epl['Season'] = df_epl['Season'].map(lambda x: x.split('/')[0]).astype('int64') st.write("Sample of the dataset:", df_epl.tail(20)) club = st.selectbox('Clu...
656316a81683a7a77887e43c6ced3ac1ff1f7466
neelgandhi108/AI_sudoku_solver
/helpers.py
2,598
3.90625
4
from setup import row_units, column_units, diagonal_units, square_units, boxes, rows, columns def grid_values(str_board): """ Convert grid into a dict of {square: char} with '123456789' for empties. Args: grid(string) - A grid in string form. Returns: A grid in dictionary form ...
205ba53a26a595190875819911dd2bf6e27cba10
MaxiVargas78/DesafioLatamPython
/Desafios Modulo II/Desafio I/solo_pares_refactor.py
154
3.921875
4
n = int(input("ingrese un valor para calcular pares: ")) i = 0 for i in range(n+1): if i % 2 == 0 and i !=0: print(i) else: None
093b900746b63ec28f2df85cd60fa75aee4b9fff
MaxiVargas78/DesafioLatamPython
/Desafios Modulo III/Desafio I/asociar.py
989
3.5625
4
from velocidad import * matrix = [] for lista in zip(vel, distancia): matrix.append(lista) matrix1 = [] for j in matrix: matrix1.append(j[0]) matrix2 = [] for k in matrix: matrix2.append(k[1]) a = promedio(matrix1) b = promedio(matrix2) count = 0 for i in range(len(matrix1)): if (matrix1[i] < a): ...
68202e160654a74f879656915b632679e51ccb89
lmaywy/Examples
/Examples/Examples.PythonApplication/listDemo.py
1,041
4.25
4
lst=[1,2,3,4,5,6,7] # 1.access element by index in order print 'access element by index in order'; print lst[0]; print 'traverse element by index in order ' for x in lst: print x; # 2.access element by index in inverse order print 'access element by index in inverse order' print lst[-1]; length=len(lst...
04bfbbc9ba2abe94021e9853336977eb11b4a6b0
RicSegundo/HackerRank
/Solved/ViralAdvertising.py
249
3.71875
4
import math n = 5 def viralAdvertising(n: int) -> int: likes = 0 people = 5 for day in range(1, n+1): likes += math.floor(people/2) people = math.floor(people/2) * 3 return likes print(viralAdvertising(n))
80a58c65baa01c02bdad5d8d28294596605f4cbc
OnlyHyun/Python
/fibonacci.py
344
3.53125
4
n = int(input("정수 n을 입력하라: ")) count = 2 s = [0, 1] while True: if(s[count-1] + s[count-2] > n): break s.append(s[count-1] + s[count-2]) count += 1 print(s) """ n = int(input("정수 n을 입력하라: ")) a, b = 0, 1 print('0', end = ' ') while b <= n: print(', %d' % b, end='') a, b = b, a+b """
78c21e33f30def17b206a1003101bf19c7953d9e
ytkgit/py_play
/zip.py
954
3.71875
4
# import urllib.request # import urllib.parse # API = "https://api.aoikujira.com/zip/xml/get.php" # code = int(input("What\'s your zip code? input 7 code: ")) # values = { # 'fmt' : 'json', # 'zn' : code # } # params = urllib.parse.urlencode(values) # url = API + "?" + params # print("url=", url) # data = u...
1f4619da7153fa21df1f9bb5b8b647bc566c41c5
Piero942/calculadora
/t03alfaro/ejercicio3.py
331
4.34375
4
#Algoritmo para hallar la resta de 3 numeros numero1,numero2,numero3,resta=0.0,0.0,0.0,0.0 #asignacion de valores numero1,numero2,numero3=35.9,25.5,7.4 #calculo resta=numero1-numero2-numero3 #mostrar valores print("la numero1 es",numero1) print("la numero2 es",numero2) print("la numero3 es",numero3) print("la resta ...
ba78368c65dadee28789f6315f783e501cb4be88
Piero942/calculadora
/t03alfaro/ejercicio10.py
245
3.84375
4
#Algoritmo para hallar el area de un rectangulo lado1,lado2,area=0.0,0.0,0.0 #asignacion de valores lado1,lado2=2.8,5.4 #calculo area=lado2*lado1 #mostrar valores print("el lado1 es",lado1) print("el laso2 es",lado2) print("el area es",area)
815d65b9a79274eeb785533d83a905ac8f5d9de7
BorisKolev/Python-OOP-Deck-Of-Cards
/Player.py
1,227
3.734375
4
""" Player class Created: 15/01/2019 Author: Borislav Kolev """ from Deck import Deck class Player(object): def __init__(self, name, age): self.hand = [] self.name = name self.age = age def draw(self, deck): # The argument we are passing is a deck created fr...
8e76e8cea5754cbf0d6d14bdcefdc6e54e514c3f
geoffcorvera/Music_Generator
/lstm.py
10,168
3.546875
4
""" Adapted from Christina Kouridi's blog post "Implementing a LSTM from scratch with Numpy": https://christinakouridi.blog/2019/06/20/vanilla-lstm-numpy/ """ import numpy as np import matplotlib.pyplot as plt # "Adam" optimiser # Xavier initialisation (involves random sampling) # Create LSTM input vectors (dimensi...
526312e9a440036d5ae7c3ac3ddcf34c165b18d2
masa3141/procon
/AOJ/CGL_4_A.py
1,254
3.65625
4
# -*- coding: utf-8 -*- N = int(input()) data = [] for i in range(N): x, y = map(int, input().split()) data.append((x, y)) data.sort() #上側の凸包を求める def isClockwise(a, b): ax, ay = a bx, by = b cross = ax*by - ay*bx if cross <= 0: return True else: return False ans1 = [data[...
4918f8b7f9e1e4c86dca1dcef58ab67b333e22d6
masa3141/procon
/Atcoder/ARC/079/check_divide.py
157
3.625
4
# -*- coding: utf-8 -*- import math N = int(input()) for i in range(N): for j in range(1,N): if i//j != math.floor(i/j): print(i,j)
62d8c229f14671d1ffacfcd65a667a1bce570b9b
aguynamedryan/challenge_solutions
/set1/prob4.py
2,219
4.28125
4
# -*- coding: utf-8 -*- """ Question: Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string s, which contains only non-zero digits. 
This function should print the length of longest contiguous substring of s, such that the length of the substring is2*N digits and the...
3f728174c5048b37f550d7c95493606b8c8df6e7
tobraga/Learning-Python-3
/Primeiros Comandos/desafio_2-entrar com a data de nascimento e mostrar formatada.py
205
3.9375
4
print('Entre com a data de nascimento') print('#'*30) dia = input ('DIA:') mes = input('MES:') ano = input('ANO:') ### print('####') print('Você nasceu no dia '+dia+' de '+mes+' de '+ano+'. Correto?')
7f275fd68ef75aa3bff775177c55292c1a8cb5f4
AmimoAustin/OOP-Basics1
/File I/File IO.py
870
3.78125
4
class Human: def sayHello(self, name=None): if name is not None: print('Hello ' + name) else: print('Hello ') obj = Human() # Call the method, else part will be executed obj.sayHello() # Call the method with a parameter, if part will be executed obj.sayHello('Rahul') #...
1a534e03ba7774f87b18cf2f093d0a815d548dcd
AlAtEX/Infinite_Dungeon_Experience
/Textgame/Configfiles/Events/Comments/eventWriter.py
5,614
3.53125
4
with open(input('File name without extention:\n')+'.txt', 'w') as x: position = 'main' currentdepth = 0 currentnums = {} length = {} end = False x.write(input('Text shown when event starts: ') + '\n') #end: tells the computer to end the current tag. while True: item = in...
397272b9240bb35d43542d541bd33951a0c83c0c
xiangqianzsh/usefull_scripts
/pybin/dictstr2dsv.py
2,887
3.515625
4
#coding:utf-8 import sys import os import argparse ''' dictstr2dsv.py input: line of python dict string (print dict) if you want your output to be orderd, please contain a key __output_fields__ output: csv/excel format data, sep by tab by default for example: # test.txt {'__output_fields__': ['name', 'score'], '...
69fc3c97246a8bfb0880e01e66a3ae8773eb3541
aksinghal5590/CSE544
/src/H4.py
3,647
3.640625
4
#!/usr/bin/env python # coding: utf-8 # #### Hypothesis: amount of loan lent per month is a time series. We try to predict total amount that will be lent on a month # In[1]: import numpy as np # In[2]: import pandas as pd # In[90]: import matplotlib.pyplot as plt import pylab # In[67]: df = pd.read_csv(...
fbbf75e32f57032e8ab2be65a712ead6704e559e
Kimuksung/bigdata
/python/function.py
1,182
3.65625
4
''' 함수의 가변 인수 - 한개의 가인수로 여러개의 실인수를 받는 인수 def function(*value) *value -> 가변 인수 ''' # 1. tuple 형으로 받는 가변 인수 def fun1(name,*names): print(name) print(names) print(type(names)) fun1('홍길동','이순신','유관순') # package , module import scatter.scatter_module from scatter.scatter_module import Avg,var_std # from pac...
602aa38aab6e7bcf043ece494d91bd5ee5d11961
Kimuksung/bigdata
/python/wordcount.py
1,947
3.53125
4
''' 1. pickle file laod 2. text 전처리 3. word count ''' import pickle # 1. pickle file load file = open("../data/new_crawling.pickle" , mode= 'rb') news_crawling = pickle.load(file) print(type(news_crawling)) print(news_crawling) # 2. 텍스트 전처리 def clean_text(texts) : from re import sub # gsub() 유사함 # 1. 소문자 변...
82a75efd837784c6c1c3369ede53600fb7d319a2
Kimuksung/bigdata
/python/override.py
868
3.78125
4
''' method override - 부모의 원형 메소드 -> 자식에 원형 메서드를 다시 작성하는 문법 - 상속관계에서만 나오는 용어 - 인수, 내용 -> 수정 대상 다형성 - 상속 관계 용어 - 한 가지 기능 -> 2개 이상 결과 생성 - 부모 object -> 자식 멤버 호출 ''' #1 . 메서도 재정의 class Parent : data = None def superFunc(self): pass class Sub1(Parent): def superFunc(self,data): # method override ...
553103464c9b8a79a375b2e3e5543c757a72a022
Kimuksung/bigdata
/python/selector.py
890
3.5625
4
''' 선택자(selector) - 웹 문서 디자인(css) - 선택자 : id(#) - 중복 불가 / class(.) - 중복 가능 - html.select('선택자') : 여러 개의 element 수집 - html.select_one('선택자') : 한 개 element 수집 ''' from bs4 import BeautifulSoup file = open("../data/html03.html" , encoding="utf-8") src = file.read() #print(src) html = BeautifulSoup(src , 'html.parser')...
09f8f01255f435db3ff85168c5aab810076ef520
Kimuksung/bigdata
/python/sqlite/CRUD.py
2,441
3.78125
4
''' CRUD -create -read -update -delete ''' import sqlite3 try: # database 생성 conn = sqlite3.connect("../data/sqlite.db") # sql문 실행 객체 c = conn.cursor() sql = """create table if not exists goods ( code integer primary key , name text(30) unique not null , su in...