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
6b4e1d7e026e8092f09ecbc6f8984ae4c8ef9807
okipriyadi/NewSamplePython
/SamplePython/samplePython/Process_and_Thread/signal/_03_Alarm.py
735
3.5625
4
""" Alarms are a special sort of signal, where the program asks the OS to notify it after some period of time has elapsed. As the standard module documentation for os points out, this is useful for avoiding blocking indefinitely on an I/O operation or other system call. In this example, the call to sleep() does not la...
5d53da37eaeb7ab546a1a289e5c95c6641debe23
okipriyadi/NewSamplePython
/SamplePython/samplePython/Process_and_Thread/Threading/_03_determining_current_thread.py
824
4.09375
4
""" Using arguments to identify or name the thread is cumbersome and unnecessary. Each Thread instance has a name with a default value that can be changed as the thread is created. Naming threads is useful in server processes made up of multiple service threads handling different operations. """ import threading import...
54601bfc436361968a04d4d8dcc9715e1901a914
okipriyadi/NewSamplePython
/SamplePython/samplePython/Process_and_Thread/signal/_01_a_receiving_signal.py
1,210
3.78125
4
""" As with other forms of event-based programming, signals are received by establishing a callback function, called a signal handler, that is invoked when the signal occurs. The arguments to the signal handler are the signal number and the stack frame from the point in the program that was interrupted by the signal. ...
36f470094e74fdf5bf80792de7a3b24a4b443b54
okipriyadi/NewSamplePython
/SamplePython/samplePython/internet/urllib/_02_ENCODE_argument.py
344
3.5
4
""" Arguments can be passed to the server by encoding them and appending them to the URL. """ import urllib query_args = { 'q':'query string', 'foo':'bar' } encoded_args = urllib.urlencode(query_args) print 'Encoded:', encoded_args url = 'http://localhost:8080/?' + encoded_args print 'url =',url print 'urlopen = ', ur...
28d62ead494a5f35e18d87e05fb6b7b9f47d57ea
okipriyadi/NewSamplePython
/SamplePython/Framework/Django/_06_apllication_extending.py
7,081
3.796875
4
""" Extend your application We've already completed all the different steps necessary for the creation of our website: we know how to write a model, url, view and template. We also know how to make our website pretty. Time to practice! The first thing we need in our blog is, obviously, a page to display one post, ...
8d0e4e75cfb540e40ea4b72134aa35ae51743daa
okipriyadi/NewSamplePython
/SamplePython/dari_buku_network_programming/Bab1_socket_and_simple_server_client.py/_13_echo_server.py
1,508
4.0625
4
""" First, we create the server. We start by creating a TCP socket object. Then, we set the reuse address so that we can run the server as many times as we need. We bind the socket to the given port on our local machine. In the listening stage, we make sure we listen to multiple clients in a queue using the backlog arg...
757f1fe7ac984a14ad45198c98c5413485a390e2
okipriyadi/NewSamplePython
/SamplePython/samplePython/Assignment5PM/Sudah Beres/bukuTeleponDatabase/engine/model/PhonebookModel.py
1,956
3.78125
4
import sqlite3 class PhonebookModel: def __init__(self): self.con = sqlite3.connect('files/test.db') self.cur = self.con.cursor() def createTable(self): self.cur.execute('''CREATE TABLE person (id_person INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT , address TEXT)...
36360988ad89205311f6f8ff806f345bbf5bf5ba
okipriyadi/NewSamplePython
/SamplePython/dari_buku_network_programming/Bab1_socket_and_simple_server_client.py/_06_socket_timeout.py
809
3.828125
4
""" Sometimes, you need to manipulate the default values of certain properties of a socket library, for example, the socket timeout. You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very usef...
f08bd170328ec6dc4ca3c8da2f3d8e2af7af5891
okipriyadi/NewSamplePython
/SamplePython/build_in_modul/_01_zip.py
358
4.125
4
""" built-in zip berfungsi untuk iterasi yang menghasilkan satu-ke satu. return nya berupa tuple. contoh zip([1, 2, 3, 4], ['a', 'b', 'c', 'f']) menghasikan """ a = zip([1, 2, 3, 4], ['a', 'b', 'c', 'f']) for i in a : print i print "a = " , a b = zip([1, 2], ['a', 'b', 'c', 'f']) print "b =",b c = zip([1, 2, ...
d34b149c0cb8bf87bd81b880f35f507d3b20fbd4
okipriyadi/NewSamplePython
/SamplePython/samplePython/internet/CGI/01_test_web_server_works_or_not_with_CGI.py
2,560
3.53125
4
""" The Python standard library includes some modules that are helpful for creating plain CGI programs: 1. cgi : Handling of user input in CGI scripts 2. cgitb : Displays nice tracebacks when errors happen in CGI applications, instead of presenting a "500 Internal Server Error" message The Python wiki f...
a3330d6f9075ac7c7524bcb8d859092454967559
okipriyadi/NewSamplePython
/SamplePython/Basic Source /Dasar/struct/01_awal_pack_and_unpack.py
1,173
3.890625
4
""" The struct module includes functions for converting between strings of bytes and native Python data types such as numbers and strings. Structs support packing data into strings, and unpacking data from strings using format specifiers made up of characters representing the type of the data and optional count and ...
583f24e601964798dc24de7ae7bc1845d991f6e1
kishen19/HSS-Course-Allotment
/generate_codes/code_generation.py
1,720
3.875
4
''' Generating Unique Codes for students. These codes are used for authentication when collecting student preferences. Codes are sent to students by email. Students are required to enter this unique code when submitting the form. Each unique code contains 8 characters, alphanumeric. 'Case Sensitive'. ''' from random i...
a6ac166cbc0c8ee75d09c906e4376c05f5a40169
jeffsmohan/words
/scripts/wordcounts_clean.py
1,361
4.03125
4
"""Tool to clean wordcounts files by removing the count.""" import argparse def clean_word_counts(args): """Remove count from wordcounts file.""" with open(args.valid_words) as f: valid_words = set(word.strip() for word in f) with open(args.word_counts) as i, open(args.output, "w") as o: ...
cbe557cecd80fbd899d131c5fdd126550afaf88a
paulwuertz/CodeEval
/Easy/AgeDistribution.py
830
3.796875
4
import math import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: if(int(test)<0): print("This program is for humans") elif(int(test)<3 and int(test)>-1): print("Still in Mama's arms") elif(int(test)<5 and int(test)>2): print("Preschool Maniac") elif(int(test)<1...
57864bba5ca80ebbc1d1035b28a22a9b56cec39a
paulwuertz/CodeEval
/Easy/SumOfPrimes.py
271
3.546875
4
import math def isPrim(zahl): for i in range(3,(int)(zahl/2),2): if(zahl%i==0): return 0 return 1 primAnz=1 primSum=2 zahl=3 while primAnz<1000: if(isPrim(zahl)==1): primAnz+=1 primSum+=zahl zahl+=2 print(primSum)
1edcf09a11ad03b85559e095fe1dcae4dfce6d3c
akshayjain3450/HackerRank30DaysChallenge
/loopreview.py
302
3.5625
4
T = int(input()) if T < 1 and T > 10: exit() else: for i in range(T): S = input() odd = '' even = '' for j in range(len(S)): if j % 2 == 0: odd = odd + S[j] else: even = even + S[j] print(odd,even)
78b23e0df36a221a1bf75c1947cabca32551a428
rnlclngpilar/CBIRusingBarcode
/Feb28_GoogleDrive_Update/RBC_all.py
1,638
3.625
4
from mnist import MNIST mndata = MNIST('.') images, label = mndata.load_training() # images, labels = mndata.load_testing() print("Read all Images") # index = random.randrange(0,len(images)) # choose a random index #https://stackoverflow.com/questions/11926620/declaring-a-python-function-with-an-arra...
7cce2411a94de777d3a73993399cb9fadb574369
anmolparida/selenium_python
/CorePython/DataTypes/Numbers/BitwiseOperators.py
304
3.578125
4
""" Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name. For example, 2 is 10 in binary and 7 is 111. """ x = 10 # 0000 1010 y = 4 # 0000 0100 print(x & y) # 0000 0010 - 0 print(x | y) # 0000 1010 - 14 print(-x) # 1111 0101 -
cf4bf216fd03c9acaff05038fe3f204902ddd216
anmolparida/selenium_python
/CorePython/FlowControl/Pattern_Stars.py
758
4.125
4
""" Write a Python program to construct the following pattern, using a nested for loop. * * * * * * * * * * * * * * * * * * * * * * * * * """ def pattern_star_right_arrow_method1(n): print('pattern_star_right_arrow_method1') for i in range(n + 1): print("* " * i) for j in ran...
5512e04c4832ad7b74e6a0ae7d3151643747dd8c
anmolparida/selenium_python
/CorePython/DataTypes/Dictionary/DictionaryMethods.py
1,181
4.28125
4
d = {'A': 1, 'B' : 2} print(d) print(d.items()) print(d.keys()) print(d.values()) print(d.get('A')) print(d['A']) # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} print(my_dict) # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} print(my_dict) # us...
39d0acbcb42f0e6e26264e867d4bbdea341be8a4
anmolparida/selenium_python
/CorePython/DataTypes/List/Set.py
3,256
4.65625
5
""" Strings are immutable. Forzensets are immutable version of the set This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name. """ my_string = 'programiz' # my_string[5] = 'a' # TypeError: 'str' object does not support item ass...
0ac431eb794358e899b968ff554df3060e54075d
anmolparida/selenium_python
/CorePython/FlowControl/DataTypes.py
555
4.09375
4
singleLine = "Single line string" multiLine = """ Multi line string""" print(singleLine) print(multiLine) print(float(5)) print(int(5.0)) print(float(0)) print(int(0.0)) print(float(-5)) print(int(-5.0)) print("#"*50) print(1, 2, 3, 4) print(1, 2, 3, 4, sep='*') print(1, 2, 3, 4, sep='#', end='\n') # pr...
8b97530008656847d3e8218d6e7d292aed34ede1
anmolparida/selenium_python
/CorePython/DataTypes/Numbers/Decimal.py
731
3.859375
4
""" Adding float in python PROBLEM It turns out that the decimal fraction 0.1 will result in long binary fraction 0.1000000000000000055511151231257827021181583404541015625 and our computer only stores a finite number of it. ******* When to use Decimal instead of float? ******* # When we are making financial applicat...
6e5ea5a76c0af38d4fefd42eaff48f9d13512ec1
anmolparida/selenium_python
/Tutorials/Udemy/FindElement_Xpath_CSS.py.py
3,096
3.578125
4
# driver.find_element_by_id() # driver.find_element_by_name() # driver.find_element_by_xpath() # driver.find_element_by_link_text() # driver.find_element_by_partial_link_text() # driver.find_element_by_tag_name() # driver.find_element_by_class_name() # driver.find_element_by_css_selector() # drive.find_elemen...
6a655da9e2fefbfaa7a77ce652b6af6755ae1e95
surenthiran123/sp.py
/number.py
330
4.21875
4
n1=input(); n2=input(); n3=input(); Largest = n1 if Largest < n2: if n2 > n3: print(n2,"is Largest") else: print(n3,"is Largest") elif Largest < n3: if n3 > n2: print(n3,"is Largest") else: print(n2,"is Largest") else: print(n1,"is ...
e29e3741598e0c459a2bd22292f9349f7cfe4fb4
jonbinney/python-planning
/python_task_planning/src/python_task_planning/common.py
7,885
3.609375
4
class Symbol: def __init__(self, val=None): self.val = val def __hash__(self): return hash(id(self)) def __eq__(self, other): return (self is other) def __repr__(self): return 'symbol%d' % id(self) class Variable: def __init__(self, name): self.name = name...
6473a46ccb7d1e761875c1e0bad2e231228a2d2a
amulyaparam/girlswhocoderepo
/gloop.py
89
3.84375
4
g_list = ["bread", "cheese", "milk", "juice"] for g_list in range(3): print(g_list)
5d728361f053726e324ee0e39d6e7743f50ef9f3
auvy/big_data_2021
/lab4/main.py
1,973
3.765625
4
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import os #PART1 #step1 #step2 salesDist = pd.read_csv('./stores-dist.csv') # print(salesDist.head()) salesDist = salesDist.rename(columns={'annual net sales':'sales','number of stores in district':'stores'}) ...
cbf7a121424cb1217533d40d5c0a492197035194
HuuHoangNguyen/Python_learning
/Modules.py
5,574
4.25
4
#!/usr/bin/python """ A module allows you to logically organize yout Pyhon code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes thay you can bind and reference. Simply, a module is a file consisting of Python code. A modul...
243fa09f33b873b827c1a69345df1da1f850bdf4
HuuHoangNguyen/Python_learning
/membership_operators.py
458
4.03125
4
#!/usr/bin/python a = 10 b = 20 list = [1, 2, 3, 4,5] if a in list: print "Line 1: a is available in the given list" else: print "Line 1: a is not available in the given list" if b not in list: print "Line 2: b is not availabale in the given list" else: print "Line 2: b is available in the given list"...
057e4637e754f4dbb0bd6e71078e730864603eef
ChengYuHua/PI-God-and-their-100-project
/計分系統.py
12,926
3.5
4
# import csv # # filename = "______.csv " # with open filename as f # reader csv reader f # header_row=next(reader) # print(header_row) class Restaurant: service = [0, 0, 0] food = [0, 0, 0] cp = [0, 0, 0] environment = [0, 0, 0] reachable = [0, 0, 0] speed = [0, 0, 0] total = ...
ab44b0bc2c1dda3e9f6af2267146e0357005fa13
Guo-Alex/genetic-steganography-algorithm
/RankSelection.py
1,836
3.890625
4
import random as random import hashlib class RankSelection: def __init__(self,population): self.population = population self.rankedList = list() def setup(self,population,SP): print "Preparing for RankSelection\nSoring List...", self.rankedList = sorted(population, key=lambda x: x.fitness, reverse=True) f...
946d183421857c5896636eac5dcaa797091cb87a
aboyington/cs50x2021
/week6/pset6/mario/more/mario.py
480
4.15625
4
from cs50 import get_int def get_height(min=1, max=8): """Prompt user for height value.""" while True: height = get_int("Height: ") if height >= min and height <= max: return height def print_pyramid(n): """Print n height of half-pyramid to console.""" for i in range(1, n...
0db86d8ae6589de68b76677ad7ea6d8149332e71
kmangutov/cs467Sankey
/csv_parser.py
2,707
3.5625
4
import csv f = open("data.csv", "r") data = csv.reader(f) schema = [] for row in data: schema = row + [] break print schema univ = set() univ_bs = set() univ_ms = set() univ_phd = set() univ_idx = schema.index('University') univ_bs_idx = schema.index('Bachelors') #univ_ms_idx = schema.index('Masters') univ...
138db170991e2efbeabe8efac9210b5885fd49c7
edwight-delgado/python-profesional
/codes/palindrome.py
409
3.953125
4
def is_palindrome(string:str)->bool: """Returns if the string is palindrome (True or False)""" string= string.replace(" ","").lower() return string == string[::-1] def suma(a:int,b:int)->int: return a+b def main(): print(suma('2','3')) #lista =[ (value ,is_palindrome(value)) for value in ['Ana','Maria','oro','a...
ff977846f338448778072c134dbf1ff0e0cfa998
drexpp/Personal-projects
/Codefights/Interview questions/Dynamic programming/cimbingStairs.py
124
3.53125
4
def climbingStairs(n): a = [0, 1, 2] for i in range(3,n+1): a.append(a[i - 1] + a[i - 2]) return a[n]
2b233d93ef2101f8833bbff948682add348fde63
djanibekov/algorithms_py
/inversion_counting.py
2,025
4.21875
4
inversion_count = 0 def inversion_counter_conquer(first, second): """[This function counts #inversions while merging two lists/arrays ] Args: first ([list]): [left unsorted half] second ([list]): [right unsorted half] Returns: [tuple]: [(first: merged list of left and right halves...
609b60ed9ad43ca1b3053d86daf92bf440fcd65a
LeongWaiLimn/Coursera-test
/Python_stuff/Assignment/9/assignment_9.4.py
647
3.703125
4
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) email_data = dict() for readfile in handle: if not readfile.startswith ("From "): continue email_list = readfile.split() email_only = email_list[1] #print("Email list:",email_only) email_data[email_...
59b8795ae291f06a1b9f56a4e9e0eac3e15d3a34
SyaoranR/ADS_Pycharm
/Idade COMPLETO.py
4,847
3.875
4
# idade, nasc, ano, niver_mes, mes, niver_dia, dia, # i, j, dias, d, idade_dias, resto_ano, meses, days # bis: logico print("Idade, COMPLETO") # s em anos idade = int(input("Informe a idade do indivduo: ")) # verificao nasc = int(input("Informe o ano de nascimento: ")) atual = int(input("Informe o ano atual: ")) nive...
ca2c9198e41e1fa53fb33eedca15a40e47e68d51
pjc0618/ImageModifier
/imager/a6test.py
12,909
3.8125
4
""" Test cases for Tasks 1 and 2 You cannot even start to process images until the base classes are done. These classes provide you with some test cases to get you started. Author: Walker M. White (wmw2) Date: October 20, 2017 """ import cornell import pixels def test_assert(func,args,message): """ Tests ...
d872888d0820e600a2324ff64beb376384011c28
ShuklaG1608/Python-for-Everybody-Specialization---Coursera
/2. Python Data Structures/Week 6/Py4EDataStructureWeek6Ex1.py
849
3.9375
4
'''Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Once...
a2676ba8f5951f65248b4503b8df8e989c2422e9
nurulsucisawaliah/python-project-chapter-6
/latihan 2[praktikum 4]/latihan 2[ starFormation ].py
1,166
3.515625
4
#starFormation1 def starFormation1(n): Kolom=0 Baris=n i=0 while(i<=n): j=0 while(j<Kolom): print('*',end='') j+=1 print('') i+=1 Kolom+=1 #contohsF1 starFormation1(4) print() #starFormation2 def starFormation2(n): ...
c415d93b04059c595aea33f054d032c075cfa83c
pran-p/port-mapper
/script.py
3,211
4.21875
4
"""This is a simple port scanner built using the concept of sockets in python""" import socket import sys import argparse import pyfiglet import os """This function is used to scan a given ip for a given open port""" def portScanSingle(port,ip): s=socket.socket() try: print ("[+] 4tt3mpting t0 c0nn3ct ...
bf67625fe7b4925716e91c5dea79a23c91aeb248
bomjic/StudyPython
/Problem016/Power_digit_sum.py
244
3.671875
4
def power_digit_sum(base, exponent): result = 1 exp_res = str(base ** exponent) print exp_res for i in exp_res: result += int(i) return result if __name__ == "__main__": print power_digit_sum(2, 1000)
1188524f18c0098b94fecfe5a38f4556886adfd0
ForritunarkeppniFramhaldsskolanna/epsilon
/example_contests/fk_2014_beta/problems/tonlist/submissions/accepted/solution.py
308
3.671875
4
pat = raw_input() n = int(raw_input()) for _ in range(n): s = raw_input() if '*' in pat: a, b = pat.split('*') ok = len(a+b) <= len(s) and s.startswith(a) and s.endswith(b) else: ok = s == pat if ok: print('Passar') else: print('Passar ekki')
4f246a420a74ea3db6aa8541995ff046a99719ca
ForritunarkeppniFramhaldsskolanna/epsilon
/example_contests/fk_2014_beta/problems/bencoding/data/secret/check.py
5,270
3.5
4
import sys # def parse(s): # at = 0 # def next(): # if at == len(s): # return None # if s[at] == 'i': # at += 1 # no = 0 # while at < len(s) and ord('0') <= ord(s[at]) <= ord('9'): # no = no * 10 + (ord(s[at]) - ord('0')) # ...
fa06ca0e9bd83aefd2ec1fce4b35b5e89b387c2b
sonu-python/Web-Scrabing-Using-scrapy
/webscrabing.py
3,532
3.78125
4
import urllib3 from bs4 import BeautifulSoup # Create instance of urllib to get the data form browser http = urllib3.PoolManager() # Get the data using urls request_data = http.request('GET', 'https://in.hotels.com/search.do?resolved-location=CITY%3A1506246%3AUNKNOWN%3AUNKNOWN&destination-id=1506246&q-destination=New...
607cbe367b21dc77e4fcc52ba2311a5954afe50f
NCR7777/PythonLearning
/practice/practiceWeek2.py
1,156
3.625
4
# # 练习1 # from turtle import * # # penup() # forward(-250) # pendown() # setheading(-40) # width(25) # pencolor("pink") # for i in range(4): # circle(40, 80) # circle(-40, 80) # circle(40, 80 / 2) # forward(50) # circle(16, 180) # forward(40) # done() # # 练习2 # from turtle import * # pensize(25) # for i in ran...
34285608be053d54a240f38590098d6b4196e8b4
Carlos123b/X-Serv-Python-Multiplica
/mult.py
222
3.96875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- for i in range(1,11): print("Tabla del " + str(i) + ":") print("---------------------------") for j in range(1,11): print(i,"por",j,"es",i*j) print("\n")
0d74013d13a6d16001e6cdae2986a24644ddb023
ezvone/advent_of_code_2019
/python/src/solve12.py
3,077
3.5625
4
import itertools from math import gcd from input_reader import read_moons class Moon1D: def __init__(self, x, v=0): self.x = x self.v = v def __repr__(self): return f'<Moon1D {self.x} -> {self.v}>' def __eq__(self, other): return (self.x == other.x and self.v == other.v)...
2ded271d6edb4ab7060cc67d17fceb9aef8c0a19
Kaustav-G23/Python_prog
/descending_list.py
153
3.875
4
lst = [] n = int(input("Enter the number of inputs: ")) for i in range(0, n): ele = input() lst.append(ele) lst.sort(reverse = True) print(lst)
343638e772118f92de1d7442e4f439b52fbc19ae
justindodson/PythonProjects
/CPR_Temps/resources/card_template.py
3,410
3.53125
4
import docx from docx.shared import Pt # class to create the Word templates class Template: # constructor takes a student object and file name as aruments. def __init__(self, user, file_name): self.user = user self.file_name = file_name self.document = docx.Document('../files/template....
3b2ef800db7e55959d07634bcfbbb5d3823d88bb
BezK97/alx-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
329
3.625
4
#!/usr/bin/python3 def uniq_add(my_list=[]): sum_unique = my_list[0] n = 0 for i in range(1, len(my_list)): for j in range(i): if my_list[i] == my_list[j]: n = 0 break else: n = my_list[i] sum_unique += n return (sum...
412b8d4c072a90cca2e41d61100ce2d507d79de3
kyokley/ProjEuler
/projEuler35.py
1,830
3.53125
4
#!/usr/bin/python import projEulerFuncs savedPrimes = projEulerFuncs.savedPrimes isPrime = projEulerFuncs.isPrime permuteRec = projEulerFuncs.permuteRec def convertToList(num): strNum = str(num) lst = [int(x) for x in strNum] return lst def convertFromList(lst): tempStr = "" for i in lst: tempStr += str(i) ...
8011dbdefa7ee07880fcb1ae94e6f00becd95e6f
kyokley/ProjEuler
/projEuler29.py
725
3.765625
4
#!/usr/bin/python2.7 import math from projEulerFuncs import print_timing def main(): res1 = listPowers() res2 = setPowers() print res1, res2 @print_timing def listPowers(): upperBound = 101 lowerBound = 2 results = [] for i in range(lowerBound, upperBound): for j in range(lowerBound, upperBound): ...
d9c96086c62ec3cf38f630057c63120699c50b82
kyokley/ProjEuler
/projEuler41.py
444
3.5625
4
#!/usr/bin/python import projEulerFuncs isPrime = projEulerFuncs.isPrime permuteRec = projEulerFuncs.permuteRec reverseDigitize = projEulerFuncs.reverseDigitize def main(): results = [] for i in xrange(8, 2, -1): lst = permuteRec(range(1, i)) lst = [reverseDigitize(x) for x in lst] for j in lst: if isPr...
a5807fbb80791e78d47a6f7656f9e492414541cb
kyokley/ProjEuler
/projEuler45.py
677
3.953125
4
#!/usr/bin/python def triangle(): n = 1 while 1: yield (n * (n + 1)) / 2 n += 1 def pentagonal(): n = 1 while 1: yield (n * (3*n - 1)) / 2 n += 1 def hexagonal(): n = 1 while 1: yield n * (2*n -1) n += 1 def main(): gen1 = hexagonal() gen2 = pentagonal() gen3 = triangle() for i in xrange(...
9abd265657ff11174be5a9f761359716b8fbee32
FelipeDasr/Python
/FundamentosPython/Interpolação.py
301
3.65625
4
from string import Template nome, idade = "Ana", 30 print("Nome: %s Idade: %d %r %r" % (nome, idade, True, False)) print("Nome: {} Idade: {}".format(nome, idade)) print(f'Nome: {nome} Idade: {idade}') s = Template('Nome: $nome Idade: $idade') print(s.substitute(nome =nome, idade = idade))
4c75bfd29fdbb14b06271e3916ac6d2c43f81b83
FelipeDasr/Python
/EstruturasDeControle/For04.py
102
3.59375
4
#!python for i in range(1, 11): if i == 6: break print(i) else: print("Fim")
916af4c0e1759dfe3cc68c5e2a37cfbfdbf66352
FelipeDasr/Python
/EstruturasDeControle/SimulandoOSwitch.py
576
3.953125
4
#!python def getDiaSemana(dia): dias = { 1: "Domingo", 2: "Segunda", 3: "Terca", 4: "Quarta", 5: "Quinta", 6: "Sexta", 7: "Sabado" } return dias.get(dia, "Dia Invalido") def getTipoDia(dia): if dia == 1 or dia == 7: return "...
5515124d6212b93ea990f6fa86662590cc5e6c71
FelipeDasr/Python
/POO/Construtor.py
310
3.53125
4
#!python class Data: def __init__(self, dia = 1, mes = 1, ano = 1970): self.dia = dia self.mes = mes self.ano = ano def __str__(self): return f"{self.dia}/{self.mes}/{self.ano}" if __name__ == "__main__": d1 = Data(ano = 2020) print(d1)
0df18f9f12d36d7db0025c31f648f644bb8b3e26
JamesAsuraA93/CMU_Python
/assignment#3/third.py
704
3.6875
4
def prime(x): m = x // 2 for i in range(2, m + 1): if x % i == 0: return False return True def compo(x): lst = [] keep = x start = 2 while x != 1: if x % start != 0: start += 1 if start % 2 == 0 and start != 2: start += 1 ...
d5a49a42495246cfaa3c6870476d66b271a0e188
ElineSophie/Smart_grid_alt
/cable.py
556
3.59375
4
from house import House from battery import Battery class Cable(object): def __init__(self, house, battery): self.house = house self.battery = battery self.route = route def distance(self): """ Calculates a route between battery and house according to the manha...
6eef9efebad6e30050ee372b6e4f3b3fbcc0ef79
ElineSophie/Smart_grid_alt
/code/classes/battery.py
443
3.6875
4
class Battery(object): def __init__(self, id, x_pos, y_pos, capacity): """ Initializes an Item """ self.id = id self.x_battery = int(x_pos) self.y_battery = int(y_pos) self.capacity = float(capacity) self.capacity_available = 0 def __str__(self):...
a5b02e9dce6abc5b3ff30a257bdab3caf371186d
KamalNaidu/Competitive_Programming
/Week-1/Day-2/Making_Change.py
646
4
4
#5 Making Change def change_possibilities(amount, denominations): """ Computes the number of ways to make amount of money with coins of the available denominations. Dynamic space efficient programming solution """ if (len(denominations) == 0) or (amount < 0): return 0 results...
e40ea40cf7b6a96c8da57942ec7ec0d5029916f2
foresthz/numpy_basics
/src/basic/np_genarray.py
859
3.59375
4
''' Created on 2017-06-11 @author: btws ''' import numpy as np a = np.array([1,2]) print a.shape b = np.array([ [1,2], [3,4] ]) print b.shape c = np.array([[[1,2],[3,4]], [[5,6],[7,8]]]) print c.shape d = np.zeros([3,3]) print d # the type is object e = np.array([[1,2],[3,4],[5,6,7]]) print...
63ca4f68c05708f2482045d06775fa5d7d22ea55
loudan-arc/schafertuts
/conds.py
1,574
4.1875
4
#unlike with other programming languages that require parentheses () #python does not need it for if-else statements, but it works with it fake = False empty = None stmt = 0 f = 69 k = 420 hz = [60, 75, 90, 120, 144, 240, 360] if k > f: print(f"no parentheses if condition: {k} > {f}") if (k > f): ...
4afceabb3673acbe934061dd9888d06e0457a152
dark5eid83/algos
/Easy/palindrome_check.py
330
4.25
4
# Write a function that takes in a non-empty string that returns a boolean representing # whether or not the string is a palindrome. # Sample input: "abcdcba" # Sample output: True def isPalindrome(string, i=0): j = len(string) - 1 - i return True if i >= j else string[i] == string[j] and isPalindrome(stri...
a2e7a66a04141aaa578c4dc025bfc70d11b95e8f
xstonekingx/project_euler
/projectEuler21.py
355
3.5
4
def d(a): divisor_sum = 0 for i in range(1, a): if a%i == 0: divisor_sum += i return divisor_sum total_sum = 0 #send numbers 1-10000 into d #if it returns add it to total_sum for a in range(1, 10001): b = d(a) if d(b) == a and a!=b: total_sum = tot...
7c8c84d00d944b074c6627731c10762658d581d5
farshadnp/Data-Mining-Exercises-Code
/Ex1/03.py
506
3.671875
4
import keyboard while True: print("_____________________________Tamrin #3 _________________________________\n\n") MySentence = input("Please enter a long sentence : ") MySentence_Splited = MySentence.split(" ") print("\nBe soorat List kalamate jomle vared shode : ",MySentence_Splited) pr...
7d0101020d591a15c25bae422b9c7702cc6fdd60
AdamMartinCote/IntroductionToAI
/tp1/src/state.py
3,420
3.53125
4
from typing import List import numpy as np from tp1.src.car import Car class State: def __init__(self, pos, c=None, d=None, previous_state=None): """ Contructeur d'un état initial pos donne la position de la voiture i (première case occupée par la voiture); """ self.pos ...
a767f1479e709878cdfdd0705f3e1ddb0e5d7bfc
xjy611/grokking_algorithms
/chapter1/binary_search.py
734
4.03125
4
# _*_ coding : UTF-8 _*_ # 开发人员 : 16092 # 开发时间 : 2020/7/8 13:58 # 文件名称 : binary_search.PY # 开发工具 : PyCharm def binary_search(list, item): """ 二分查找法 Args: list: 需要查找的列表 item:需要查找的元素 Returns: mid:元素索引 None:查找不到返回空 """ low = 0 high = len(list) - 1 while l...
6849ca836d10f111664ba453e7798bc36dc40128
Ursulinocosta/circunferencia
/11/circunferencia.py
196
3.859375
4
raio = float(input('Entre com o valor do raio para obter a circunferencia do circulo: ')) circunferencia = 2 * 3.14 * raio print("A circunferencia do circulo: {:.2f}".format(circunferencia))
529002f634849ccd180872ea5dc4e514bcd2fd0a
Prateek1992/Coding_Projects
/sequenceOperators.py
375
4.09375
4
string1 = "he is " string2 = "probably " string3 = "pining " string4 = "for the " string5 = "fjords" print(string1 + string2 + string3 + string4 + string5) # string concatenation print("he is " "probably " "pining " "for the " "fjords") print("Hello \n"*(2*2)) # strings can be multiplied in python today = "monday" pr...
691d59f03de0cb41fab482f3f7387a5d8cbb1b00
alexander-mc/Other_Projects
/01_Python_Projects/01_Hangman_Game/hangman.py
2,709
3.953125
4
# Python 2.17.13 # Project name: Hangman! # Project details: Guess the word in 8 tries # Course: MITx 6.001x # ----------------------------------- # Helper code import random import string WORDLIST_FILENAME = "/Users/Alexander/Documents/Coding/0_GitHub_Portfolio/Other_Projects/01_Python_Projects/01_Hangma...
b38851862e7c1546740708b72ca0b4dcf51efe0c
alexander-mc/Other_Projects
/04_MIT_6.001x_Course/Lessons/L6P10.py
432
3.625
4
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') a = {'l': []} b = {} def biggest(aDict): count = 0 key = "" if aDict == {}: return None for k in aDict: if len(aDi...
280aa4ae96a202fe41ca16459456f9527ee9b4ff
alexander-mc/Other_Projects
/04_MIT_6.001x_Course/Problem_Sets/Problem_Set_2/PS2Q1.py
578
3.875
4
balance = 4213 annualInterestRate = .2 monthlyPaymentRate = .04 monthlyInterestRate = annualInterestRate/12 totalPaid = 0 for m in range(1,13): print 'Month:',m print 'Minimum monthly payment:', float("{0:.2f}".format(balance*monthlyPaymentRate)) totalPaid += balance*monthlyPaymentRate bala...
19d96e01d939f855d225f07dd20d5df3a2d21993
rickychau2780/practicePython
/exercise9.py
417
4.03125
4
import random num = random.randint(1,9) count = 0 while True: guess = input("What is your guess? (0-9): ") if guess == "exit": break guess = int(guess) count += 1 if guess > num: print("it is too high!") elif guess < num: print("it is too low!") else: ...
3b58e7105a1d46c41da745ee2f52a25d8dfcce88
ngophuongthuy/NgoPhuongThuybaitap
/Matplotlib4.py
302
3.734375
4
import matplotlib.pyplot as plt import numpy as np divisions = ["Python","PHP","CSS","JAVA","C++"] divisions_average_marks = [92,76,9,67,51] plt.bar(divisions, divisions_average_marks,color='pink') plt.title("Bar Graph") plt.xlabel("ngôn ngữ lập trình") plt.ylabel("tỷ lệ") plt.show()
a5783a5103f9f7873bf1e412b65b0666cf532fcb
nestorcolt/smartninja
/curso_python/clase_006/player_manager.py
528
3.734375
4
""" This module holds the abstract class for player data model All players will inhered from this class """ class Player: def __init__(self, first_name, last_name, height_cm, weight_kg): self.first_name = first_name self.last_name = last_name self.height_cm = height_cm self.weight...
de6efec5a642dc7843543d771395385f0ad85c33
doudouhhh/Stanford_dogs-classification-by-CNN
/Rename.py
596
3.734375
4
# coding:utf-8 import os import sys def rename(): path=input("请输入路径:") name=input("请输入开头名:") startNumber='1' fileType='.jpg' print("正在生成以"+name+startNumber+fileType+"迭代的文件名") count=0 filelist=os.listdir(path) for files in filelist: Olddir=os.path.join(path,files) if os.pa...
9adde924d98de1abadf6249fbb952124f337114b
naranundra/python3
/dasgal3.py
324
3.78125
4
# хүний нэр өгөгдсөн бол 2 оос дээш а үсэг орсон эсэхийг шалга ner = input("нэр ээ оруулна уу:") c = ner.count("a") print(c) ner = input("нэр ээ оруулна уу:") c = ner.count("a") if c>2: print("2-оос олон а үсэг орсон")
70547602bad5568d71dd4a664cc5324af9e5b55c
gvimpy/Abhinav
/direction = input ("choose operation mul.py
1,356
3.96875
4
direction = input ("choose operation mult add sub div:") if direction == "add": ans = input ("Number One:") rad = input ("Number Two:") result = int(ans) + int(rad) print (result) if direction == "mult": an = input ("Number One:") ra = input ("Number Two:") ww = int(an) * int(ra) print (...
7ce3fe03de726250fbad7573e0f6a12afa5fcc4a
AshishKadam2666/Daisy
/swap.py
219
4.125
4
# Taking user inputs: x = 20 y = 10 # creating a temporary variable to swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y))
7186b81599cf00acbf1f1dd1436fc21d467abfa2
kunigami/blog-examples
/huffman/simple_queue_test.py
1,130
3.8125
4
import unittest from simple_queue import Queue class QueueTest(unittest.TestCase): def test_operations(self): q = Queue() self.assertTrue(q.is_empty()) self.assertEqual(q.front(), None) self.assertEqual(q.pop(), None) q.push(1) self.assertFalse(q.is_empty()) ...
98ca8affd941f3bafcd9e2b9ae8fa35dfdf89166
hchang18/nonparametric-methods
/exchangeability_test.py
2,105
3.5
4
# exchangeability_test.py import numpy as np def exchangeability_test(x, y, size): """ Calculate the variance test. This test tests the null hypothesis that two distributions on X and Y have same variance. This time, the assumptions on medians are relaxed, but it requires the existence of the 4th ...
ef3a0ab8ca46680697e312f31094b9ce455a37bb
Choe-Yun/Algorithm
/LeetCode/문자열 다루기/02.Reverse_String.py
746
4.15625
4
### 문제 # Write a function that reverses a string. The input string is given as an array of characters s. # 문자열을 뒤집는 함수를 작성해라. 인풋값은 배열이다 ### Example 1 # Input: s = ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] ###### code from typing import List # 투 포인터를 이용한 스왑 방식 class Solution: def reverseString(...
539f504f6b4ec2b2e07d8900fc7290d0c7ee3f39
seangrant82/AI
/graphs/streamlit/streamlit_newNode_txtInput.py
1,187
3.59375
4
import streamlit as st from neo4j import GraphDatabase from py2neo import graph # Add your Neo4j database credentials here uri = "bolt://localhost:7687" user = "neo4j" password = "password" # Create a driver instance to connect to the Neo4j database driver = GraphDatabase.driver(uri, auth=(user, password)) ...
00911f42a052a0a3a3b3f2ace57d324657fd8758
valekovski/ssts
/python/vaje_resitve3.py
1,689
3.625
4
# 1. Fibonaccijevo zaporedje st_clenov = 20 # št. členov zaporedja, ki jih bomo generirali predzadnji_clen = 1 # inicializiramo začetna dva člena zadnji_clen = 1 print(predzadnji_clen, " ", end="") print(zadnji_clen, " ", end="") # odštejemo 2, ker smo prva dva člena že izpisali for i in range(st_cl...
c2329fb310cf7ab43c20f56ccb00b0bdf6bb3ae4
CullenMar/205proj1section2
/project_1.py
1,244
3.625
4
# this is a comment, yo -> https://github.com/CullenMar/205proj1section2 from PIL import Image def median( inputList ): #gets median value from an array a = 0 while a < 8: if (inputList[a] > inputList[a + 1]): b = inputList[a] inputList[a] = inputList[a + 1] inputList...
ac298bd148566e21a3868973a35dab63d7ea8b47
dgolov/autoru_parser
/utils.py
1,200
3.640625
4
from parser import ParserSlugs def convert_entered_data_to_int(message_to_input): """ Конвертирует вводимое число в integer В случае ошибки обрабатывает исключение и возвращает 0 :param message_to_input: - число в текстовом формате :return: - Integer """ try: response = int(input(m...
bb155d4d67a7611506849ea6160074b6fec2d01f
kalpitthakkar/daily-coding
/problems/Jane_Street/P5_consCarCdr.py
1,420
4.125
4
def cons(a, b): def pair(f): return f(a, b) return pair class Problem5(object): def __init__(self, name): self.name = name # The whole idea of this problem is functional programming. # Use the function cons(a, b) to understand the functional # interface requir...
55bbfa30507bc3fb63ab5385aa33f80b827e0395
kalpitthakkar/daily-coding
/problems/Amazon/P12_numberOfSteppingWays.py
927
3.8125
4
class Problem12(object): def __init__(self, name): self.name = name def solver_dp(self, N, steps=[1,2]): dp = [0] * (N + 1) dp[0] = 1 for i in range(1, N+1): val = 0 for j in steps: if (i - j) >= 0: v...
11b8b5e7175b685c7f3718409d22ce34322dbb11
mariagarciau/EntregaPractica3
/ejercicioadivinar.py
1,884
4.125
4
""" En este desafío, probamos su conocimiento sobre el uso de declaraciones condicionales if-else para automatizar los procesos de toma de decisiones. Juguemos un juego para darte una idea de cómo diferentes algoritmos para el mismo problema pueden tener eficiencias muy diferentes. Deberás desarrollar un algoritmo que ...
4069cdb0e12ef67a163ace35f8869c91a1c3dcad
mdcoolcat/CandB
/B/python/matrix_simple.py
1,744
3.734375
4
# simple matrix manipulation # from CareerCup Ch1 import sys import os import commands import re from sets import Set def show(m): for row in m: print row # rotate a N*N matrix by 90 degrees in place def rotate_right_90(m): if len(m) != len(m[0]): raise ValueError('not N*N') show(m) ...
85aa86cdbb15c78367f9eeef853e848dcf517054
mdcoolcat/CandB
/B/python/linked_list.py
4,405
4.0625
4
# Implementation of single linked_list # Danielle Mei import sys import os import commands import re class Node(object): def __init__(self, key): self.key = key self.next = None def __repr__(self): return '%r' % (self.key) def __str__(self): return str(self.key) def...
84f2c41dd849d194eb1bbdbb5abc97ae9f05bfcd
trishajjohnson/python-ds-practice
/fs_1_is_odd_string/is_odd_string.py
974
4.21875
4
def is_odd_string(word): """Is the sum of the character-positions odd? Word is a simple word of uppercase/lowercase letters without punctuation. For each character, find it's "character position" ("a"=1, "b"=2, etc). Return True/False, depending on whether sum of those numbers is odd. For example...
011c454aef55fecb05e327744b8cf001fd90ed5a
smirnoffmg/codeforces
/591A.py
116
3.640625
4
# -*- coding: utf-8 -*- l = int(raw_input()) p = int(raw_input()) q = int(raw_input()) print(p * l / float(p + q))
9f88b91a2834e93146e7dc4c5b0cc1a38dba5553
smirnoffmg/codeforces
/519A.py
416
3.609375
4
# -*- coding: utf-8 -*- res = '' for i in xrange(8): res += raw_input() white_sum = res.count('Q') * 9 + res.count('R') * 5 + res.count('B') * 3 + res.count('N') * 3 + res.count('P') black_sum = res.count('q') * 9 + res.count('r') * 5 + res.count('b') * 3 + res.count('n') * 3 + res.count('p') if white_sum > black...
1991e34b3272b9374e485fb49abe10f2adfb7b3b
smirnoffmg/codeforces
/519B.py
303
4.15625
4
# -*- coding: utf-8 -*- n = int(raw_input()) first_row = map(int, raw_input().split(' ')) second_row = map(int, raw_input().split(' ')) third_row = map(int, raw_input().split(' ')) print [item for item in first_row if item not in second_row] print [item for item in second_row if item not in third_row]