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
3eb7e45ceea5c0a6b7b975ba80c2d751c68cb451
Greatbar/Python_Labs
/12_6.py
470
3.703125
4
text = input() example_1 = [' * ', '* * ', '*** ', '* * ', '* * '] example_2 = ['** ', '* * ', '** ', '* * ', '** '] example_3 = [' * ', '* * ', '* ', '* * ', ' * '] for j in range(5): for i in range(len(text)): if text[i] == 'example_1': print(example_1[j], end='')...
c892c80f600b932e45a2e3575407e8bcbb7a82ef
Greatbar/Python_Labs
/27_2.py
803
3.90625
4
def image_filter(pixels, i, j): """Создает эффект сепии(делает RGB в светло-коричневых тонах, как на старых фотографиях) Чтобы получить сепию, нужно посчитать среднее значение и взять какой — нибудь коэффициент. По умолчанию установлен коэффициент - 50""" depth = 50 r = pixels[i, j][0] g =...
ea247c36740413d90383edd9c3a67c42abe586a3
Greatbar/Python_Labs
/22_1.py
641
3.78125
4
def encrypt_caesar(msg, shift=3): lowercase_char_1 = "абвгдежзийклмнопрстуфхцчшщъыьэюя" uppercase_char_1 = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" shift = shift % len(lowercase_char_1) lowercase_char_2 = lowercase_char_1[shift:] + lowercase_char_1[:shift] uppercase_char_2 = uppercase_char_1[shift:] ...
cc7d4a5df556472a56968955caa46bafbce160cb
skycakjustin/assignment-problems
/test_file.py
224
3.65625
4
number = 5 twice_the_number = 10 print('testing on number {}...'.format(number)) assert twice_the_number == 2*number, 'twice_the_number is {} whereas it should be {}'.format(twice_the_number, 2*number) print('PASSED')
16ae0a4a80bd01843615fec77d01a8160b5f25c8
AaryenMehta/CS641
/Assignments/Assignment 2/play_fair.py
2,698
3.8125
4
# Key for Play Fair Cipher # # S E C U R # I T Y A B # D F G H K # L M N O P # Q V W X Z # J is omitted similar to a standard Playfair Cipher. And I is used in place of it. import numpy as np # makes array related computations easy def Decrypt(arr): '''Decrypting Play Fair Cipher''' key = np.array([["...
621b8a23cb903e67aa71765feb8b0593a1b32583
barisceliker1/PYTHON
/global4.py
1,074
3.640625
4
a=int(input("donem başındaki koltuk sayısını giriniz")) b=int(input("dönem başındaki yatak sayısını giriniz")) c=int(input("dönem başındaki dolap sayısını giriniz")) donemsonukoltuk=25 donemsonuyatak=20 donemsonudolap=10 donemicikoltuk=10 donemiciyatak=15 donemicidolap=5 def donembasistok(a,b,c): global d...
1b757dbb426a0857f71428499b5cd264c9311358
barisceliker1/PYTHON
/modul2.py
1,310
3.625
4
a=int(input("100 kasa heasbı giriniz")) b=int(input("101 alınan çekler giriniz")) c=int(input("102 bankalar hesabına değer giriniz")) d=int(input("121 alacak senetleri hesabına değer giriniz")) e=int(input("153 Ticari mal hesabına değer giriniz")) f=int(input("252 Binalar hesabaına değer giriniz")) g=int(input("2...
d2b87aa95dc2287807b3de3596ccb73ed2e1d391
abgoswam/2016
/022016/python/leetcode_pb139_wordbreak.py
1,075
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 11:39:57 2016 @author: agoswami """ class Solution(object): def __init__(self): self.notbreakable = set() def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ ...
f4eec3bfb70385a5bcc4b4a9f5d830a33599139e
abgoswam/2016
/052016/python/args_kwargs.py
960
3.890625
4
# -*- coding: utf-8 -*- """ Created on Mon May 16 11:49:07 2016 @author: agoswami """ def doubler(f): def g(x): return 2 * f(x) return g def f1(x): return x + 1 def magic(*args, **kwargs): print "unnamed args:", args print "keyword args:", kwargs print f1(9) myg1 = doubler(f1) pri...
4f26de84b03104f0a7791e2c2b5c4882ea046c13
HarshitGupta11/HackSlash
/March_23/Python/P2.py
600
3.5625
4
#Finding Pairs - tushar pandey n_iter = int(input()) for i in range(n_iter): # iterate over test cases N = int(input()) # take input for N # take input of array and save in arr arr = [int(x) for x in input().split()] count = 0 # counter var for i, e ...
50cba13a376fc1f49bfdc1442a03eaaf6e2f5276
GuyElad/opsschool3-coding
/home-assignments/session1/exercise2-fix.py
1,775
3.765625
4
import urllib.request import requests import json def get_location_from_api(): with urllib.request.urlopen("http://ip-api.com/json") as url: data = json.loads(url.read().decode()) city = data["city"] country = data["country"] return city, country def get_weather_from_api...
2a175f1592005d47e823470b7e2ffbea4bc6f948
ksantiag/python1-75solutions
/problem08.py
394
3.765625
4
#problem8 A = [6,8,15,22,77,93,98] B = [5,15,22,44,93] def howManyInCommon(A, B): count = 0 #A.length looks like in python len(A) for i in range(len(A)): for j in range(0,len(B)): if B[j] == A[i]: count = count + 1 return count #has to be called after method/fun...
7bfdcdc24b552b7e9b1f6d5b0f924de0f7ee8eba
greggoren/textGen
/summarization/preprocees_csv_file_for_input.py
429
3.5
4
import pandas as pd import sys def read_df(fname): return pd.read_csv(fname,delimiter=",",names=["a","b","query","source","input"]) def prepare_input(df): tmp = df["input"] tmp.reset_index(drop=True) with open("input.txt",'w') as f: for row in tmp.itertuples(): f.write(row[1].repla...
7820dd82034ed5ae070b89e2becb4ebf92e65864
Sleeither1234/t0_7_huatay.chunga
/chunga/iterar_rango_07.py
257
3.71875
4
#Tabla del numero 6 import os #asignacion de valores multiplicar=int(os.sys.argv[1]) #funcion iterar for numero in range(0,16): #fin_iterar_rango print(multiplicar, "x", numero,"=",multiplicar*numero) #se imprime un comentario print("Fin del bucle")
fd5206d1acc0d585c91ee3d59fc230d2ea484785
Sleeither1234/t0_7_huatay.chunga
/huatay/iterar_rango_01.py
293
3.53125
4
#Contador del 0 al 20 import os for c in range(int(os.sys.argv[1])): #funcion iterar para poder indicar las repetiiones del valor segun el rango dado print(c) #se imprime el valor de la variable c entre el rango indicado #fin_iterar_rango print("fin del bucle")#se imprime fin del programa
774d29a39d06a26a5f1bb98e9d5547f7377d49c0
Sleeither1234/t0_7_huatay.chunga
/chunga/bucle_mientras_09.py
853
3.828125
4
# Algoritmo para solucion determinar como son las raices cuadraticas import os print("la ecuacion genereal es A**2+Bx+C") print("por favor A>0 ,ya que si no ,no seria ecuacion cuadratica si no lineal") A=int(os.sys.argv[1]) B=int(os.sys.argv[2]) C=int(os.sys.argv[3]) discriminante=B**2-4*A*C cont=0 while(A>=0 and cont<...
6117da5806f59ec549bb5da4fa9602099720bb1b
pauljensen/tigerpy
/tigerpy/parsing.py
6,024
4.0625
4
import pyparsing as pp class Expression(object): def is_empty(self): return False class Atom(Expression): """Base value in a logical expression. For a GPR, each gene is an Atom. When printed, Atoms are prefixed with a `$`. """ def __init__(self, name): self.name = n...
c2a02a4dd5731fbe7ac0cab44a763b070eb456fe
gluo7777/python-scripting
/total-ordering.py
1,171
3.828125
4
# https://docs.python.org/3/library/functools.html#functools.total_ordering from functools import total_ordering from dataclasses import dataclass import heapq @total_ordering @dataclass class Student: group: int name: str def __eq__(self, other: 'Student') -> bool: return self.group == other.grou...
5a91f9e430a2ebf94653c3c78ed5dd200291ecc1
gluo7777/python-scripting
/oop.py
655
3.625
4
class Parent(object): def __init__(self): super().__init__() self.base = "https://www.google.com" def _path(self,*paths: str) -> str: return self.base + "/" + "/".join(paths) class Child(Parent): def __init__(self): super().__init__() self.base = "https://www.ya...
1d8a5fda9e89dc5c81d825fa2e6c63251e4bec32
TudorMaxim/assignment3-4Python
/sort_utility.py
2,713
3.6875
4
''' Created on Oct 24, 2017 @author: Tudor ''' from total_expenses import calculate_expenses, calculate_expenses_by_type def get_type(my_type, V): #This method searches the type of an expense in the list V #input: my_type = the type of expense that is searched # V = the list of expenses #output...
fdc9e5dc5a169d1178cf3efa9e1f70a2f42576a1
rcoady/Programming-for-Everyone
/Class 1 - Getting Started with Python/Assignment4-6.py
982
4.375
4
# Assignment 4.6 # Write a program to prompt the user for hours and rate per hour using raw_input to # compute gross pay. Award time-and-a-half for the hourly rate for all hours worked # above 40 hours. Put the logic to do the computation of time-and-a-half in a function # called computepay() and use the function to do...
e6aebf71ce7887dbc48b05a3b49a6bf365c5677e
BreakZhu/py_recommend_demo
/sort/insertSort.py
1,214
4.03125
4
#!/usr/bin/env python # coding:utf-8 """ 插入排序: 对于一个n个数的数列: 拿出第二个数,跟第一个比较,如果第二个大,第二个就放在第一个后面,否则放在第一个前面,这样前两个数就是正确顺序了 拿出第三个数,跟第二个数比较,如果比第二个数小,就放在第二个数前面,再跟第一个数比,比第一个小就放在第一个前面,这样前三个数就是正确顺序 .... 拿出最后一个数,跟之前的正确顺序进行比较,插入到合适的位置当中。 可以理解成: 每次拿到一个数,他前面都是一个有序的数列,然后,找到我何时的位置,我插入进去 最坏时间复杂度: O(n^2) 最优...
98d6f64b98a893aeabb7a9692305f1d3d12ae2ec
PRINTHUE/PROJETO-IP
/DamasChinesas v3.1/GUI.py
3,358
3.8125
4
# -*- coding: utf-8 -*- import time def limpaTela(): print('\n'*50) def validaNumeroDeJogadores(quantidade): if quantidade.isdigit(): if int(quantidade) > 1 and int(quantidade) <= 6 and int(quantidade) != 5: return True else: return False else: return...
2267572e2dbbde16e2a1f2eb689736f2ecf0d4cb
jksparrow/NCHU-Algorithm
/Maze/test.py
361
3.640625
4
import random import math import time ''' for i in range (5): string = [] for j in range (10): string.append(random.choice(['1','2','3','4'])) print('output : ') print(string) ''' for i in range (5): string = '' for j in range (10): string += random.choice(['1','2','3','4']) ...
e94e9bba980e60c3c6bbb96ef5c221a3852e9941
Shakleen/Problem-Solving-Codes
/Hacker Rank/Language Proficiency/Python/3. Strings/13. sWAP cASE.py
276
4.125
4
def swap_case(s): L = list(s) for pos in range(len(L)): if L[pos].isalpha: L[pos] = L[pos].lower() if L[pos].isupper() else L[pos].upper() return ''.join(L) if __name__ == '__main__': s = input() result = swap_case(s) print(result)
56ca4c41d2e1934a4178fbb30bfe9b7d99c22259
Shakleen/Problem-Solving-Codes
/Hacker Rank/Language Proficiency/Python/4. Sets/30. Set.add().py
131
3.6875
4
N = int(input()) distinct = set() for i in range(N): countryName = input() distinct.add(countryName) print(len(distinct))
f3a80e2cff4435877c10cd96517a31a91d89f47f
Shakleen/Problem-Solving-Codes
/Hacker Rank/Algorithms/Grading students.py
274
3.703125
4
n = int(input()) for i in range(n): grade = int(input()) rounded_grade = grade if grade >= 38: next_multiple = ((grade // 5) + 1) * 5 if next_multiple - grade < 3: rounded_grade = next_multiple print(rounded_grade)
f556770a340c42eda6c83b0eeb89cf449415df3d
boompig/pyCatan
/catan/sprite.py
4,388
3.734375
4
''' Draws a settlement, with the ability to rescale it. Can similarly port to a city sprite, road sprite, etc. Maybe sprites would be easier than drawing everything every time... ''' ################# # IMPORTS # ################# from tkinter import ALL, Tk, Canvas from utils import CatanUtils # constants for sett...
2ea59f29cb061d98860627836b35f39aba8297f5
onaio/onadata
/onadata/libs/utils/string.py
368
3.734375
4
# -*- coding: utf-8 -*- """ String utility function str2bool - converts yes, true, t, 1 to True else returns the argument value v. """ def str2bool(v): """ String utility function str2bool - converts "yes", "true", "t", "1" to True else returns the argument value v. """ return v.lower() in ("yes",...
18cc032cb83dc9856b3b2f8a4eea9a3c3fee6cf4
3rcok/gym
/sandbox/MergeTwoArrays1.py
4,353
4.09375
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: How will you merge two sorted arrays. This is a question from Java world. # The first array has enough empty spaces to accomodate the second array. # http://www.careercup.c...
890b1a84abe1b1a19ac31184f7e13ccc3ec211a1
karanu1/Py_Project
/Up_Down_Game_Script/Up_Down_Game_Script.py
3,574
3.71875
4
import random import sys import getpass def main(): print("Game Start!\nPlease select the Mode...\n") print("=======================") print("| 1. Easy |") print("| 2. Normal |") print("| 3. Hard |") print("| 4. Hell |") print("| ...
347a8ee7721de9d6a87f3983cddd2e6392371943
Shloicker/Inkwell-Inc-Generic
/src/text_adventure/enemies.py
839
3.859375
4
import text_adventure.world as world class enemy(object): """The arguments here are as for item classes. HP is an integer. Note that enemies do not carry items but just have their own damage and armour values etc.""" def __init__(self, name, description, hp, damage, armour, block): self.name = name ...
1ebfa63c90190a82ff55abfa809d96212ac88920
Shloicker/Inkwell-Inc-Generic
/src/text_adventure/map_tiles.py
10,930
3.90625
4
import text_adventure.items as items import text_adventure.enemies as enemies import text_adventure.player as player import random import text_adventure.actions as actions import text_adventure.world as world class map_tile(object): """A generic map tile - DO NOT create an instance of this class as it only serves ...
6e452aa27c1d1caff9433517518fb210e1893c1a
tjc0090/ReciPy
/ReciPyInput.py
1,085
4.0625
4
__author__ = 'Travis' def new_recipe(): """gathers a list of ingredients for a new recipe""" ingredients_list = [] print "Let's start by entering the ingredients for the new recipe." print "When finished type the word done on any prompt." while True: ingredient = raw_input("Enter quantity...
96d77534e4f3d8dc36b880af8fbffdad35d49092
TheoryWolfe/PriceHistoryApp
/PriceHistMain.py
2,057
3.671875
4
#!/usr/bin/env python3 # MAIN SCRIPT: (PRACTICE ATTEMPT) """ I need to try and layout a mini program that allows the user to get any stocks price history data. I need a GUI, the api call to TD Ameritrade, the data returned, sort the data (using pandas df), create a database, create a table in that db for the ...
8cab36ad7fc88c5f86faf3daeb9ff2fc27b7ab85
Eleazarguitar18/Tareas-2020
/ejer3.py
173
3.828125
4
#INGRESE UN NUMERO ENTERO Y CALCULE EL CUADRADO DEL NUMERO DADO print("ingrese el numero Porfavor") num=int(input()) cuad=num**2 print("el cuadrado es") print(cuad)
11ad8445d5058af5499390fe012faf091587f7de
thydungeonsean/fairy_kingdom
/src/state/state_components/turn_tracker.py
504
3.53125
4
class TurnTracker(object): FAIRY = 0 AI = 1 def __init__(self, state): self.state = state cls = TurnTracker self.turn = cls.FAIRY def end_turn(self): self.turn = TurnTracker.AI def end_ai_turn(self): self.turn = TurnTracker.FAIRY self.state....
c546ec41038d3b9b797812d3c55043c2ad4d6de4
carmi19-meet/y2s18-python_review
/exercises/for_loops.py
105
3.578125
4
# Write your solution for 1.1 here! x = 0 for i in range(0, 101, 2): if i%2==0: x+=i print(x)
e159b9436fd380ca0fd0230a1e64bfaa9baea177
movingroot/angela_python_100day_challenge
/Leap_year_checker.py
343
4.03125
4
if year%4 == 0 : # 4로 나누어떨어지며 100으로는 나누어떨어지지 않는 경우 if year%100 != 0 : print("Leap Year") # 4로 나누어떨어지며 100으로도 나누어떨어지는 경우 else : if year%400 == 0 : print("Leap Year") else : print("Not Leap Year") else : print("Not Leap Year")
c3be60d54a88d10b85264b02689c43ffc9ec8b9e
Hr09/Python_code
/cicerciper.py
1,240
4.21875
4
message=input("Enter a message:") key=int(input("How many Charachters should we shift (1-26)")) secret_message="" for char in message: if char.isalpha(): char_code=ord(char) char_code+=key if char.isupper(): if char_code > ord('Z'): char_code-=26 ...
c94ee45b1b073378eb3ba266c46eb45996e4871b
D3MON1A/tic_tac_toe
/app.py
4,505
3.828125
4
current_player = "X" stop = False board = [ "-","-","-", "-","-","-", "-","-","-", ] count=0 def changePlayer(current): global current_player if current == "X": current_player= "0" if current == "0": current_player="X" def play(position): global current_player global c...
a090de74944fce1f6396a8dd2e79fcab0bf92ac6
jamescwalpole/gitdemo
/fibonacci.py
181
3.640625
4
from functools import cache @cache def fibonacci(n): if n==0: return 0 if n==1: return 1 return fibonacci(n-1)+fibonacci(n-2) if __name__=='__main__': print(fibonacci(20))
9f56101a49c8460bcbfcde48f2c268b2f7fd08f7
denizgenc/advent-2020
/day2.py
1,059
3.84375
4
from typing import Callable, List import adventinput def password_validator( password_list: List[str], policy: Callable[[str, str, int, int], bool] ) -> int: num_valid = 0 for line in password_list: counts, letter, password = line.split(" ") num1, num2 = [int(s) for s in counts.split("-")...
2f96899bde0d9c63d81e00a3f9936d7ad7996068
HypoChloremic/easyplot
/EasyMat.py
719
3.5625
4
"""This package will attempt to simplify the process of graphing with matplot, automating much of the process""" import matplotlib.pyplot as plt class EasyPlot: """This will attempt to simplify the process of making plots with matplotlib """ def __init__(self, *args, **kwargs): self.args = args self.kwargs...
f0962d5680b85b70b403a237c81be03c85d9c6bc
Luisarg03/Python_desktop
/Apuntes_youtube/Excepciones I.py
989
4.03125
4
#exepciones def suma(num1,num2): return num1+num2 def resta(num1,num2): return num1-num2 def multiplicacion(num1,num2): return num1*num2 def division(num1,num2): #al dividir por cero da el error zerodivisionerror, lo que hace estas lineas es omitir el error y que se siga el programa. try: return num1/num2 ...
57abcfd1f015392cec8b05af62fdf4a1ff06aa35
Luisarg03/Python_desktop
/Apuntes_youtube/operador_in.py
512
4.15625
4
print("Eleccion de asignaturas") print("Asignaturas disponibles: Bioquimica - Fisiologia - Salud mental") asignatura=input("Elige la asignatura: ") if asignatura in ("Bioquimica", "Fisiologia", "Salud mental"): print("La asignatura elegida es "+asignatura) else: print("La asignatura elegida no esta contempla...
7e3dd9e033c96905e757c41cd6d18b3a3d6c7ae4
Luisarg03/Python_desktop
/Apuntes de libros/Funciones_hipotenusa.py
479
3.84375
4
import math print("Los valores se tomaran en centimetros.") print() while True: def triangulo(cateto1,cateto2): sumacatetos=cateto1**2+cateto2**2 hipotenusa=math.sqrt(sumacatetos) print("La hipotenusa del triangulo es "+ str(hipotenusa)) print() try: triangulo( int(input("Longitud del pri...
47d304e4fad65459268ffe3aa69ca565cfeca10e
Luisarg03/Python_desktop
/Apuntes_youtube/Generadores Il.py
785
3.890625
4
# yield from #simplifica el codigo de generadores en el caso de usar bubles anidados, osea bucles dentro de otros bucles. #ej, el generador devuelve un elemento y quiero acceder a los datos de ese elemento extraido.(sub elementos). def devuelve_ciudades(*ciudades): #el asterisco adelante del argumento de la funcion ...
dd71dd304911c2bf7413d61e5323d069c9238868
Luisarg03/Python_desktop
/Apuntes_youtube/Excepciones III_ej2.py
469
3.890625
4
import math def raiz_cuadrada(num): if num<0: raise ValueError("Debe usar numeros positivos") else: return math.sqrt(num) try: op=(float(input("Ingrese un numero:"))) except ValueError as ErrorDeCaracteres: print("Debe ingresar caracteres numericos.") try: print(raiz_cuadrada(op)) except NameError as Erro...
aa8ce351d3db8bea6c40a85628811e6beac739e4
Luisarg03/Python_desktop
/Apuntes_youtube/Bucles IV_Bucle While_ej2.py
170
3.765625
4
edad=int(input("Introduce la edad: ")) while edad<5 or edad>100 : print("Edad incorrecta") edad=int(input("Introduce la edad: ")) print("Edad correcta " + str(edad))
b34263d331b98b7d2e62250b92cfaf9c1eb5e518
Luisarg03/Python_desktop
/Apuntes_youtube/concatenacion_operadores.py
727
3.953125
4
Sueldo_presidente=int(input("Ingrese el sueldo del presidente: ")) print() print("EL sueldo del presidente es de " + str(Sueldo_presidente) + " dolares") print() Sueldo_vicepresidente=int(input("Ingrese el sueldo del vicepresidente: ")) print() print("EL sueldo del vicepresidente es de " + str(Sueldo_vicepresidente) +...
381467c9ac0ae671463340dee5d4b34297918d14
Luisarg03/Python_desktop
/Apuntes_youtube/practica_lista.py
1,537
4.3125
4
lista1=["maria", "luis", "natalia", "juan", "marcos", "pepe"]#el indice empieza contar desde el cero, ej "luis" seria posicion 2 indice 1 print([lista1]) print(lista1[2])#indico que solo quiero que aparezca el indice 2 print(lista1[-1])#el menos hace que el indice se cuente de derecha a izquierda, en este caso solo ...
d965a4b55a68851be050064e17e287e36600b938
adilevin/coding-exercise
/problem-1/fit_circle.py
691
3.734375
4
""" Problem: Given set of (x,y) points in the plane, sampled in the vicinity of a circle, estimate the circle's radius and center point. How to get started: Run this script. It will read the input points and plot them. Then, add your code below (see comments). """ from utils import read_pnts, plot_points, sa...
569f081dce7fddb22821e10e5cdf553d9feb4171
Chyi341152/chyi-book
/Concurrency/race.py
937
3.65625
4
# race.py # Race Conditions 竞争线程 # A simple example of a race condition import threading import time x = 0 # A shared value COUNT = 10000000 def foo(): global x for i in range(COUNT): x += 1 def bar(): global x for i in range(COUNT): x -= 1 def timeit(method): def timed(*ar...
0f448cf0746357e030495cb62fd798aaee849e4c
Chyi341152/chyi-book
/Concurrency/lock_with.py
1,122
3.59375
4
# lock_with.py # # A simple example of using a mutex lock for critical sections. # Uses the context manager feature of Python 2.6. import threading import time x = 0 # A shared value x_lock = threading.Lock() # A lock for synchronizing access to x COUNT = 1000000 def foo(): global x ...
45a9a549feb38286b8d826526cdf45d39768bd41
Dszymczk/Practice_python_exercises
/01_character_input.py
404
3.875
4
import time; #name = input("Give me your name please: ") #age = input("Give me your age please: ") name = "Damian" age = 22 time_now = time.localtime(time.time()) message = f"Hy {name}, your are {age} now, and you'll turn 100 in {time_now[0] + 100 - int(age)}" print(message) multiply = int(input("How many t...
bc654fcbd56f777b2bb72574d434cdcbae1ea4c8
Dszymczk/Practice_python_exercises
/23_File_overlap.py
628
3.796875
4
# Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has # a list of all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000. if __name__ == "__main__": with open("23_Happy_numbers.txt", "r") as file: hap...
73b0b07826794a242dde684f94f946581c180949
Dszymczk/Practice_python_exercises
/06_string_lists.py
803
4.40625
4
# Program that checks whether a word given by user is palindrome def is_palindrome(word): return word == word[::-1] word = "kajak" # input("Give me some word please: ") reversed_word = [] for index in range(len(word) - 1, -1, -1): reversed_word.append(word[index]) palindrome = True for i in range(l...
5710605732a31641a1d86255f2e5a963845eecc4
Dszymczk/Practice_python_exercises
/26_Check_tic_tac_toe.py
742
4.0625
4
# Program checks who has won i Tic tac toe game # Matrix represents board: # [[0,1,2], # [2,1,0], # [2,1,1]] # 0 represents empty square, 1 firs player choice, 2 second player choice # # Damian # function to check the board # # board - 3x3 list def check_board(board): for player in [1, 2]: ...
10c36c7f229c577dcb6c40c26a511896da9d4dc2
Hett-XY-14/CS61A
/discussions/guerrilla_01.py
3,120
4.5625
5
# Consider an insect in an M by N grid. The insect at the bottom left corner, (0, 0), and wants to end up at the top right corner (M-1, N-1). The insect is onl capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the ...
980315e2a75e5c88537962d240e3663ef095b15f
fluency03/Andrew-Ng
/ex1/ex1-chang.py
5,237
4.09375
4
#!/usr/bin/python '''For scientific computing''' from numpy import * import scipy '''For plotting''' from matplotlib import pyplot, cm from mpl_toolkits.mplot3d import Axes3D # Path of the files PATH = '/home/cliu/Documents/github/Andrew-Ng/ex1/' # generate the matrix - Part 1 def newMatrix(): A = eye(5) print ...
6fcd96b8c44668ccac3b4150d9b6c411b325bcc0
mm/adventofcode20
/day_1.py
2,436
4.375
4
"""AoC Challenge Day 1 Find the two entries, in a list of integers, that sum to 2020 https://adventofcode.com/2020/day/1 """ def find_entries_and_multiply(in_list, target): """Finds two entries in a list of integers that sum to a given target (also an integer), and then multiply those afterwards. """ ...
568a1d1b9aae9d2689fb9b7dcad51137acca3894
git4rajesh/python-learnings
/String_to_Bytes/bytes_to_str.py
327
3.5
4
def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value # Instance of str input_str1 = 'Test1' print(type(input_str1), to_str(input_str1)) input_bytes = b'Test1' print(type(input_bytes), to_str(input_b...
1454e066904e8dd039923b045ad9638214fa7255
git4rajesh/python-learnings
/Algorithms_Data_Structures/Graphs/demo2.py
7,151
3.6875
4
class Node: def __init__(self, node_name): self.name = node_name self.adjacent_nodes = {} def __str__(self): return str(self.name) + ' adjacent: ' + str([x.name for x in self.adjacent_nodes]) def add_neighbor(self, neighbor_node, weight=0): self.adjacent_nodes[neighbor_node...
b28dd70b85411b90d19a5f3bf0de11adcf58d819
git4rajesh/python-learnings
/named_tuple/named_tuple_to_dict.py
241
3.53125
4
from collections import namedtuple Animal = namedtuple('Animal', 'name age type') animal = Animal(name="perry", age=31, type="cat") # Named tuple to Ordered Dict animal_dct = animal._asdict() print(animal_dct['age'], type(animal_dct))
7fbeafd6b9ad7c3bdc88b9f59e4171c3b2c8738f
git4rajesh/python-learnings
/AsyncIO/demo1.py
904
3.53125
4
import time import asyncio def is_prime(nr_num): status = True for dr_num in range(2, nr_num - 1): if (nr_num // dr_num == nr_num/dr_num): status = False break return status async def highest_prime_below(num): print('Highest Prime below number {}'.format(num)) ...
5dfe5599db66c72f94a671a33dbd3bbf2e4f044b
git4rajesh/python-learnings
/Inner_Classes/example1.py
452
3.578125
4
class Human: def __init__(self): self.name = 'Guido' self.head = self.Head() class Head: @classmethod def talk(cls, name): print('Name is: {}'.format(name)) return 'talking...' def print_human(self): name = 'raj' self.Head.talk(name)...
710a7dfbaa472d6ee6243c13356a37b7b0065882
git4rajesh/python-learnings
/Global_Local/non_local.py
266
4.0625
4
def outside(): msg = "Outside!" def inside(): msg = "Inside!" print(msg) inside() print(msg) outside() # When we run outside, msg has the value "Inside!" in the inside # function, but retains the old value in the outside function.
1319eeb416fd4b039aac5c9602575f1712aa8122
git4rajesh/python-learnings
/Overloading_demo/ex2.py
521
3.828125
4
class Vector: """ Demo of a class with multiple signatures for the constructor """ def __init__(self, constructor=()): self.values = list(constructor) @classmethod def from_values(cls, *args): return cls(args) @classmethod def from_vector(cls, vector): return cl...
b5e539887b828ddea2f224a4576d125219c46aa2
git4rajesh/python-learnings
/Closures/ex1.py
246
3.671875
4
def print_msg(msg): # This is the outer enclosing function def printer(): # This is the nested inner function print(msg) printer() # this is called now # We execute the function # Output: Hello print_msg("Hello")
4eb7cb4f660f14f631e961e0dde690a0e377d38d
git4rajesh/python-learnings
/AsyncIO/sync_demo.py
586
3.84375
4
import time def is_prime(number): status = True for i in range(2, number - 1): if (number // i == number / i): status = False break return status def highest_prime_below(num): print('Highest Prime below number {}'.format(num)) for i in range(num - 1, 0, -1): ...
e7134c6c1054d8848af6138678c2ee19570621a3
git4rajesh/python-learnings
/Design_Patterns/Structural/Facade/ex1.py
871
4
4
# ChangeInterface/Facade.py class A: def __init__(self, x): print('Created object A with value {}'.format(x)) class B: def __init__(self, x): print('Created object B with value {}'.format(x)) class C: def __init__(self, x): print('Created object C with value {}'.format(x)) # Ot...
7252e716f0bb533d1a612728caf027276883e0ef
git4rajesh/python-learnings
/String_format/dict_format.py
800
4.5625
5
### String Substitution with a Dictionary using Format ### dict1 = { 'no_hats': 122, 'no_mats': 42 } print('Sam had {no_hats} hats and {no_mats} mats'.format(**dict1)) ### String Substitution with a List using Format ### list1 = ['a', 'b', 'c'] my_str = 'The first element is {}'.format(list1) print(my_str) ...
761131c6cab4f6df375225e226697ea5524c4aca
git4rajesh/python-learnings
/named_tuple/named_tuple.py
243
3.703125
4
from collections import namedtuple Animal = namedtuple('AnimalDetails', 'name age type') animal = Animal(name="perry", age=31, type="cat") print(animal, type(animal)) print(animal.name) # they are backward compatible too print(animal[0])
0d8c6e0da07ee971ef77be0682b66741b654a704
Theodore-Ruth/pygameMC
/pygame/inventory.py
5,425
3.546875
4
#Code By: Theodore Ruth #Imports for game code import pygame, sys import random from pygame.locals import * #Constants DIRT = 0 GRASS = 1 WATER = 2 COAL = 3 ROCK = 4 LAVA = 5 DIAMOND = 6 TILESIZE = 20 MAPWIDTH = 30 MAPHEIGHT = 20 BLACK = (0, 0, 0) BROWN = (153, 76, 0) GREEN = (0, 255, 0) BLUE =...
cd7d0d1e99d2f5199e71e31c815d5fcc5d70a116
HazmanNaim/SIF2007-Numerical-and-Computational-Methods
/Chapter 7/Simpson Rule Integral.py
614
3.546875
4
'''' @Author HazmanNaimBinAhsan Title: Simpson Rule for Integration ''' #import necessary libraries import numpy as np import scipy.integrate as integrate #Function to integrate def f(x): return 1/(1+x**3) #Limit of the integration [x0,xn] x0 = 0 xn = 1 print("-------------------------------------"...
f2bc5a82164af293ba223f432dcab508371e78c7
pjfan/BioinformaticsAlgorithms
/009_SUBS.py
763
3.828125
4
""" Given: Two DNA strings s and t (each of length at most 1 kbp). Return: All locations of t as a substring of s. """ def subStringLocator(s, t): """Returns all locations of t as a substring of s""" substrlen = len(t) substrloc = [] for i, nuc in enumerate(s): if nuc == t[0...
e2cb3311abfaaf08ba8540fd87fd04a81bc3d353
pjfan/BioinformaticsAlgorithms
/013_REVP.py
1,874
4.03125
4
""" Given: A DNA string of length at most 1 kbp in FASTA format. Return: The position and length of every reverse palindrome in the string having length between 4 and 12. You may return these pairs in any order. """ import FASTA_Reader def findPalindromes(sequence, length): PalindromeDict = dict() ...
a588f62b4cfe58611e5693926958812fb5debb62
ravitej5226/Algorithms
/string-in-a-grid.py
5,431
3.65625
4
def print_string_in_a_grid(arr,dim,target): grid=[]; for i in range(dim[0]): start_row=i*dim[1]; end_column=start_row+dim[1]; grid.append(arr[start_row:end_column]); print grid is_match=False output=[] target_length=len(target); for i in range(0,dim[0]): ...
79618644a020eaa269bc7995d650afed3043b411
ravitej5226/Algorithms
/backspace-string-compare.py
1,312
4.15625
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. # Example 1: # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # Example 2: # Input: S = "ab##", T = "c#d#" # Output: true # Explanation: Both S and ...
dcc0b47ebecc12001c808378427390a0dc895270
ravitej5226/Algorithms
/next-larger-element.py
1,628
3.8125
4
# Given an array A [ ] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1 # Input: # The first line of input contains a single integer T denoting the number of test cases.Then T test cases...
0d1e65830ef0cb9e941341b1794040b6392a00d7
ravitej5226/Algorithms
/evaluate-postfix-expression.py
1,679
4.0625
4
# Given a postfix expression, the task is to evaluate the expression and # print the final value. # Input: # The first line of input will contains an integer T denoting the no of # test cases . Then T test cases follow. Each test case contains an # postfix expression. # Output: # For each test case, evaluate the post...
08815d5371e53a75f10ec4d2b0b9bba1747a6fa6
ravitej5226/Algorithms
/zigzag-conversion.py
1,458
4.15625
4
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) # P A H N # A P L S I I G # Y I R # And then read line by line: "PAHNAPLSIIGYIR" # Write the code that will take a string and make thi...
d7a82383482ca3c6a4f3bb88abc63955261f3051
ravitej5226/Algorithms
/longest-increasing-subsequence.py
1,069
3.78125
4
# Given an unsorted array of integers, find the length of longest increasing subsequence. # Example: # Input: [10,9,2,5,3,7,101,18] # Output: 4 # Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. # Note: # There may be more than one LIS combination, it is only necessary for...
5fa0a0ab95042208eb2bef0dc47498c34056dda6
arthuroe/codewars
/6kyu/sort_the_odd.py
2,963
4.25
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ''' import sys def sort_arr...
291d8bf0604da58d2b4db1498c3c0a8d8ad08ec7
arthuroe/codewars
/7kyu/remove_vowels.py
414
3.890625
4
def disemvowel(string): #filter function to sort out the string string = list(filter(lambda x: x not in 'aeiouAEIOU', string)) #formatting filter function output back to a string string = ''.join(string) return string ''' -----------tests----------- test.assert_equals(disemvowel("This websit...
78576dc109ab336280899a740fbc2f3797563e52
bryansilva10/CSE310-Portfolio
/Language_Module-Python/Shopping-Cart_Dictionary/cart.py
1,423
4.21875
4
#var to hold dictionary shoppingCart = {} #print interface print(""" Shopping Options ---------------- 1: Add Item 2: Remove Item 3: View Cart 0: EXIT """) #prompt user and turn into integer option = int(input("Select an option: ")) #while user doesn't exit program while opt...
a8169b238e55089776f08c7fe786644b05ba39ef
facumen/2-Parcial
/registro.py
3,395
4
4
import random titles = 'Ing. Sistemas', 'Teacher', 'Mecanico' author = 'Juan', 'Silvio', 'Frodo', 'Bush', 'El profe de AED', 'Es el mejor', 'Franco', 'Gabriela' class Trabajo: def __init__(self, numero, titulo, autor, categoria): self.numero = numero self.titulo = titulo self.auto...
9b72b3dd6d3aba0798f18f06ab37bdf0c39a339a
xu2243051/learngit
/ex30.py
858
4.125
4
#!/usr/bin/python #coding:utf-8 #================================================================ # Copyright (C) 2014 All rights reserved. # # 文件名称:ex30.py # 创 建 者:许培源 # 创建日期:2014年12月09日 # 描 述: # # 更新日志: # #================================================================ import sys reload(sys) sys.se...
544b88029eee5875de669232295cb44d4c1bdcfd
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Fundamentals/session04/search/binarysearch.py
607
3.734375
4
numbers = [19, 5, 96, 79, 6, 51, 80, 8] hi = len(numbers) lo = 0 found = False x = int(input("Nhap so:")) while hi>lo: mid = (hi+lo)//2 num = numbers[mid] if x == num: found = True print("Found") break elif x < num: hi = mid print('Left') else: lo = ...
003c035f6833a510069eb813c68590ada8157d87
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Fundamentals/session02/random_ex.py
126
3.609375
4
from random import randint x = randint(0, 100) if x<30: print("Sad") elif x<60: print("OK") else: print("Happy")
33a4cb93a8a86f16beca9d439e37733786b534e1
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Fundamentals/session03/homework/serious_2_3.py
378
3.890625
4
ship_size = [5, 7, 300, 90, 24, 50, 75] print('Hello, my name is Hiep and these are my ship sizes') print(ship_size) print() print('Now my biggest sheep has size', max(ship_size), "let's shear it") print() for i in range(len(ship_size)): if ship_size[i] == max(ship_size): ship_size[i] = 8 break p...
2333f9987677f828be15e95b93b340de00b59ca8
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Fundamentals/session03/update.py
344
3.859375
4
menu = ['com', 'kem', 'keo'] for i, item in enumerate(menu): print(i + 1, item, sep = ". ") position = int(input('Position u want to upate:')) content = input('Replace: ') menu[position-1] = content for i, item in enumerate(menu): print(i + 1, item, sep = ". ") # for i, item in enumerate(menu): # print(i...
75f071ee2a4d7b10edafd291026b9679583280fd
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Fundamentals/session06/f-math-problem/freakingmath.py
487
3.625
4
from random import * from calc import evaluate from random import randint def generate_quiz(): x = randint(0,10) y = randint(1,10) op = choice(['+', '-', '*', '/']) result = evaluate(x, y, op)+randint(-2,2) # Hint: Return [x, y, op, result] return [x, y, op, result] def check_answer(x, y, op...
8d101ebe53f6950b212b03a20cd8c0258aaeea63
AnhQuann/nguyenanhquan-fundameltal-c4e14
/Labs/calc.py
502
3.890625
4
x = int(input('Nhap x: ')) y = int(input('Nhap y: ')) while True: calc = input('Operation(+, -, *, /): ') if(calc == '+'): print('{0} + {1} = '.format(x, y), (x+y)) break elif(calc == '-'): print('{0} - {1} = '.format(x, y), (x-y)) break elif(calc == '*'): print(...
7354e64e461aba8b8de20b1629328661e26c5c9b
OrlT/university_projects
/Principles-of-programming-project/cities.py
7,622
4
4
import math import random import os import matplotlib.pyplot as plt def read_cities(file_name): """ Read in the cities from the given `file_name`, and return them as a list of four-tuples: [(state, city, latitude, longitude), ...]""" with open(file_name, 'r') as in_file: file_lines ...
df183a0d067475d79f1bdb9f8ed0409daf379b75
cupofteaandcake/CMEECourseWork
/Week2/Code/align_seqs_fasta.py
2,989
3.796875
4
#!/usr/bin/env python3 """A python script which finds the best alignment of two DNA sequences which are provided in a FASTA format""" __appname__ = 'align_seqs_fasta.py' __author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code" # These are the two sequences to ma...
3c4cb233be63715f662d6f81f76feae91e51ac85
cupofteaandcake/CMEECourseWork
/Week2/Code/lc1.py
1,787
4.375
4
#!/usr/bin/env python3 """A series of list comprehensions and loops for creating sets based on the bird data provided""" __appname__ = 'lc1.py' __author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18....
504f4e93ba765b11e5250b97721ae4cc50b43fff
chasejohnson3/Lab1-Senior-Design
/Pi_code/connect_to_database.py
634
3.5625
4
#Joshua Deutsch #Python Script to establish database connection #!/usr/bin/python # This library is required to connect to a MySQL database import MySQLdb #Set up the database connection db = MySQLdb.connect(host="34.68.18.19", user="root", passwd="dreamteam1", db="Lab1") #Set up a cursor object so you can...
d89cb35a53523651f6bec2df16f7cbae76ad7969
JasonC256/python
/Sqlite.py
1,816
3.828125
4
#!/usr/bin/python #后续务必要更改db文件存在位置 import sqlite3 def create_table(): #只创建一次表 conn = sqlite3.connect('D:/data.db') print("Opened database successfully") c = conn.cursor() c.execute('''CREATE TABLE KEYDATA (NAME TEXT , DUE TEXT);''') c.execute('''CREATE TABLE USERDATA (NAME TEXT ,...