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
44b529ec6d562bd113bab95c0a97077b2cded729
vmeazevedo/CRUD_dados_cadastrais
/crud_dados_cadastrais.py
16,566
3.734375
4
import mysql.connector from mysql.connector import connect, cursor #================================================================================= # CAMPOS DE CONEXÃO COM O BANCO DE DADOS #================================================================================= # PARAMETROS DE CONEXÃO host = "localhost" u...
3f0712e915866d39ce3d68f9b7aea9be60e828c9
rlucioni/cs181
/hw1/dtree.py
16,914
4.28125
4
"""Learn to estimate functions from examples. (Chapters 18-20)""" from utils import * import random, operator #______________________________________________________________________________ class Example: """A class that holds an example. An example is a list of attributes along with a weight. The default is f...
52bb36c951aa8480c2a8d07c5ed777958e261190
rlucioni/cs181
/hw3/utils.py
2,260
3.9375
4
import itertools def argmin(seq, fn): """Return an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to' """ best = seq[0]; best_score = fn(best) for x in seq: x_score = fn(x) if x_score < best_score: best, best_sco...
9e718af3c990aecca1e23a4c9ce7002bec89ba33
GrigoriyPL/10.04.21
/pyataya.py
186
3.640625
4
print ('Программа запущена') ocenki = input() ocenki = ocenki.split() kolvo = 0 vsego = 0 for i in ocenki: kolvo += 1 vsego += int(i) print (vsego/kolvo)
bcca66c0a0b06a0c21218dd3b412cff1d12322e3
GrigoriyPL/10.04.21
/27.02.2021(5).py
317
3.609375
4
high = input() maxn = 0 minn = 10000000000000 while high != 's': print(high) high = int(high) if high < 160 or high > 180: break if high < minn: minn = high print('min', minn) if high > maxn: maxn = high print('max', maxn) high = input()
0990fdca628dfbf2ed54571868342e537afcc797
alagarsamya8870/as
/ala.py
79
3.828125
4
a=raw_input("enter the name:") b=int(input()) for x in range (0,3): print(a)
661d8daf9b95c25b34b7ccc869b39080ec4ac5e9
RJM1996/learngit
/Study/python/py_base/test.py
14,442
3.78125
4
#!/usr/bin/python # coding:utf-8 ''' python 练习 ''' print '\n' ## 类型 #counter = 0 #pi = 3.14 #name = 'rjm' # #print counter #print pi #print name # ## 引用 #a = 10 #b = a #print id(a), id(b), id(10) #b = 20 #print id(b), id(20) # #b = a ## 代码块和缩进 #if a > b: # print "hello" #elif a == b: # print "haha" # pri...
f3f4cad54ae31f6af74c260b5c4df43a9a248c2d
nagapoornima22/voting_app
/ex1.py
1,394
3.9375
4
import sqlite3 conn = sqlite3.connect('my_database.sqlite') cursor = conn.cursor() print('hi, are you looking for vote') response = input("enter Y or N ") if response=='N': print("Thank you") else: aadhar = int(input("Give your adhar number ")) name = input("enter your name") cursor.execute("SELECT AA...
2345ec144325d83368e30e6003dc433b36c64e49
EarthCodeOrg/earthcode-curriculum
/modules/m0003_recursion.py
3,079
4.5
4
# RECURSION # recursion is simply a function calling itself, or a small collection of functions that are calling themselves def a_recursive_func(a): if a < 1: print(a) a += 1 a_recursive_func(a) #a_recursive_func(-10) # loops are built with recursion under the hood (in assembly for ex) # p...
64fef01dcc207fc7e1d965d319f03433672f2429
EarthCodeOrg/earthcode-curriculum
/modules/recursive_to_iterative.py
544
4.15625
4
# Recursive to Iterative # Approach 1: Simulate the stack def factorial(n): if n < 2: return 1 return n * factorial(n - 1) def factorial_iter(n): original_n = n results = {} inputs_to_resolve = [n] while inputs_to_resolve: n = inputs_to_resolve.pop() if n < 2: results[n] = 1 else: ...
5b5bb6efe533c87cb55fd73e433eb59a0553d1e4
bparinas/py4e
/grade.py
509
3.984375
4
score = input("Enter score between 0.0 - 1.0: ") try: f_score = float(score) if (f_score < 0.0 or f_score > 1.0) : print("Score",f_score,"is out of range") except: quit() if f_score <= 1.0 and f_score >= 0.9 : print("A") elif f_score >= 0.8 and f_score < 0.9 :...
7d0330b4971cc8f27b5f8b962df1a09ef8f56013
langitem/python_exercises
/lpthw/ex19.py
602
3.6875
4
#!/usr/bin/python def cheese_and_crackers(cheese_count, box_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d box of crackers!" % box_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" print "We can give the function numbers directly:" amount_of_cheese = 10 amou...
78d45adfc3645214c240954b35468188fa702391
awolden/advent2020
/day5/main.py
1,277
3.515625
4
# https://adventofcode.com/2020/day/5 import math import os ROWS = 128 COLUMNS = 8 def process(): data = read_file('input') part_one(data) part_two(data) def part_two(data): seats = [get_seat_id(boarding_pass) for boarding_pass in data] seats.sort() for i, seat in enumerate(seats): if i+1 < len(seats...
f2a9b7ec51fa931682743a4957d34a9a80441679
ModellingWebLab/chaste-codegen
/chaste_codegen/_script_utils.py
676
4.15625
4
import os def write_file(file_name, file_contents): """ Write a file into the given file name :param file_name: file name including path :param file_contents: a str with the contents of the file to be written """ assert isinstance(file_name, str) and len(file_name) > 0, "Expecting a fi...
dae4d467ff187ab8cbf6d5175e6656ea563854a3
sbuddhiraju/Symbolic-Regression
/equation_tree.py
3,604
3.578125
4
from numpy.random import random # implements an equation tree class class Node: def __init__(self): self.val = None # value of node, corresponding to the value up to that node when x is entered and constants are specified self.name = None # name of node self.eq_class = None #...
ef78f6e182ff157c0b41b6a3547e3334aa449f09
git123hub121/python-project
/通讯录/学生信息通讯录.py
4,294
3.953125
4
import sqlite3 # 打开数据库 def opendb(): conn = sqlite3.connect("e:\mydb.db") cur = conn.execute("""create table if not exists tongxinlu(usernum integer primary key,username varchar(128), passworld varchar(128),address varchar(125), telnum varchar(128))""") return cur, conn #查询全部信息 def showalldb(): ...
ec815ae7eea0e5dc677698324a9834380d88e5d4
KavilanNaidoo/Functions
/Calculate basic pay.py
877
4.0625
4
#Kavilan Naidoo #18-11-2014 #Calculate basic pay def calculate_basic_pay(hours,pay): total = hours * pay return total def calculate_overtime_pay(hours,pay): overtime_pay = (hours - 40) * (pay * 1.5) basic_pay = 40 * pay total = basic_pay + overtime_pay return total def calcula...
38d62c70bad4b50cc6b56f5eeb3145f8ea1c0588
minlo/smartfix
/feature_engineering/generate_n_order_diff.py
5,417
3.53125
4
from sklearn.base import BaseEstimator, TransformerMixin import pandas as pd class GenerateNDiffFeatures(BaseEstimator, TransformerMixin): """Fit and transform data to get diff features. target_column: str We are gonna generate diff features on this column. look_forward_days: int Number ...
d0bf5cbec6cc10cecfd3a5e556851908df86110e
pliz/PDF-guard
/pdf-encryptor.py
651
4.15625
4
from PyPDF2 import PdfFileWriter, PdfFileReader pdfWriter = PdfFileWriter() # Read the pdf file which will be encrypted pdf = PdfFileReader("example.pdf") for page_num in range(pdf.numPages): pdfWriter.addPage(pdf.getPage(page_num)) # Encryption process goes here passw = input('Enter your password: ') pdfWriter...
7b8f5858686b6f742e2ce5273edd9e2bcbdb7511
YoonkyungH/Network_programming
/HW3_YOONKYUNG_HA/hw3_2.py
972
3.671875
4
d = [{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'}, {'name':'Princess', 'phone':'555-3141', 'email':''}, {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}] # 전화번호가 8로 끝나는 사용자의 이름 출력 for i in range(len(d)): if d[i]['ph...
5fc3cf87167e7da2aec86a7631fd0ded0bb3e47d
baoyuanjin/mypython1
/mystr.py
321
3.703125
4
''' 这是一个字符串的练习 ''' week = "星期一星期二星期三星期四星期五星期六星期天" chose = int(input("请输入你选择的日期(0-7):\n")) if chose == 1: print("今天是",week[0:3]) elif chose == 2: print("今天是",week[3:6]) else: print("输入数字超出范围!",chose)
132ccc6045569073d3a76e8eb21cec524565403e
rboudrouss/adventofcode2020
/day3/part1.py
371
3.5
4
if __name__ == "__main__": (lambda i,n,x:[n:=n+1 for y in range(1,len(i))if(x:=(3+x)%len(i[0]))+1 and i[y][x]=='#'][-1])(open("i",'r').read().split('\n'),0,0) # def main_debug(inp,D=1,R=3): nb=x=y=0 inp = inp.split('\n') maxx = len(inp[0]) for y in range(0,len(inp),D): if inp[y][x]=='#': ...
8cf7391c4310c65d46970aa0d8dbd4bac4488971
printpythonpattern/projects
/Python Project 1d.py
1,129
4.03125
4
# to import package import turtle as pattern # to view in full screen screen = pattern.Screen() # to set the screen size screen.setup(width = 1.0, height = 1.0) # to remove close, minimize, maximize buttons canvas = screen.getcanvas() root = canvas.winfo_toplevel() root.overrideredirect(1) # turtle ...
23ee062052cb5c0865d47a5c69ba61d34c269cca
Sadeeptha-B/Algorithm_implementations
/hashtable.py
4,222
3.78125
4
""" HashTable implementations """ __author__ = "Sadeeptha Bandara" class HashTable: """ HashTable that makes use of cuckoo hashing """ DEFAULT_TBL_SIZES = [13, 7] DEFAULT_KICK_LIMIT = 10 def __init__(self, size_tbl_one=DEFAULT_TBL_SIZES[0], size_tbl_two=DEFAULT_TBL_SIZES[1]): """ ...
2a185cc736922ae8baff835e5d0b9b3727dc7fc3
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q139_word_break.py
1,980
4.28125
4
import re from typing import List def wordBreak(s: str, wordDict: List[str]) -> bool: """ Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multip...
2b28dd3ac32263bf25c0379873cbbf8a98ee9b61
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/tests/Q3_longest_substring_without_repeating_characters_test.py
644
3.84375
4
import pytest from leetcode.problem_sets.Q3_longest_substring_without_repeating_characters import longest_substring_without_repeating_characters def test_longest_substring_without_repeating_characters(): string = "abcabcbb" ans = longest_substring_without_repeating_characters(string) assert ans == 3 ...
9c247e16b233880e248b9c7b4424324df108b1d6
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q172_factorial_trailing_zeroes.py
683
3.96875
4
def trailingZeroes(n: int) -> int: """ Given an integer n, return the number of trailing zeroes in n!. Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. Example 1: Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: n = 5 Output: 1 Explana...
0c822fefe2815bf1f401a6ae0e5ca175fd252ee8
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q46_permutations.py
1,137
4.125
4
from typing import List def permute(nums: List[int]) -> List[List[int]]: """ Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Examp...
6b91e70df04c6feb54be4da4c340b151951f0a4e
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q169_majority_element.py
1,126
4.28125
4
from typing import List def majorityElement(nums: List[int]) -> int: """ Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: num...
8d11f8a825d05e8ebd37907386d9253b2af7170f
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q1004_max_consecutive_ones_iii.py
1,176
3.859375
4
from typing import List def longestOnes(nums: List[int], k: int) -> int: """ Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. Example 1: Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6 Explanation: [1,1,...
cd2d86cd6a9e91412e5e4eaac9d33716291177e2
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/CSES_Problem_Set/Q2_missing_number.py
1,248
4.125
4
""" You are given all numbers between 1,2,…,n except one. Your task is to find the missing number. Input The first input line contains an integer n. The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive). Output Print the missing number. Constraints 2 ≤ n ≤ 2*10^5 Example ...
856d259f74a1016e5cc43bfe2bc9bb714108ed2c
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q20_valid_parenthesis.py
1,243
4.28125
4
def isValid(s: str) -> bool: """ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order....
6ad68ea092a6435db680bd485a1279b2de19292d
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q11_container_with_most_water.py
1,501
4.25
4
from typing import List def container_with_most_water(height: List[int]) -> int : """" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines...
5fb58d360ced84b59ad8042791f025d1dc1c7a3e
abhishekhandacse/HealthFirst
/Welcome.py
1,009
4.03125
4
# create a splash screen, 80% of display screen size, centered, # displaying a GIF image with needed info, disappearing after 5 seconds import tkinter as tk root = tk.Tk() # show no frame root.overrideredirect(True) width = root.winfo_screenwidth() height = root.winfo_screenheight() root.geometry('%dx%d+%d+%d' % (width...
8561fcb30c8b84dac86e6be75b49db0bd491a4e8
Accelegator/accelegator
/route_commands.py
838
3.5
4
""" Routes commands to the REPL """ def route_commands(command, arg1, arg2): call = 0 if command == "list": call = 1 if command == "show": if arg2 == "": call = 2 else: call = 3 if command == "search": if arg2 == "": call = 4 ...
88e9fea30a0c6d78c7e421c18d5b63d3b694f0b4
Accelegator/accelegator
/parse_arguments.py
897
3.6875
4
""" Parses command-line arguments """ import argparse import logging def parse_arguments(args): """Parse command-line arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( "-d", "--debug", help="Displ...
9342f441b458c41e9841f863227cb526fc0f7380
FuongHoa/hoalephuong-lab-C4E22
/lab2/dantri.py
1,120
3.609375
4
# 1. Download the webpage from urllib.request import urlopen from bs4 import BeautifulSoup import pyexcel url = "https://dantri.com.vn" # 1.1 Open a connection conn = urlopen(url) # 1.2 Download raw data raw_data = conn.read() # 1.3 Decode data webpage_text = raw_data.decode("utf-8") #1.4 Save text # w - write # b...
db2e4c75a3c214e747cb52d749965a6060e2ed9b
FuongHoa/hoalephuong-lab-C4E22
/lab1/homework/matplotlib-example.py
361
3.578125
4
from matplotlib import pyplot #prepare data machine_counts = [18, 4, 2] #prepare labels machine_names = ["PC", "MAC", "Linux"] #draw pie chart pyplot.pie(machine_counts, labels = machine_names, autopct="%.1f%%", shadow=True, explode=[0, 0.2, 0]) pyplot.title("The percentage of the number of ppl using which laptop") ...
fb4ebb506769b1e9b267f56b597ed2a86d5c5fd3
chenxshuo/Learn-Python-the-hard-way
/ex3.py
382
3.578125
4
#coding= utf-8 print "I will now count something" print "Hens", 65 + 32 / 7 #计算 65加32除以七的值 print "Roosters", 46 - 14 * 6 % 4 print "what is the result of '3 + 4'?", 3 + 4 print 3 + 2 < 5 - 4 print 9%3 #9%3 表示(3/9)的余数 为零 3%9表示(9/3)的余数 为3 print "Is it greater?", 5 > -3 print "Is it true that 5 <= 2 ?", 5 <= 2 print...
4cf6aad1e877bbf5452b144123061953e2cf3f0c
tnakaicode/pygrasp
/pygrasp/Map.py
6,362
3.796875
4
from __future__ import division import os import numpy as np import matplotlib.pyplot as plt """ This is an abstract class that contains methods useful for maps. """ class Map(object): # Figure out if it's possible to get subclasses to read # their own shape and data_type class variables. def __init__(...
e8f9a0b8242e7ae2884958405ffc4a64dbaf7c68
NerdParker/Pandas_Kaggle
/Creating Reading and Writing.py
1,119
3.75
4
# -*- coding: utf-8 -*- """ @author: ParkerHall """ #imports pandas and Kaggles feedback system import pandas as pd pd.set_option('max_rows', 5) from learntools.core import binder; binder.bind(globals()) from learntools.pandas.creating_reading_and_writing import * print("Setup complete.") #creates a DataFra...
2be28d3c7f1d27878116b489ddf78409f4fe1a2c
bheinks/2018-sp-a-puzzle_4-bhbn8
/priorityqueue.py
1,194
4.21875
4
class PriorityQueue: """Represents a custom priority queue instance. While Python has a PriorityQueue library available, this is more efficient because it sorts on dequeue, rather than enqueue.""" def __init__(self, key, items=[]): """Initializes a PriorityQueue instance. Args: ...
cca2f39a74c3bd497a67a33f542ad63de640fee7
ATurico/Introduction2
/main.py
54
3.71875
4
x=int(input("Name:")) print("Hello ", x) x=10 print(x)
6129a7ebd44a1877a9bf30b13320bedab2263717
PacktPublishing/Java-to-Python-in-100-Easy-Steps---The-Fastest-Way-to-Learn-Python-for-Experienced-Java-Programmers
/python-code/oops/oops_in_depth.py
274
3.921875
4
class Planet: def __init__(self, name, distance_from_sun): self.name = name self.distance_from_sun = distance_from_sun earth = Planet('Earth', 200) mars = Planet('Mars', 500) earth.speed = 10000 print(earth.speed) # mars.name = 'Mars' print(mars.name)
9d0ac2b4ca348881fd44956c3ef6398c9e207f9d
PacktPublishing/Java-to-Python-in-100-Easy-Steps---The-Fastest-Way-to-Learn-Python-for-Experienced-Java-Programmers
/python-code/python-hello-world/menu_with_if.py
537
4.09375
4
number1 = int(input("Enter Number1:")) number2 = int(input("Enter Number2:")) print("Choices Available are ") print("1 - Add") print("2 - Subtract") print("3 - Divide") print("4 - Multiply") choice = int(input("Enter Choice: ")) print("Your Choices are") if choice == 1: print(f"Result = {number1 + number2}") el...
6f8c0f8f11363eb7d3384df0a21b7fc93b1fcc2f
kumarshrestha009/computer_vision_python_opencv
/video_basics_opencv/Video_basics_opencv_assignment.py
1,068
3.921875
4
'''You only have one task here. Create a program that reads in a live stream from a camera on your computer (or if you don't have a camera, just open up a video file). Then whenever you click the left mouse button down, create a blue circle around where you've clicked.''' import cv2 cap = cv2.VideoCapture(0) #CALLBA...
a61582c87e799974a4c0d4b646f9b97244e39c7c
btardio/dataviz_warmups
/day6/warm-up-day-6-ex1-solution.py
452
3.84375
4
# # Given the following sequence of 1's and 0's write the reverse function that # makes 0's 1's and 1's 0's. # # 1001 # 0100 # 1011 # 1110 # def a(n): print (n + 1) def b(n): print (n - 1) def c(n): print (n) def reverse(s): for i in s: if i == '1': b(int(i)) ...
9bbfe357814f4a2a3581e9c4a3ce931d97bcc4a9
btardio/dataviz_warmups
/day5/warm-up-day-5-ex3-solution.py
412
3.578125
4
words = ['whisk', 'fresh', 'chop'] encoded = [] decoded = [] print(words) for word in words: encodedword = '' for charac in word: encodedword += chr(ord(charac)+1) encoded.append(encodedword) print(encoded) for word in encoded: decodedword = '' for charac in word: ...
404154ad1971becad237613ed4364cf76b8283b3
jayeshhinge98/demo
/python/functions.py
318
3.9375
4
def add(a,b): return a+b def studentScore(name,*score): if name=="" and score==0: print("Name and score is empty. please enter names again") name=input("Name? ") score=input("Marks? ") studentScore(name,score) else: print("Student ",name,' scored ',score,' marks.')
ec9ab3c13b26dfbfbf5edf2225ae6870f59a7e80
lucguittard/DS-Unit-3-Sprint-2-SQL-and-Databases
/module2-sql-for-analysis/practice.py
946
4.21875
4
# Working with sqlite # insert a table # import the needed modules import sqlite3 import pandas as pd # connect to a database connection = sqlite3.connect("myTable.db") # make a cursor curs = connection.cursor() # SQL command to create a table in the database sql_command = """CREATE TABLE emp (staff_number INT...
6a09413ad26a2cb7709d2120701ef5cd0b42f76a
webgoal/dojos
/numero-extenso/extenso_alt.py
1,368
3.84375
4
class Numero: algarismos = {1:"um", 2:"dois", 3:"tres", 4:"quatro", 5:"cinco", 6:"seis", 7:"sete", 8:"oito", 9:"nove", 10:"dez", 11:"onze", 12:"doze", 13:"treze", 14:"quatorze", 15:"quinze", 16:"dezesseis", 17:"dezesete", 18:"dezoito", 19:"dezenove", 20:"vinte", 30:"trinta", 40:"quarenta", 50:"cinqu...
eac026460f5faa4ece947fb9aba8afee326d00bf
Pratyush1014/Python
/ControlstrucControlstat/max.py
218
3.984375
4
a = input("Enter a : ") b = input("Enter b : ") c = input("Enter c : ") if a>b : if a>c : print 'max is : ', a else : print 'max is : ', c else : if b>c : print 'max is : ', b else : print 'max is : ', c
17dd73ad52fd89f968bc870371f34bd309f58ed1
Pratyush1014/Python
/ControlstrucControlstat/numbers/palindrome.py
150
3.78125
4
n = input("Enter any number :") b = n rev = 0 while n>0 : rev =rev*10 +n%10 n=n/10 if b == rev : print "Yup its a palindrome" else : print "Nope"
6604a01039033c309c27ca267e9eb622a1d9647b
Pratyush1014/Python
/ControlstrucControlstat/list/maxnmin.py
433
3.8125
4
list = [] i = 0 temp = 0 while True : n = input("Enter the elements to be pushed") list.append(n) ch = raw_input("Do you wanna continue (y/n)") if ch == 'y' : continue else : break print list max = 0 min = list[0] for i in range (0,len(list),1) : ...
db33b9b37bcc7fa8b237aaa19ff9547e89b0d68e
Pratyush1014/Python
/datatypes/list.py
335
3.734375
4
x = list () print x ,type(x) x = list([1,2,3,4,5,6]) print x ,len (x) x = [10,20,30,40] print x , type (x) y = [1,2,3,4,5,6,7,8] x = y [1:6] print y print x reverse = y[-1::-1] print reverse reverse1 = y[ :: -1] print reverse1 z = list ([11,22,33,44,55,66]) print z[0] z[1] = 21 print z z[0:5:2] = [0,0,0] print z del ...
3ae08dfaa3892d5202b9520ef1afdc37608af60b
Pratyush1014/Python
/datatypes/listfunctions.py
458
3.796875
4
x = [1,2,3,4,5,6,7,8,9] print x x.append(10) print x x.pop(9) print x x.append(11) print x x.remove(11) print x y = [10,11] x.append(y) print x del x[9][1] print x x.remove(y) print x y=[10,11,12] x.extend(y) print x x.insert (1,100) print x x.sort() print x x.sort(reverse = True) print x i=x.index(100) print x#prints...
0297cb1a8c475399dbd839626bbd1b0cc817ed18
Pratyush1014/Python
/class/declarationnmemfetch.py
536
3.703125
4
class test : pass def main() : obj1 = test () obj2 = test () obj3 = test () print id(test) print id(obj1) print id(obj2) print id(obj3) print id(obj1.__class__) obj1.x = 10 obj1.y = 20 obj2.x = 10 obj2.y = 20 setattr(obj3,'x',10) setattr(obj3,'y',20) print obj1.__dict__ print obj2.__dict__ print obj3....
9d90cd511999729a2e725cccf84f598ff74e2132
Pratyush1014/Python
/inheritance/single.py
437
3.640625
4
class person : def __init__(self,name,age) : self.name = name self.age = age def __repr__(self) : return self.name+" "+str(self.age) class student (person) : def __init__(self,name,age,mark,regid): person.__init__(self,name,age) self.mark = mark self.regid = regid def __repr__(self) : return person.__...
d1c4a695c6574a756151c15dc30678eedfa7c9ef
Pratyush1014/Python
/operator/maxof3.py
189
3.984375
4
x = input('Enter the first number : ') y = input('Enter the second number : ') z = input('Enter the third number : ') w = x if x>z else z if x>y else y if y>z else z print "Max of 3 is ",w
ad0624c76595e69bda90a042197d6fab8aecf632
Pratyush1014/Python
/inheritance/supersub.py
278
3.671875
4
from super import person as p class man(p) : def __init__(self,name,age) : super().__init__(name) self.age = age def __repr__(self) : print (super().__repr__()) print (self.age) return str() def main() : obj = man("alpha",45) print (obj) print (obj.mro()) main()
ccddc3ac057c502026bb861a8b5637a67cae9704
Pratyush1014/Python
/ControlstrucControlstat/numbers/bintodec.py
109
3.609375
4
n = input("Enter a binary num :") dec = 0 i = 0 while n>0 : dec = (n%10)*2**i + dec n=n/10 i+=1 print dec
544d87708e36c64ebaa1e548d23f585131612c00
Pratyush1014/Python
/modules/class/engineer.py
327
3.625
4
from person import person class engineer(person) : def __init__(self,name,age,dept,salary,company) : person.__init__(self,name,age) self.dept = dept self.salary = salary self.company = company def __repr__(self): print person.__repr__(self) print self.dept print self.salary print self.company return...
e82e7951682b837b2d75384b1ced61427a21ba40
michaelmurwayi/FinanceBot
/financeapi/bank/Transactions/record_transactions.py
1,335
3.96875
4
import csv def create_record(row): """ Create record into a dictionary""" record = { "accountname": row[0], "accounttype": row[1], "branchname": row[2], "phonenumber": row[3], "transactiontype": row[4], "accountnumber": int(row[5]), "transactionamount": float(row[6]), } return validation_for_blanks(record...
cf99592ad8e02503cfa2ff5e72bdd762a49fc2e8
dennisg0505/cs180-projects
/scripts/csv_prims.py
3,145
3.5625
4
#!/usr/bin/env python import sys import csv from collections import defaultdict from collections import OrderedDict # Graph class from https://gist.github.com/econchick/4666413 class Graph: def __init__(self): self.nodes = set() self.edges = defaultdict(list) self.distances = {} def add_node(self, v...
225337b95d81996e4ccfc1d9be75b86e9e1cd934
bl00p1ng/ejercicios-basicos-python
/entrada_datos_teclado/ejercicio05.py
433
3.75
4
def run(): # Ejercicio 5 # Escribe un programa que calcule el salario semanal de un empleado en base # a las horas trabajadas, a razón de 12 euros la hora print('**** CALCULADORA DE SALARIO ****') hours = int(input(':: Ingresa el número de horas que trabajaste esta semana: ')) print(f'Trabajas...
fa338cc1299fce474dca192022697e06bf8b9b98
bl00p1ng/ejercicios-basicos-python
/variables/ejercicio01.py
592
3.9375
4
def run(): # Ejercicio 1 # Escribe un programa en el que se declaren las variables enteras x e y. Asignales # los valores 144 y 999 respectivamente. A continuación, muestra por pantalla # el valor de cada variable, la suma, la resta, la división y la multiplicación. x = 144 y = 999 ...
6dbdcd37813cb368b1540129b2f4e64aa1c15e6e
deepakdashcode/data_structures
/list_comprehensions/questions.py
263
3.6875
4
vals=[1,2,3,4,5,33,24,27,90,43,45,46,47] mul3=[i for i in vals if i%3==0] print(mul3) ls=[('a',11),('b',12),('c',13)] new_ls=[n*3 for (a,n) in ls if a =='a' or a=='b'] print(new_ls) odd_even=['Even' if i % 2 ==0 else 'Odd' for i in range(1,10)] print(odd_even)
c9383ad52e23d0a2ed43dfae9b6d488d067da5cc
deepakdashcode/data_structures
/searching/binary_search.py
527
3.515625
4
ls = [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 32, 43, 45, 78, 778] def binary(element, ls): ls.sort() lower = 0 higher = len(ls)-1 ind = -1 while lower <= higher: mid_ind = (lower + higher) // 2 middle_element = ls[mid_ind] if element == middle_element: ind = mid_ind ...
c79ab803bbcb372dbb07d54f82c683ec075561d9
BrandonJanisieski/SNHU-CS-210
/Module 7 Project/Release/PythonCode.py
2,349
4.03125
4
import re import string def ItemsPurchased(): f = open('GroceryItems.txt') #Opens grocery items list contents = f.read() #Reads GroceryItems, and sets it to "contents" items = contents.split() itemsBought = [] #List that stores the items bought from the file for item in items: #fo...
9be16c2bbba8d226697e416c81b970e2a9394389
TimeMachine00/Youtube_python_projcet
/python-project-5.py
483
4.0625
4
# Welcome to AI-PY youtube Channel """ pizza bill calculator """ size = input("choose piza size: S, M, L\n") add_pepporoni = input("do you want pepporoni: yes or no\n") cheese = input("do you want extra cheese: yes or no\n") bill = 0 if size == 'S': bill+= 200 elif size =='M': bill+=250 elif size == "L": ...
c8c26d46e85c8556e559b68e892a80d7578d8b26
GuiLendr/course-material
/exercices/080/solution.py
264
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 23 10:05:30 2014 @author: Guillaume """ import string alph = string.ascii_lowercase lettre = list(alph) for i in alph: for j in alph: if(i != j): if(i < j): print(i+j, "\n")
5c510bf85657dd9b66f54aad64d498ef12a2a244
michaelvargasloza/Python-Programacion-orientada-a-objetos-python-desde-cero-
/Ej7.py
538
4.09375
4
#Método constructor de clase class Usuario: def __init__(self): self.usuario = "" self.ingresos = 0 def intro(self): self.usuario = input("Ingrese el nombre del usuario: ") self.ingresos = float(input("Cantidad ingresos anual: ")) def visualizar(self): print("Nombre:", self.usuario) print("Ingresos:", ...
c377013df48ceae17282d06e8dca6a0fe2d9628f
michaelvargasloza/Python-Programacion-orientada-a-objetos-python-desde-cero-
/Ej9.py
1,082
4.09375
4
#Llamada de métodos desde otro método de la misma clase class Alumnos: def __init__(self): self.nombres = [] self.notas = [] def menu(self): opcion = 0 while opcion != 4: print("1.- Cargar alumnos.") print("2.- Listar alumnos.") print("3.- Listado de alumnos con notas mayores o iguales a 7.") pri...
ed7f6e45ccd4b64953fda1225ea58476cc803e8e
huguofengcool/python
/get_labels.py
555
3.53125
4
import os, sys def loadfileAndgetlabel(filename): filelists=[] with open(filename,'r') as fl: readlines=fl.readlines() for line in readlines: line=line.strip().split() filelists.append(line[1]) return filelists def writeTofile(filelists,labelfile): label=[] label=filelists with open(labelfile,'w+') as...
dafd5fab826ef11850bdcbd5e7c74834863e1004
djFooFoo/euler
/ex_4.py
805
3.75
4
def isPalindrome(numberString): if numberString == numberString[::-1]: return True return False def ex_4(): currentHighestProduct = 0 product = 0 for i in range(999, 100, -1): for j in range(999, 100, -1): product = i * j if product > currentHighestProduct and isPalindrome(str(product)): currentHigh...
35ec4efa237c2acaccab8e526c0a9180a1df50f8
djFooFoo/euler
/ex_5.py
575
4
4
def gcd(a, b): while b != 0: (a,b) = (b, a%b) return a def lcm(a,b): return a * b / gcd(a,b) def ex_5(): return int(functools.reduce(lambda x,y: lcm(x,y), range(1,21))) import functools import time start_time = time.time() print(ex_5()) print("--- %s seconds ---" % (time.time() - start_time)) # ...
5703b4306e364aa6c34b937de4d6c54caf787c98
YuanG1944/COMP9044-Software-Construction
/lab01/dictionary/generate_answer_sheet.py
1,226
3.734375
4
#!/usr/bin/python3 import re, sys, html print_answers = not not sys.argv[1:] print(""" This file is automarked. Do not add extra lines to this file, just add your answers. For example if your answer to Q1 is: egrep Andrew words.txt Change the line that says Q1 answer to: Q1 answer: egrep Andrew words.txt """) q...
ecb46f3c69690021ce2d529c4db0e688d7c45559
jjun0127/ML
/MNIST_01.py
3,112
3.625
4
import tensorflow as tf import random import matplotlib.pyplot as plt import numpy as np tf.set_random_seed(777) # for reproducibility # Check out https://www.tensorflow.org/get_started/mnist/beginners for # more information about the mnist dataset #mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trai...
2b4dc52d947105fc5dfe2fa8a13441706b794b57
perfectlyodd/spoj-python
/palindrome-submission.py
2,617
4
4
def inner_string_number(string_number, length): if length <= 2: return '' return string_number[1:-1:] def add_one_to_string(string_number, length): if length == 0: return '1' position = 1 carry = True while carry: char = string_number[length - position] if positi...
c5c04301b377f99cf2b9420248d2a3ab1c913267
Melkemann84/ProjectEuler
/projectEuler_04.py
820
3.703125
4
import time # https://projecteuler.net/problem=4 ''' Larges palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' def isPalindrome(num): ...
7e18a133569500ee277404ea04521ad0a70011f8
MrR3set/file_encription_script
/main.py
1,259
3.71875
4
from cryptography.fernet import Fernet from keygen import getKey import tkinter as tk from tkinter import filedialog def encrypt(key, file): with open(file,"rb") as f: message = f.read() f.close() fernet = Fernet(getKey(key)) cipherTxt = fernet.encrypt(message) with open(file+".encrypt...
afd7945111023bed23758197b2c3e3f9048d5fd8
DivAnanand/div2
/Project Note Making/FIRST.py
2,776
3.71875
4
from tkinter import * def btnClicke(numbers): global operator_1 operator_1 += str(numbers) text_Input.set(operator_1) def btnClearDisplay(): global operator_1 operator_1=" " text_Input.set(" ") def btnEqualsInput(): global operator_1 sumup = str(eval(operator_1)) text_...
23b32a35acc060b021706f17754c0e1479259025
saranaweera/dsp
/python/q8_parsing.py
701
4.3125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to r...
62c80c43d1099afb413f7b6736234fc09616b8b0
NielsOelderik/NielsProg1
/PE3_1.py
147
3.578125
4
x = int(input('geef je score: ')) if x >= 15: print('gefeliciteerd!') print('met een score van' + ' ' + str(x) + ' ' + 'ben je geslaagd!')
656a32a3781605c1f68539cfcdc3e8de98bf4181
sivaneshl/real_python
/implementin_linked_list/implementing_a_own_linked_list.py
1,765
4.46875
4
from linked_list import LinkedList, Node # using the above class create a linked list llist = LinkedList() print(llist) # add the first node first_node = Node('a') llist.head = first_node print(llist) # add subsequent nodes second_node = Node('b') third_node = Node('c') first_node.next = second_node secon...
048ad1d2b51974943f5fae0a16cb94fa68eee496
sivaneshl/real_python
/implementin_linked_list/linked_list.py
5,735
4.34375
4
# class LinkedList will only have the pointer to the start of the linked list class LinkedList: def __init__(self, nodes=None): self.head = None # if the nodes list is provided, create the linked list if nodes is not None: # assign the head node node = Node(dat...
e4e23a6768515f70806fdaed6dd8a9126c6f7b0e
HPRIOR/DS-Algo-Zoo
/DynamicProgramming/best_sum.py
1,303
4.09375
4
# best_sum(target, numbers) -> [shortest array that sums to target] def best_sum(target, numbers, memo=None): if memo is None: memo = {} if target in memo: return memo[target] if target == 0: return [] if target < 0: return None # this will store the shortest comb...
54c2219352f2ab1b9eef98121ec12cf594a408c3
HPRIOR/DS-Algo-Zoo
/Backtracking/wordsearch.py
691
3.828125
4
''' board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" = true ''' def exists(board, word): directions = [(0, 1), (0, -1), (1, 0)] def helper(current_word: str, d): if current_word == "": return True if current_word.startswith(board[d[0]][d[1]]): ...
716f908f00bf730be4c2666dda6fefd682c9afa0
HPRIOR/DS-Algo-Zoo
/SortingSearching/DutchNationalFlagProblem.py
715
4.0625
4
""" given an array of numbers from 0-2, sort an array such that it is in the order 0,1,2 The solution is to have 3 pointers p1: right-most boundary of 0's p2: left-most boundary of 2's current: pointer under evaluation for swapping """ def dutch_flag(nums): p1 = current = 0 p2 = len(nums) - 1 while curre...
e2ac9238ece7a5dcf73994dd710942ec589bb7e1
vuva/MAppLE
/dash/chunkstats.py
622
3.625
4
#!/usr/bin/env python3 import math import sys sizes = [] def get_mean(l): return sum(l) / len(l) def get_median(l): return sorted(l)[len(l) // 2] def get_variance(l): mean = get_mean(l) return math.sqrt(sum([(x - mean)**2 for x in l]) / (len(l) - 1)) with open(sys.argv[1], "r") as f: sizes =...
a31d8cdab733831abee2ced3449388266b24adf1
mehta-smit/python_ITMCS
/fun_with_anagram_best_practice.py
314
3.5625
4
def funWithAnagram(text_items): text_cp = text_items[:] [text_cp.remove(text_items[i]) for i in range(1, len(text_items)) if sort_string(text_items[i-1]) == sort_string(text_items[i])] return text_cp def sort_string(text): text_list = list(text) text_list.sort() return "".join(text_list)
3f3beb620cdd988100776d254531edae193d9f9e
mehta-smit/python_ITMCS
/math/nprime.py
533
4.03125
4
import sys import list.duplicates_remove def main(arg=None): if arg is None: arg = sys.argv[1:] n = int(input("get primes upto n number : ")) prime(n) def prime(n): noprimes = [j for i in range(2, 8) for j in range(i*2, n, i)] print("not primes :", noprimes) #before sort noprimes = li...
809c27c87a2645637c9aed1907816fa12ba9d6c8
ebylund/school.erikbylund.com
/challenges/data/newLineStripper.py
316
3.5625
4
__author__ = 'ebylund' def main(): fileToStrip = raw_input("Enter file name to strip: ") outputFile = raw_input("Enter output file name: ") fin = open(fileToStrip, "rb") fout = open(outputFile, "wb") for line in fin: for word in line.split(): fout.write(word + " ") main()
f9a3a507cd10b821e54d4f771ca42b596fb4c4af
nelsongo4/GrovePi-EE250
/ee250/lab06/json_test.py
560
3.78125
4
import json # json library: https://docs.python.org/3.5/library/json.html person = { 'name': 'Tommy Trojan', 'email': 'tommy@usc.edu', 'phone': '213-740-2311', 'nicknames': [ 'Tommy T', 'Spirit of Troy', ], } print(type(person)) print(person) person_json = json.dumps(person) prin...
cff7da06f9295aca95bf19a68531a72827adf88f
Genius-AQ/sklearn_demo
/knn_pandas.py
764
3.84375
4
""" Reference: https://www.dataquest.io/blog/k-nearest-neighbors-in-python/ """ import pandas from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split """ Load data """ with open('iris.csv', 'r') as f: iris = pandas.read_csv(f) # Attribute columns X = iris.drop(colum...
d504c26783f51d7ebd7e179fda8b58d9ae25e090
skydragonceo/Game-of-Life
/GameOfLife.py
43,010
3.59375
4
from Tkinter import * import os import urllib import random #Images of Game of Life owned by Hasbro #Images retrieved from http://blog.nicoledelsenno.com/?p=212 #http://recruiterpoet.files.wordpress.com/2011/07/life2.gif #Images of Mario and Koopa ownership of Nintendo #Images retrieved from http://www.spriters-resour...
37898e1d98f7a08c52d2dc6fc80779c54ba60685
nnamon/ctf101-systems-2016
/lessonfiles/offensivepython/11-stringencodings.py
864
4.125
4
#!/usr/bin/python def main(): sample_number = 65 # We can get binary representations for a number print bin(sample_number) # Results in 0b1000001 # We can also get hex representations for a number: print hex(sample_number) # Results in 0x41 # Also, octal: print oct(sample_number) # Re...
47edb4eb16b771df7faaab42dffd46585cac3d8b
nnamon/ctf101-systems-2016
/lessonfiles/compromise/1-denialofservice.py
985
3.828125
4
#!/usr/bin/python import socket def main(): HOST, PORT = "localhost", 0 # Create the server, binding to localhost on a free port server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen(10) # Print the connection information print "Please connect...
a77b285f309ccdc966c4f4a912ae4701d05fd954
LINDBURG/Programmers
/test.py
2,439
3.515625
4
class Geograph(): def __init__(self, land, height): self.land = land self.height = height self.queue = [] self.nodes = [Node(i, land[i//len(land)][i % len(land)], len(land)) for i in range(len(land)**2)] self.answer = 0 self.include = [] self...
30acb72fbdd43924e40866227aeefe6e8d8d9c27
LINDBURG/Programmers
/2020_KBR_가사 검색.py
1,319
3.71875
4
class trie: def __init__(self): self.next = dict() self.count = dict() def insert(self, word): now = self for c in word: if len(word) not in now.count: now.count[len(word)] = 0 now.count[len(word)] += 1 ...