blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c3229af99a74ee76d1a992aa22323a14716a8656
geekidharsh/tilt-python
/pandas-notes/pandas-df-01.py
1,953
4.3125
4
import pandas as pd import os import numpy as np #create a sample dictionary data web_stats = {'Day': [1,2,3,4,5,6], 'Visitors':[12,43,23,54,67,23], 'Bounce_Rate':[65,72,34,21,89,101], 'Engagement':[5,6,8,9,10,11]} sampledf = pd.DataFrame(web_stats) # clears the screen on windows, delete this line...
e97e4cf17ef1d981a6c64e737e04364e8f5bb995
geekidharsh/tilt-python
/unordered-tilt-works-py/web-scrape-bsoup-02.py
1,130
3.65625
4
import requests import bs4 from BeautifulSoup # trying here for multiple urls url = ['www.example.com', 'www.example-1.com'] #r to get the request from url string, #use_soup to get use bs4, links to store all the a tags that we find r = requests.get(url) use_soup = BeautifulSoup(r.content) links = use_soup.find_all(...
11f49ad3ed19374f2c716e7771a576227e232a67
geekidharsh/tilt-python
/unordered-tilt-works-py/chilliPicker.py
12,616
4.21875
4
# From a bunch of chocolates and a chilli in a jar. # Find a way to pick any number of chocolates each time so that the last item left is always the chilli # total number of items in the jar is given def main(): items = ['choco', 'choco', 'choco', 'choco','choco', 'choco', 'choco', 'choco', 'choco', 'choco', 'choco',...
e565e7201c7307b0c6a7434101a0db27531f2d9f
geekidharsh/tilt-python
/python-basics/python basics/classes-2.py
1,318
4.34375
4
# 1. Python Class # Simplest look of a python class is something like this: class MyClass: # <statements> # <statements> i = 1.2345 def f(args): return "Hi from f" def example(self): return "Hello from example" # Python classes just like any other class feature all functionalities of OOP, # syntactically i...
335d9f317da43111ffd0b5c2ec1bef831d4a5e26
nrubin/RachelAndNoamsDirectedGraphs
/multithread_analysis.py
2,072
3.59375
4
from multiprocessing import Pool from Wikipedia_PullAndParse import load_object_from_file, save_object_to_file class IndexResults(): """The class basically just acts a container for data, to make it easier to store data, and then access it later """ def __init__(self,name, k, c, n_vs, n_es): se...
8e8fbc09c35081b7acd3877e3be152296c1b16da
collinsanele/A-simple-non-scientific-calculator
/calculator_tkinter.py
6,050
3.71875
4
import tkinter as tk from decimal import Decimal class Calculator_App(): def __init__(self, *args): self.window = tk.Tk() self.window.title('Calculator app') self.fonts = ('times', 9, 'bold') self.text_display = tk.Text(height=5, bd=15) self.text_display.pack() self.btn_exit = tk.Button(...
e7423eb61b8f36aadfe52b3ff1ee1b30d8926c33
mask2live/python_learn
/FileProcessing/file_test.py
1,006
3.75
4
def read_from_file(file_path): with open(file_path, 'r') as f: content = f.read(10) print(content) print(type(content)) def write_to_file(file_path): with open(file_path, 'a+') as f: f.write('\nwhich is your favorite?') f.seek(0) print(f.read()) def getStr...
2dc39f3325b9e6c5dd3fbe1b5e215b19c3dddccc
mask2live/python_learn
/Application4/frontend_script.py
4,920
3.765625
4
from tkinter import * from backend_script import Book_Database """ connect to database server """ db = Book_Database("root", 'Lmy_131724', '42.194.218.246', 'dbtest') def get_selected_row(event): """ mouse click event if the box is empty, nothing will happen when clicked clicked spec...
56e49b9a72d542c840c4c3e1f411c3e8581b2447
EdenAraura/Games-Programming
/Personal Study/Lesson_1/pythonPersonalStudy0.6.py
137
4.125
4
x=input ("say something!") if len(x) >=3 and x[-3:] == "ing": print(x+"ly") elif len(x) >= 3: print(x+"ing") else: print(x)
8fd6111923de004323443d9d3df2b8f105715c64
EdenAraura/Games-Programming
/text adventure0.1.py
350
3.875
4
game = True inv = ["dagger", "axe"] northList = ["north", "n"] yesList = ["y", "yes", "yeah"] while game == True: inp = input("which direction would you like to go?").lower() ##north if inp in northList: print("You encounter an enemy! It hasn't seen you yet...") inp = inpu...
6c1d9099e93402d739b2425403094894ec17b3c2
EdenAraura/Games-Programming
/Classwork/Lesson_3/pythonClass3.1.py
176
3.6875
4
list = ["mix", "xyz", "apple", "xanadu", "rovio"] a = [] b = [] for y in list: if y[0] == "x": a.append(y) else: b.append(y) print(sorted(a)+sorted(b))
b69332abce1da68b2a031aa93710212f920b2f3f
JHanek3/Coursera
/15.1.py
484
3.921875
4
#read json from that url using urlib and then parse #extract comment counts and sum the numbers import urllib.request as ur import json url = input("Enter the url:") if len(url) < 1: url = " http://py4e-data.dr-chuck.net/comments_42.json" data = ur.urlopen(url).read().decode('utf-8') info = json.loads(data...
3217b971ff924ab7e6cf146ac3de058a9ff9979c
MarcusDMelv/HelloGitHub
/OOP_Program.py
2,922
4.25
4
# to abstract methods must import libs from abc import ABC, abstractmethod # todo abstraction part1 # use ABC to identify abstraction class # this class could be used in all classes class Felidae(ABC): # abstract decorator @abstractmethod def family_description(self): pass @abstractmethod ...
52b915bc76613c940501734421cdbb4c4f0a8f73
toonarmycaptain/project_euler
/problem_4/problem_4_solution.py
1,392
4.46875
4
""" 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. """ from typing import Generator, Sequence, Iterable, Union def yield_3_digit_products_from_largest_to_sh...
0508834c8b870419ac13e39d8def6bfb0d14bba7
SnoW246/Emerging-Technologies
/Python-Fundamentals/03-Fizz-Buzz.py
574
4.3125
4
#Problem Set 3 #Adrian Golias #Declaration of the for loop for num in range(1,101): #If the # is a multiple of three if num % 3 == 0: #Output Fizz message to the screen print("Fizz") #Else if the # is a multiple of five elif num % 5 == 0: #Output Buzz message to the screen print("Buzz") #Else ...
6c088447b56daf2d3997c3e832d29bb9fc72d992
yuyama137/osero
/miniosero.py
7,373
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 6 19:19:42 2019 @author: yuichiro """ import numpy as np def start():#盤の初期配置を返す board = np.zeros((6,6)) board[2][2]=1 board[3][3]=1 board[2][3]=2 board[3][2]=2 return board def move(num,myplace): lst=myplace if num=...
9419a15c8b0ce65fcb0eea1ce97d4005746d9010
taskmaker/tutorials
/chap2prob5.py
320
4.1875
4
# Chapter 2 Problem 5 - robot distance travelled - math.pi version import math RADIUS = 2.7 # of wheel, in cm rotations = 2 #robot will travel the circumference of its wheel (pi * d) with each rotation distance = math.pi * RADIUS * 2 * rotations print("Rotations:", rotations) print("Distance travelled:", distance,"cm")
a562e8accb91781230a4ba4056668946d989ed5e
radk0s/ply
/AST.py
10,937
3.671875
4
class Node(object): def accept(self, visitor, table = None): return visitor.visit(self) def setParent(self, parent): self.parent = parent class Program(Node): def __init__(self, declarations, fundefs, instructions): self.declarations = declarations self.fundefs = fu...
c667cd0d65dbe272869e655a3a6bdb7a81fb61e2
varun31415/Pong_python3
/__init__.py
7,848
4.15625
4
# section 1 of the program # This part of the program sets up the variables, and libraries # imports the necassary packages import pygame import sys import math import time import random #initiates the pygame library pygame.init() # defines the basic colors needed red = (255,0,0) green = (0,255,0) blue = (0,0,255...
606ca268b7852d204524c91764329c94b51c0bae
hexxxand16/Recreational-Programming
/sevens/sevens.py
11,048
3.65625
4
from random import shuffle, seed # card object class Card: def __init__(self, suit, rank, play=0): self.suit = suit self.rank = rank self.connect = -1 self.shield = -1 def __str__(self): return "{} of {}".format(self.rank, self.suit) def __repr__(self): re...
3bd4b166cd13a3d1cde4a4d62cbe14857f391176
jocmp/cis343
/project/connect4_python/modules/Board.py
582
3.796875
4
#!/usr/bin/env python class Board: def __init__(self, rows, columns): self.rows = rows self.columns = columns self.grid = [[-1 for x in xrange(self.columns)] for y in xrange(self.rows)] def __str__(self): print_board = "" for i in xrange(0, self.rows): ...
cbede2f77596d8267cd749dffac18f3f726df590
tiber-w/learn-python-the-hard-way
/ex11.py
470
4.09375
4
import datetime print("What's your name?", end = ' ') name = input() print("How old are you?", end = ' ') age = int(input()) print("How tall are you?", end = ' ') height = input() print("How much do you weigh?", end = ' ') weight = input() year = datetime.datetime.now().year print("So, %s was born in %d, %s tall and ...
41f4c365edf7dbd6ea78c865bf8b74bbf2ebc0db
kupreeva/PyCheckiO
/home/house_password.py
1,526
4.21875
4
""" Stephan and Sophia forget about security and use simple passwords for everything. Help Nikola develop a password security check module. The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least one digit, as well as containing one uppercase letter and one ...
54898c8de4667af5de77ac3e8793eb19a0041390
szabgab/slides
/python/examples/advanced/do_while.py
69
3.625
4
x = 0 while True: x += 1 print(x) if x > 0: break
2ece455629ffb98794148251162fae0fd51a2d8c
szabgab/slides
/python/examples/ml/generate_images.py
3,301
3.921875
4
# Generate images for several machine learning projects # Classification # A bunch of images with red shapes, green shapes, yellow shapes. Tag them according to the color and the shape they got. # Simple case: all the images are large circles of the same size # Complex case: allow for more sizes; allow for different ...
fa5cbd281872cd44c45ac778414c3c05c2517220
szabgab/slides
/python/examples/lists/change.py
740
3.828125
4
fruits = ['apple', 'banana', 'peach', 'strawberry'] print(fruits) # ['apple', 'banana', 'peach', 'strawberry'] fruits[0] = 'orange' print(fruits) # ['orange', 'banana', 'peach', 'strawberry'] print(fruits[1:3]) # ['banana', 'peach'] fruits[1:3] = ['grape', 'kiwi'] print(fruits) # ['orange', 'grape', 'k...
47d74bc6d59757d9ca6b5b30284c67a46ab0e892
szabgab/slides
/python/examples/threads/use_queue.py
1,106
3.640625
4
import threading import random import sys import time thread_count = 5 counter = 0 queue = list(map(lambda x: ('main', random.randrange(5)), range(20))) #print(queue) locker = threading.Lock() class ThreadedCount(threading.Thread): def run(self): global counter my_counter = 0 thread = th...
121a78c4de965d5c2e3075770f9ffc073892a96f
szabgab/slides
/python/examples/regex/search.py
282
3.828125
4
import re text = 'The black cat climed' match = re.search(r'lac', text) if match: print("Matching") # Matching print(match.group(0)) # lac match = re.search(r'dog', text) if match: print("Matching") else: print("Did NOT match") print(match) # None
9e3d03921104602702d756a0a79b200a873d1711
szabgab/slides
/python/examples/dictionary/dictionary_of_dictionaries_csv.py
309
3.609375
4
import sys import csv filename = 'examples/csv/monty_python.csv' if len(sys.argv) == 2: filename = sys.argv[1] people = {} with open(filename) as fh: reader = csv.DictReader(fh) for line in reader: people[(line['fname'], line['lname'])] = line print(people[('Eric', 'Idle')]['born'])
efd9e0d4f7fe64950b99fbef9c850609e1b5fc25
szabgab/slides
/python/examples/functions/tower_recursive.py
674
3.984375
4
def check(): for loc in hanoi.keys(): if hanoi[loc] != sorted(hanoi[loc], reverse=True): raise Exception(f"Incorrect order in {loc}: {hanoi[loc]}") def move(depth, source, target, helper): if depth > 0: move(depth-1, source, helper, target) val = hanoi[source].pop() ...
726cd8906ae7a849b83127d0e08bfac4f177f46b
szabgab/slides
/python/examples/csv/count_csv_rows.py
1,089
3.75
4
import csv import sys from collections import defaultdict def check_rows(filename): rows = [] widthes = defaultdict(int) with open(filename) as fh: rd = csv.reader(fh, delimiter=';') for row in rd: width = len(row) rows.append(width) widthes[width] += 1 ...
fb2ea422cd65a5ec4d085987f24885c780af69ac
szabgab/slides
/python/examples/basics/isdigit.py
265
3.84375
4
for var in ["23", "2.3", "a", "2.3.4"]: print(var) if var.isdigit(): print(f"{var} can be converted to int:", int(var)) if var.replace(".", "", 1).isdigit(): print(f"{var} can be converted to float:", float(var)) print('-----')
9bec7e9c41ab11aaeb2f0fb8cb5313dc9b85c0b8
szabgab/slides
/python/examples/numbers/random_choice.py
231
3.609375
4
import random letters = "abcdefghijklmno" print(random.choice(letters)) # pick one of the letters fruits = ["Apple", "Banana", "Peach", "Orange", "Durian", "Papaya"] print(random.choice(fruits)) # pick one of the fruits
926406f3d73dc971c4abd19001992a1a106e8c00
szabgab/slides
/python/examples/exceptions/raise_value_error.py
505
3.734375
4
def add_material(name, amount): if amount <= 0: raise ValueError(f"Amount of {name} must be positive. {amount} was given.") print(f"Adding {name}: {amount}") def main(): things_to_add = ( ("apple", 3), ("sugar", -1), ("banana", 2), ) for name, amount in things_to_ad...
955ee7fd93efc3207c3a35745f417e80113ed626
szabgab/slides
/python/examples/sqlite/counter.py
2,710
3.84375
4
""" Counter using an SQLite backend --list list all the counters --start name creates the counter for 'name' name counts for 'name' """ import sys import os import argparse import sqlite3 database_file = "counter.db" def list_counters(crs): print('List counters:') f...
5c44c6c964c88b562c7e51781dd12cf952eb377a
szabgab/slides
/python/examples/dictionary/counter_condition.py
114
3.828125
4
counter = {} word = 'eggplant' if word not in counter: counter[word] = 0 counter[word] += 1 print(counter)
08a070b54944129959a1f010dd69042fe2f10a17
szabgab/slides
/python/examples/files/read_full_file.py
298
4.0625
4
filename = 'examples/files/numbers.txt' with open(filename, 'r') as fh: lines = fh.readlines() # reads all the lines into a list print(f"number of lines: {len(lines)}") for line in lines: print(line, end="") print('------') lines.reverse() for line in lines: print(line, end="")
9473922c20a57bc5868f4c2bae76bbf3f134ee7f
szabgab/slides
/python/examples/format/formatted_float.py
575
3.71875
4
x = 412.345678901 print("{:e}".format(x)) # exponent: 4.123457e+02 print("{:E}".format(x)) # Exponent: 4.123457E+02 print("{:f}".format(x)) # fixed point: 412.345679 (default precision is 6) print("{:.2f}".format(x)) # fixed point: 412.35 (set precision to 2) print("{:F}".format(x)) # same as f....
127c56d4c47e559c46467e92f0c35fb52aea2dbf
szabgab/slides
/python/examples/functions/call_by_value.py
104
3.578125
4
x = 3 def inc(n): n += 1 return n print(x) # 3 print(inc(x)) # 4 print(x) # 3
1daeb9a2ba3b831f1ccd6dde55ae6c321ea40f5f
szabgab/slides
/python/examples/basics/circle_math_solution.py
158
3.5
4
import math r = 7 print("The area is ", r * r * math.pi) # 153.9380400258998 print("The circumference is ", 2 * r * math.pi) # 43.982297150257104
7d0a14e8104b17cd912798b60dc3f0483c46cf6a
szabgab/slides
/python/examples/lists/list.py
167
3.578125
4
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'] print(planets) print(planets[1]) print(planets[1:3]) planets.append("Death Star") print(planets)
069557318337ab4238ea4ee2b35c9fc7be5d01a3
szabgab/slides
/python/examples/classes/with_example.py
372
3.625
4
class WithClass: def __init__(self, name='default'): self.name = name def __enter__(self): print('entering the system') return self.name def __exit__(self, exc_type, exc_value, traceback): print('exiting the system') def __str__(self): return 'WithObject:'+self...
d554bce5d640c3044141a3b48ed52c6c93644754
szabgab/slides
/python/examples/regex/assembly_process_dict.py
509
3.53125
4
import sys import re if len(sys.argv) != 2: exit(f"Usage: {sys.argv[0]} FILENAME") filename = sys.argv[1] with open(filename) as fh: code = fh.read() mapping = { 'R1' : 'R2', 'R2' : 'R3', 'R3' : 'R1', } code = re.sub(r'\b(R[123])\b', lambda match: mapping[match.group(1)], code) print(code) # ...
f0234c8005fe212ee4a597bcdc446e64d3b0e85e
szabgab/slides
/python/examples/regex/quantifier_on_character_class.py
454
3.9375
4
import re strings = ( "-a-", "-b-", "-x-", "-aa-", "-ab-", "--", ) for line in strings: match = re.search(r'-[abc]-', line) if match: print(line) print('=========================') for line in strings: match = re.search(r'-[abc]+-', line) if match: print(line) ...
0bd1355cb37613613792a55a67e33be6f7e2d6bd
szabgab/slides
/python/examples/async/count_sleep_0.py
416
3.578125
4
import asyncio async def count(name): print(f"start {name}") for cnt in range(10): print(f"{name} {cnt}") await asyncio.sleep(0) async def main(): a_task = asyncio.create_task(count("A")) b_task = asyncio.create_task(count("B")) print("Before") #await asyncio.sleep(1) prin...
7a3c9204a83c74fd94d293b35cb498dcba2056b1
szabgab/slides
/python/examples/vscode/mylib.py
412
3.546875
4
import random def count(): for x in range(1000): v = random.choice("abcd") print(x) print(v) def add(x, y): return x + y def multiply(x, y): return x * y def calc(x, y, z): if z == "+": return x + y if z == "*": return x * y if z == "-": retur...
f8dff3c19234cfe628431ae2ab9fc5abe7a81c1d
szabgab/slides
/python/examples/strings/string_copy.py
183
3.671875
4
text = "abcd" print(text) # abcd text = text + "ef" print(text) # abcdef other = text print(other) # abcdef text = "xyz" print(text) # xyz print(other) # abcdef
2d5687be359d9e202ff07f779ce131bfa57d9557
szabgab/slides
/python/examples/regex/internal_variables.py
451
3.5
4
import re line = "one 123 and two 123 and oxxo 23" match = re.search(r"(.)(.)\2\1", line) if match: print(match.group(1)) # o print(match.group(2)) # x match = re.search(r"(\d\d).*\1", line) if match: print(match.group(1)) # 12 match = re.search(r"(\d\d).*\1.*\1", line) if match: print(match.group(...
5825f8126e00cb615af27c4ea753b6e757dcdc65
szabgab/slides
/python/examples/lists/sort_numbers.py
332
3.671875
4
numbers = [7, 2, -4, 19, 8] print(numbers) # [7, 2, -4, 19, 8] numbers.sort() print(numbers) # [-4, 2, 7, 8, 19] numbers.sort(reverse=True) print(numbers) # [19, 9, 7, 2, -4] numbers.sort(key=abs, reverse=True) print(numbers) # [19, 9...
80f931344f112922d7df226696fe0c3c66ec4a16
szabgab/slides
/python/examples/functions/recursive_bubble_sort.py
439
4
4
def recursive_bubble_sort(data): data = data[:] if len(data) == 1: return data last = data.pop() sorted_data = recursive_bubble_sort(data) for i in range(len(sorted_data)): if last > sorted_data[i]: sorted_data.insert(i, last) break else: sorted_d...
28da117bc78897d3d6dafbc40d65044c20e5d02e
szabgab/slides
/python/examples/multiprocess/create_text_files.py
737
3.5625
4
import sys import string import random def main(): if len(sys.argv) != 3: exit(f"Usage: {sys.argv[0]} NUMBER_OF_FILES NUMBER_OF_ROWS") number_of_files = int(sys.argv[1]) number_of_rows = int(sys.argv[2]) characters = string.ascii_letters + ' ' + string.digits # print(number_of_rows) ...
ba9463a191d343e09bcfc8c8606e1293aa81441d
szabgab/slides
/python/examples/functions/change_details_dict.py
481
4.0625
4
b = {'name' : 'Foo'} a = b # this is a copy of the *reference* only # if we change the dictionary in a, it will # change the dictionary connected to b as well print(a) # {'name' : 'Foo'} print(b) # {'name' : 'Foo'} a['name'] = 'Jar Jar' print(a) # {'name' : 'Jar Jar'} print...
5c2f86bfc34e5844b0bc117921885eb1702216ae
szabgab/slides
/python/examples/functions/reference_passed.py
393
3.71875
4
numbers = [1, 2, 3] def update(x): x[0] = 23 def change(y): y = [5, 6] return y def replace_content(z): z[:] = [7, 8] return z print(numbers) # [1, 2, 3] update(numbers) print(numbers) # [23, 2, 3] print(change(numbers)) # [5, 6] print(numbers) # [23, 2, 3] print(rep...
49c5f5d9adc62ead634311f86912dc243e4831eb
szabgab/slides
/python/examples/dictionary/count_words_in_file.py
473
3.5
4
from collections import defaultdict import sys filename = 'README' if len(sys.argv) > 1: filename = sys.argv[1] print(filename) count = defaultdict(int) with open(filename) as fh: for full_line in fh: line = full_line.rstrip('\n') line = line.lower() for word in line.split(): ...
81bb2a44b9b8b990283690c90336a291a4f4b189
szabgab/slides
/python/examples/functions/add_function.py
106
3.71875
4
def add(x, y): z = x + y return z a = add(2, 3) print(a) # 5 q = add(23, 19) print(q) # 42
cfbefc5f03b1f98c0db7cb4d06b4e0ebf1715fb5
szabgab/slides
/python/examples/basics/elif.py
265
4.03125
4
def main(): a = input("First number: ") b = input("Second number: ") if int(a) == int(b): print("They are equal") elif int(a) < int(b): print(a + " is smaller than " + b) else: print(a + " is bigger than " + b) main()
7f860f6561dbd72cddae2f56571f2a9c6669a4b8
szabgab/slides
/python/examples/lists/dna_sequencing.py
364
3.5
4
def get_sequences(dna): sequences = dna.split('X') sequences.sort(key=len, reverse=True) print(sequences) new_seq = [] for w in sequences: if len(w) > 0: new_seq.append(w) return new_seq if __name__ == '__main__': dna = 'ACCGXXCXXGTTACTGGGCXTTGT' short_sequences = ge...
168771172931707f2a2f835a988c0e9b22a10072
szabgab/slides
/python/examples/multitasking/two_loops.py
786
3.59375
4
import multitasking import time import random @multitasking.task def first(count): sleep = random.randint(1,10)/2 if count == 10: sleep = 10 print("Start First {} (sleeping for {}s)".format(count, sleep)) time.sleep(sleep) print("finish First {} (after for {}s)".format(count, sleep)) @mult...
831b6e0e26c3c199cf168429353d0f3c1853590e
szabgab/slides
/python/examples/dictionary/count_words_with_defaultdict.py
274
3.765625
4
from collections import defaultdict words = ['Wombat', 'Rhino', 'Sloth', 'Tarantula', 'Sloth', 'Rhino', 'Sloth'] counter = defaultdict(int) for word in words: counter[word] += 1 print(counter) for word in counter.keys(): print("{}:{}".format(word, counter[word]))
0f82b5635e44084f8fcaffc06b445a2b5f5375ae
szabgab/slides
/python/examples/advanced/add_numbers.py
660
3.609375
4
import timeit from functools import reduce def add_in_loop(num): total = 0 for ix in range(num+1): total += ix return total def add_with_reduce(num): total = reduce(lambda x, y: x + y, range(num+1)) return total def main(): #num = 4 #print(add_in_loop(num)) #print(add_with_re...
a0b6f7651e94cef53fde3c970ac7a67814d95ce6
szabgab/slides
/python/examples/basics/ternary.py
183
4.21875
4
x = 3 answer = 'positive' if x > 0 else 'negative or zero' print(answer) # positive x = -3 answer = 'positive' if x > 0 else 'negative or zero' print(answer) # negative or zero
4b117b856a4da7875eb014304788c90852a6489a
szabgab/slides
/python/examples/levenshtein/generate_words.py
611
3.65625
4
import sys import random import string # TODO: set min, max word length # TODO: set filename # TODO: set character types # TODO: allow spaces? def main(): filename = "words.txt" min_len = 6 max_len = 6 if len(sys.argv) != 2: exit(f"Usage: {sys.argv[0]} WORD_COUNT") count = int(sys.argv[...
e4de5f03c09e9909253cb9c01eace0a68140fe89
szabgab/slides
/python/examples/other/class.py
476
3.75
4
import re a = 2 b = "3" c = 2.3 m = re.search(r'\d', str(c)) print(a.__class__) # <type 'int'> print(b.__class__) # <type 'str'> print(c.__class__) # <type 'float'> print(type(a)) # <type 'int'> print(type(b)) # <type 'str'> print(type(c)) # <type 'float'> print(a.__class__.__name__) # int print(b._...
1db44c2f04e424840771faa51923ee6c6726f666
szabgab/slides
/python/examples/classes/person/person5.py
363
3.765625
4
from datetime import datetime class Person(): def __init__(self, years): self.age = years @property def age(self): return datetime.now().year - self.birthyear @age.setter def age(self, years): if years < 0: raise ValueError("Age cannot be negative") sel...
a26a878d119663cacf3ad70f6b43209a2f216df6
szabgab/slides
/python/examples/basics/converting_string_to_int.py
317
3.609375
4
a = "42 for life" print(a) # 42 for life print( type(a) ) # <class 'str'> b = int(a) print(b) print( type(b) ) # Traceback (most recent call last): # File "converting_string_to_int.py", line 5, in <module> # b = int(a) # ValueError: invalid literal for int() with base 10: '42 for life'
c9f8cd30a4c3388f678a433dee979b566520ddfe
szabgab/slides
/python/examples/advanced/scoping_internal_sub.py
351
3.515625
4
def external_func(): the_answer = 42 def func(args): print(args, "the_answer:", the_answer) # the_answer = 'what was the question?' # enabling this would give: # UnboundLocalError: local variable 'the_answer' # referenced before assignment func("first") fu...
df45b725607f9661155f7ee45c9ccecfd4e33871
szabgab/slides
/python/examples/regex/capture_more.py
544
3.953125
4
import re line = 'There is a phone number 12345 in this row and an age: 23' match = re.search(r'(\w+) (\w+): (\d+)', line) if match: print(match.group(0)) # an age: 23 the full match print(match.group(1)) # an the 1st group of parentheses print(match.group(2)) # age the 2nd group of p...
62b812625e2ffce10f66645e588c0a1039b9e263
szabgab/slides
/python/examples/format/print_hexa.py
148
3.65625
4
a = 42 text = "{:x}".format(a) print(text) # 2a text = "{:#x}".format(a) print(text) # 0x2a text = "{:#X}".format(a) print(text) # 0x2A
50d578ebe91b85d4ae1433a6f4e56f892be327b3
szabgab/slides
/python/examples/numpy/set_type.py
169
3.5625
4
import numpy as np a = np.array([3, 4, 7], dtype='int8') print(a) # [3 4 7] print(a * 3) # [ 9 12 21] print(a + 4) # [ 7 8 11] print(a.dtype) # int8
528a4c9f38ea697e9811ce829f1e1cba6fda34d9
szabgab/slides
/python/examples/lists/sort_tuples.py
332
3.765625
4
students = [ ('John', 'A', 2), ('John', 'B', 2), ('John', 'A', 3), ('Anne', 'B', 1), ('Anne', 'A', 2), ('Anne', 'A', 1), ] print(students) print(sorted(students)) """ [ ('Anne', 'A', 1), ('Anne', 'A', 2), ('Anne', 'B', 1), ('John', 'A', 2), ('John', 'A', 3), ('John', 'B...
dabab3d13b5912664682629aed907c8ec70237bc
szabgab/slides
/python/examples/dictionary/scores.py
421
3.859375
4
scores = { "Jane" : 30, "Joe" : 20, "George" : 30, "Hellena" : 90, } for name in scores.keys(): print(f"{name:8} {scores[name]}") print('') for name in sorted(scores.keys()): print(f"{name:8} {scores[name]}") print('') for val in sorted(scores.values()): print(f"{val:8}") print('...
bb5b93ced38876a7901d85d77d84dce4c12ad054
szabgab/slides
/python/examples/basics/without_ternary.py
218
4.375
4
x = 3 if x > 0: answer = "positive" else: answer = "negative or zero" print(answer) # positive x = -3 if x > 0: answer = "positive" else: answer = "negative or zero" print(answer) # negative or zero
69c580715071995bf0ae483e1f00039e130ec335
szabgab/slides
/python/examples/tk/tk_simple_dialog.py
993
3.84375
4
import tkinter as tk from tkinter import simpledialog def main(): app.title('Dialog') string_button = tk.Button(app, text='Ask for string', width=25, command=ask_for_string) string_button.pack() int_button = tk.Button(app, text='Ask for int', width=25, command=ask_for_int) int_button.pack() ...
5b077db7e465c646d174f6130d41e375971f8f37
szabgab/slides
/python/examples/classes/abstract.py
577
3.875
4
import abc class Port(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def num(self): pass class HTTPPort(Port): def num(self): return 80 class FTPPort(Port): def num(self): return 21 class ZorgPort(Port): def nonum(self): return 'zorg' f = FTPPort() print...
10bcdae4b5488ad60102ebe48444ca999f6370e7
szabgab/slides
/python/examples/decorators/functions_in_list.py
228
3.5625
4
def hello(name): print(f"Hello {name}") def morning(name): print(f"Good morning {name}") hello("Jane") morning("Jane") print() funcs = [hello, morning] funcs[0]("Peter") print() for func in funcs: func("Mary")
654e2c90347e351201a919df96a004765025aed2
szabgab/slides
/python/examples/advanced/enumerate.py
143
3.828125
4
names = ['Foo', 'Bar', 'Baz'] for i in range(len(names)): print(i, names[i]) print('') for i, n in enumerate(names): print(i, n)
ffed00eaf6fe920a63dd9158a28e3ed8f0e2fc97
szabgab/slides
/python/examples/generators/generator_counter_3.py
119
3.5625
4
def counter(): n = 1 yield n n += 1 yield n n += 1 yield n for c in counter(): print(c)
3f45152a1f46525a3340c9c955b074500d0ab8e8
szabgab/slides
/python/examples/advanced/function-objects.py
266
3.671875
4
c = 0 def foo(): global c c += 1 return c print(foo()) # 1 print(foo()) # 2 x = foo # assigning the function object y = foo() # assigning the return value of the function print(foo()) # 4 print(x()) # 5 print(y) # 3
a93960c56fc4ff6cecdc40227b876eab27463151
szabgab/slides
/python/examples/pandas/so_value_counts.py
402
3.515625
4
import sys import pandas as pd filename = "survey_results_public.csv" if len(sys.argv) == 2: filename = sys.argv[1] df = pd.read_csv(filename) country_count = df['Country'].value_counts() print(country_count) print(type(country_count)) # pandas.core.series.Series # We can use it either as a dictionary or as a l...
32a42d81c99b753b1a221515bbdfcc5a1c88ebd6
szabgab/slides
/python/examples/lists/master_mind.py
702
3.6875
4
import random import sys width = 4 # TODO: verify that the user gave exactly width characters def main(): hidden = list(map(str, random.sample(range(10), width))) print(f"Hidden numbers: {hidden}") while True: inp = input("Guess a number: (e.g. 1234) or x to eXit. ") if inp == 'x' or inp ...
ccded64a9ded211f70a41e86276767b1347378c6
szabgab/slides
/python/examples/oop/inheritance/shapes.py
387
3.859375
4
class Point: def __init__(self, x, y): print('__init__ of Point') self.x = x self.y = y def move(self, dx, dy): self.x += dx self.y += dy class Circle(Point): def __init__(self, x, y, r): print('__init__ of Circle') super().__init__(x, y) sel...
bfd49a24ad17ffd6d6339a3e30454c6194cc27a3
szabgab/slides
/python/examples/format/format_braces.py
159
3.59375
4
print("{{{}}}".format(42)) # {42} print("{{ {} }}".format(42)) # { 42 } print("[{}] ({})".format(42, 42)) # [42] (42) print("%{}".format(42)) # %42
e2a35be8b2eaf813b7e10bd7b1b512ec5a998e1f
yosriko/UG10_D_71210780
/3_D_71210780.py
310
4.09375
4
#daftar belanjaan db = input("Masukkan daftar belanja Anda : ") dbs= db.split() dbsc= [i.capitalize() for i in dbs] print("Daftar belanja:", dbsc) tambah = input("Masukkan barang yang ingin ditambahkan: ") if tambah in dbsc: print("Barang", tambah.upper(), "sudah berada dalam daftar belanja.")
589207b484418a04e7c2c631c07c60ccf8eaff59
puppol/cs160
/hw/hw8.py
2,415
4.0625
4
#We know there will be two possible inputs: #a string with an odd number of letters or #a string with an even number of letters #In each case, we must use a different substring #in order to get the desired results #For example, 'attta', we need to compare the middle letter #So the first substring would be 'att' and the...
f9daadc5618a673568b37c71913a0b44ce39391a
Avenger98/Python-Programms
/App1.py
181
4.03125
4
list = [] while True: num = int(input("Enter the number: ")) if num < 0: break else: list.append(num) print("This is the list created:", list)
1c2e6b76bf0d3a6b660f661608dd79f35f57b774
Avenger98/Python-Programms
/ForLoop.py
132
3.96875
4
fruits = ['Banana', 'Apple', 'Orange'] for i in range(len(fruits)): print('Current fruit: ', fruits[i]) print("Good Bye")
1bbed0c9c6a4cd918ba56093724e2c30a4d5765a
Avenger98/Python-Programms
/New5.py
665
4
4
"""def sum(a): result = 0 i = 0 while i < a: result += i i += 1 return result print(sum(10)) """ def sum(a, b): return a+ b def mult(a, b): return a * b def minus(a, b): return a - b def division(a, b): return a / b def remainder(a, b): return a % ...
8a5aeef571d925eb04f9fc9a75da4b91309d331d
Avenger98/Python-Programms
/New2.py
606
3.953125
4
'''number1 = int(input("Enter the number1: ")) number2 = int(input("Enter the second number: ")) n1 = number1 n2 = number2 while number1 % number2 != 0: r = number1 % number2 number1 = number2 number2 = r print(r) print('First number:', n1, '\nSecond number:', n2) print(n1/r, '/', n2/r)''' nu...
05ca1263297ea52e6dd71d37c24b80ba92b4a3cb
Avenger98/Python-Programms
/Lists.py
488
4.3125
4
list = ['Shoyira', 'Olimjon','Shakhina', 'Kakhramon'] list.append("John") list.remove("John") print(list) print() print(list[1]) print() print(list[-1]) print() # third one will not get executed and it is called range of indexes print(list[2:3]) # -1 is not included Kakhramon is not included print(list[-3:-...
8e0320f3fd04923a48f20b75ff636f63b2fa95e0
Avenger98/Python-Programms
/New3.py
503
3.953125
4
# word1 = input("Enter the word: ") # char = input("Enter the character: ") # adding = "" # adding1 = "abc" # adding2 = ',' # for i in word1: # if i != char: # adding += i # elif i == char: # adding += adding2 + adding1 # print(adding) word1 = input("Enter the word: ") char = input...
1f3a242aa57512e34b608913beff11fbd5f1ec0b
Avenger98/Python-Programms
/ForSum.py
148
3.84375
4
a = int(input("Enter the cycle number: ")) sum = 0 for i in range(a): sum += i print("Sum:", sum) for i in range(0, 10, 2): print(i)
93212f8f33d6a01f6111e795b13177087bf49996
relax-space/python-cy
/python_100/Level1/read_file.py
246
3.5625
4
# -*- coding: UTF-8 -*- def read_file(filepath): with open(filepath,'rb') as file: # yield (file.readlines()) for i in file: yield i a = read_file(r'D:\pythontest/test\python_100/2/base.txt') print(next(a))
e81311d1b1b074e188ef86ac978ec76cfb85b116
relax-space/python-cy
/python_100/Level1/sortdict.py
278
3.734375
4
# 现有字典 d= {'a':24,'g':52,'i':12,'k':33}请按value值进行排序? d= {'a':24,'g':52,'i':12,'k':33} print(sorted(d.items(),key=lambda x:x[1])) # 使用了sorted函数的key,使用匿名函数lambda # x[0]代表用key进行排序;x[1]代表用value进行排序。
e82c0ef03bb976cbbaa24f1061f805f3b0a1d30f
relax-space/python-cy
/python_100/Level1/32.find_even_value.py
399
3.890625
4
# 32.请写出一个函数满足以下条件 # 该函数的输入是一个仅包含数字的list,输出一个新的list,其中每一个元素要满足以下条件: # 1、该元素是偶数 # 2、该元素在原list中是在偶数的位置(index是偶数) num = [0,1,2,3,4,5,6,7,8,9,10] res = [] for i in num: if i %2 == 0 and num.index(i) %2 == 0: res.append(i) print(res)
a9202354bb7ba3ff3a0039d9be5328ff56ef1965
175ers/LikeWar
/examplePlayerList.py
594
3.609375
4
# Example of creating a list of player structs: import random def createIP (): return str(random.randint(0, 256)) + "." + str(random.randint(0, 256)) + "." + str(random.randint(0, 256)) random.seed(0) players = [] # We will have 2 teams, team 0 and team 1. The team value will intially be set to -1 before a playe...
9ed47b2819f739cfe26765a3ee83a8ad748fc864
max-cher/euler
/euler_026.py
938
3.78125
4
import datetime from time import time #import itertools print('started at:', datetime.datetime.now(), '\n') startTime = time() def timeBetween(timeStart, timeStop): sec = abs(timeStop - timeStart) min = sec//60 sec -= min*60 h = min//60 min -= h*60 days = h//24 h -= days*24 return '{0...
f7efab0485f21c361caa08fe5f482d1b3f26356b
max-cher/euler
/euler_015.py
1,378
3.90625
4
import datetime from time import time print('started at:', datetime.datetime.now(), '\n') startTime = time() def timeBetween(timeStart, timeStop): sec = abs(timeStop - timeStart) min = sec//60 sec -= min*60 h = min//60 min -= h*60 days = h//24 h -= days*24 return '{0} days, {1} hours, ...
96de593d430a4022329c1c42cafe593dbfed61f9
max-cher/euler
/euler_017.py
3,488
3.75
4
from math import sqrt; from itertools import count, islice import datetime print("started at:") print(datetime.datetime.now()) print('\n') def isPrime(n): if n < 2: return False for number in islice(count(2), int(sqrt(n)-1)): if not n%number: return False return True def letInNum(x): s = 0 l = '' if(...
a8b7a235aee8109324a0ef5ebea42dd678334de2
AngeloBrocca/exercicios-edutech-6
/Exercicios 6/main.py
863
3.5625
4
def calcula_probabilidade(pessoas): ci = (1.0/365)**pessoas for i in range((366-pessoas),366): ci *= i ci = 1-ci cii = ci * 100 p = round(cii,2) if(p == 80): print('Existem 80 por cento de chance de duas pessoas na sala fazerem aniversário no mesmo dia.') elif(p > ...
26ad715bca206d7c45055bef06bab74b9685fdb4
annaVVV/2017_Python_Interview
/Class_Inheritance.py
1,400
4.125
4
class Person(object): def __init__(self, name): self.name = name def reveal_identity(self): print "My name is {}".format(self.name) class SuperHero(Person): def __init__(self, name, hero_name): super(SuperHero, self).__init__(name) self.hero_name = hero_name def reveal_...