blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
19ffc6c86b80cfe45d9bf4daaa32f08a26f67be1
jacquerie/leetcode
/leetcode/1470_shuffle_the_array.py
515
3.6875
4
# -*- coding: utf-8 -*- from typing import List class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: return [ (nums[i // 2] if i % 2 == 0 else nums[i // 2 + n]) for i in range(2 * n) ] if __name__ == "__main__": solution = Solution() assert [2, 3, 5, 4, ...
af961afa4d66fb0cc00f0bbf5dcf8ca4558e6995
johmarpc/Python_Homeworks
/Practica4.py
2,303
3.859375
4
# Practica IV: Python # 1- Modele tres entidades del mundo real, colocar por lo menos 3 características distintivas. Invoice = ("Costos ", "Ingresos ", "deudas") Account = ("Acceso ", "Informacion ", "Conatabilidad ") Customers = ("Persona ", "Comapañia ", "Organizacion ") # 2- Crear una clase llamada Estudiante con...
16606f3d18cda760153cca99839de2b709c38cac
hbcelebi/leetcode
/#67_ Add_Binary/main.py
1,156
3.8125
4
""" Created on Mon May 3 14:40:08 2021 @author: hbc """ # This is a O(N) computational complexity and O(1) space complexity solution to the problem from typing import List class Solution: def addBinary(self, a: str, b: str) -> str: num_carry = 0 str_result = [] len_a, len_b = len(a)-1, ...
05c2a2175f497ff9886707f520c2ed0584da0048
gbroiles/hashext
/mh.py
1,080
3.578125
4
#! /usr/bin/env python3 import argparse import hashlib def create_parse(): """ set up parser options """ parser = argparse.ArgumentParser(description="file hashing utility") parser.add_argument("target", help="one or more files to be hashed", nargs="+") return parser def Many_Hash(filename): """...
22a722a3f4aa9626a78de5448a07d935b219a66e
sarinac/reuters-21578-text-categorization
/src/modules/preprocessing/vectorizer.py
2,646
3.953125
4
"""Functions for generating bag of words.""" from collections import Counter import numpy as np def generate_bow(tokens_list: list, max_vocab=10000) -> dict: """Convert tokenized words into bag of words. This will be used to keep track of word count in the train data. Parameters ---------- to...
b9463c1231de0e4b87edb2966e541cb9eb2b97bc
efraesco/Python
/Reto-4.py
2,455
3.578125
4
def crear_usuarios (empleados: list): usuarios_codigo=[] usuarios_nombre=[] lista_usuarios=[] for empleado in empleados: cadena=[] usuarios_codigo.append(empleado['cod_empleado']) cadena.append(empleado['nombre1'][0]) if empleado['nombre2'] == '': ...
f936f3e3f079aa7a3cd88403d0071dca68c059b0
cristan563/practicas
/pares.py
140
3.9375
4
x = input("ingresa un numero \n") y = int(x) if (y % 2) == 0: print('el numero es par') else: print('el numero es impar')
ea5b51b5e8b30cbfc8961c7865d696e135d52437
bscalera/Illuminate
/ColorLibrary.py
1,144
3.703125
4
class Colors: #we can add more colors here def returnRGBVal(self, color): if color == 'yellow': return "225,225,0" elif color == 'red': return "225,0,0" elif color == 'lime': return "0,225,0" elif color == 'blue': return "0,0,225" elif color == 'green': return "0,128,0" elif color == 'p...
32295d3c8e89207837d108173351697ec669379c
perperperperper/realPythonTCPServer
/venv/Include/realPythonServ2.py
874
3.609375
4
#!/usr/bin/env python3 # TCP server. Will listen and receive data until client closes connection # Adapted by Per dahlstrøm import socket # Fetch the socket module HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) DataC...
9627a96bde35c0aa127290c7f204f0da081d1aae
jskd/ProgComp
/defis/0/viaud/anagram.py
1,527
3.9375
4
# Viaud # Python 2 import sys def open_file(filename): f = open(filename, 'r') return f def populate_dict(word, dictionary): for char in word: # On pourrait utiliser une ternaire ici mais je laisse volontairement # comme ca pour la lisibilite ! if char in dictionary: d...
6b0e1adb8df74dc432fab96cdcf43af67a20fa61
claraj/ProgrammingLogic1150Examples
/3_if_statements/quiz_3.py
493
4.4375
4
""" Quiz program, version 3. This prints a message if the user gets the answer right or wrong. It also converts the user's answer to lowercase and compares it to the lowercase version of the right answer, so the user can answer in any case, Madison and MADISON and madison are all right. """ print('Quiz program!') a...
6c5975fe77b1403ac53b1e7b7b9f8324b2678821
lw2000017/ibuy_test
/没事练习/test_1_水仙花.py
1,076
3.796875
4
# -*- coding:utf-8 -*- # @Time :2019/5/15 11:28 # @Author :LW # @File :test_1_水仙花.py def narcissistic_number_1(num): length = len(str(num)) count = length num_sum = 0 while count: num_sum += ((num // 10 ** (count - 1)) % 10) ** length ...
217d306748ae4982f8804a3c1a4d9e18bbb7b2ee
ChastityAM/Python
/Python-sys/simpleCalculator.py
443
4.09375
4
#This will take input from the user a = int(input("Please enter a number: ")) b = int(input("Please enter another number. NOT ZERO: ")) #This will add def add(a, b): sum = a + b return sum #This will subtract def sub(a, b): dif = a - b return dif sum = add(a, b) dif = sub(a, b) #This will print ...
0e93f1733b79e7a4d545c36a3c9e303711b9fef8
RiddhiDamani/Python
/Ch9/immutable_start.py
613
4.3125
4
# Python Object Oriented Programming by Joe Marini course example # Creating immutable data classes - data cannot be changed from dataclasses import dataclass @dataclass(frozen=True) # TODO: "The "frozen" parameter makes the class immutable class ImmutableClass: value1: str = "Value 1" value2: int = 0 ...
7f61454d02531685fa0c9881b884a46ec67aba4a
janFrancoo/Project-Euler
/problem21/p21.py
611
3.5625
4
import math def sum_of_divisors(number): total = 1 for i in range(2, int(math.sqrt(number)) + 1): if number % i == 0: total += i + (number//i) return total def amicable_numbers(limit): result = 0 number_list = [sum_of_divisors(i) for i in range(limit + 1)] for i in range(...
df56894482226dab4bd705a918383082359c33eb
MickysxD/EDD_1S2019_P1_201700543
/Pila/Pila.py
668
3.546875
4
class Pila(): def __init__ (self): self.cima = None self.contador = 0 def push(self, comida): snack = comida if (self.cima == None): self.cima = snack self.contador += 1 else: snack.abajo = self.cima self.cima = snack ...
599966911ef42c9f62bfe461ad8be0dd99a89d3d
itzelot/CYPItzelOT
/libro/ejemplo1_14.py
173
3.96875
4
NUM = int(input("Ingresa un número entero positivo:")) CUA = NUM * NUM CUB = NUM ** 3 print(f"El cuadrado del número {NUM} es {CUA} y el cubo del número {NUM} es {CUB}")
e87d6005e1e1b8df1409c7ce36b49b922c5c22a2
itsuttida/Python
/for2.py
132
4.0625
4
count = int(input("ใส่จำนวนรอบ : ")) for i in range(10 , count ,-3) : print("รอบที่ : ", i)
0cbd2216035ac628638863adc8c72b5b60d2d642
lucianhaj/CS362_HW4
/Volume.py
766
3.90625
4
def volume(l, w, h): try: x = float(l) * float(w) * float(h) except FloatingPointError: return "error with your input(s) type" except ArithmeticError: return "invalid input(s) type" except ValueError: return "One of inputs was not a float" except SyntaxError: ...
4d64bb801d175aaab673e1cb1b21acee390ad87e
alex-ta/Fontinator
/DataGenerator/libs/WordDict.py
1,616
4.1875
4
import random as rand class WordDict: """ Allows creating a random sentence. """ def __init__(self, word_dict: list): """ Creates an WordDict object from a list of words. which will be used as random word source :param word_dict: A list of words """ self...
7c9475b68de9fba85e73edf8471b752db11aa8b3
scottherold/python_refresher_8
/createDB/checkdb.py
415
4.09375
4
# quick check for the contacts table import sqlite3 conn = sqlite3.connect("contacts.sqlite") # user input user_name = input("Please enter your name ") # example of passing a single argument to a tuple; you must include the # trailing comma, or it will turn the single value provided into a tuple for row in conn.exec...
17e6bf662cfd7977b77c494df70ca83605351c76
atulmkamble/100DaysOfCode
/Day 34 - Quizzler Game/ui.py
2,396
3.671875
4
""" This file implements the QuizInterface class for UI of Quizzler game """ import tkinter as tk from quiz_brain import QuizBrain THEME_COLOR = "#375362" class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = tk.Tk() self.window.title('Quizz...
0ada5c86b51baee59c887739970529db4cf19a14
sealanguage/pythonExercisesDataSci
/nested_loops.py
112
3.734375
4
for number in range(1, 11) : print(" ") for count in range(0, number) : print(number, end = " ")
365a3b8eb04eaaf4957ab01509b8e359daba52e8
Fendo5242/semana-7
/Nueva carpeta/5.py
177
3.609375
4
a=0 b=1 n = int(input("Ingrese el límite: ")) suma=0 for number in range (1,n ,1) : c=a+b a=b b=c print(b) suma += b print("La suma es :", suma)
d26b7c70f3dc60a7283fe04e2acf8cfa7714234e
Jin-SukKim/Algorithm
/Problem_Solving/leetcode/linear_data_structure/Arrangement/42_Trapping_Rain_Winter/rain_drop_v2.py
955
3.5
4
# stack을 활용한 풀이 def trap(self, height: List[int]) -> int: stack = [] volume = 0 for i in range(len(height)): # 현재 높이가 이전 높이보다 높을 떄, # 즉 꺽이는 부분 변곡점(Inflection Point)을 기준으로 # 격차만큼 물 높이(volume)를 채운다. while stack and height [i] > height[[stack[-1]]]: # 변곡점을 만나면 ...
a0277106e43dd6d5d0015b408922bc595628f5a3
greatabel/PythonRepository
/04Python workbook/ch4function/82taxifare.py
234
3.9375
4
import math def fare(distance): return 0.25 * (distance/140) + 4 line = input("Enter distance:(km):") while line != "": distance = float(line) print('distance fare=%0.2f' % fare(distance*1000)) line = input("Enter distance:")
4368b11a93f1807e7a8bc7614acb699351c5cbf8
asymmetry/leetcode
/0038_count_and_say/solution_1.py
715
3.625
4
#!/usr/bin/env python3 class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ if n == 1: return '1' if n == 2: return '11' s = self.countAndSay(n - 1) result = '' count = 1 old_char = s...
5630f1fdcfcc11190aeee693715672fd087b24ac
Toufikkk/tpPython
/JOUR3/Forme1.py
567
3.640625
4
#TP geometrie class Form: def __init__(self, x,y): self.x = x self.y = y def calculer_distance(self): print('je calcule la distance') def calculer_perimetre(self): print('je calcule le calculer_perimetre') def afficher(self): print('je calcule le perimètre') class Rectangle(Form): def __init__(self...
cacc60c4dbd036a6009893e4b55ed0c0286c1612
samikshasadana/python_codes
/16aug.py
402
3.53125
4
'''f=open("rk.txt",'w') f.write("hi rishi \n") print('\n') f=open("rk.txt",'a') f.write(" by rishi for you \n" ) f=open("rk.txt",'r') print(f.read()) f=open("rk.txt",'r') print(f.read(5)) print(f.readline()) f=open("rk.txt",'a') f.write(" by rishi for you agin \n at your service \n" )''' f=open(...
e0df7563acbe458a927dd8ddbf063d1c6ec085ed
panwarsandeep/LC
/lc_1190_rev_substr_bw_each_parenthesis.py
1,227
3.71875
4
from collections import defaultdict class Solution: ''' The idea is if the string is at even index (assuming index starting from 0), in the final output it'll be reversed else not. keep this in mind while appending the string (i.e. reverse or regular order) once encounter ')', append this string to ...
dd9a86f9328c5cde9a5b2c10e321730c1dc6e1b6
MehradShahmiri/Python-class
/Ex6_ 050 Mehrad Shahmiri.py
243
3.953125
4
s=int(input('enter number betwenn 10 and 20: ')) while s<10 or s>20: if s<10: print('Too low') s=int(input('try again: ')) else: print('Too high') s=int(input('try again: ')) print('Thank you')
152429cb954da8eba410b4cab83ad1d148c9f9b9
jedzej/tietopythontraining-basic
/students/grzegorz_kowalik/lesson_02_flow_control/knight_move.py
284
3.890625
4
begin_row = int(input()) begin_col = int(input()) target_row = int(input()) target_col = int(input()) d_rows = abs(begin_row - target_row) d_cols = abs(begin_col - target_col) if (d_cols == 2 and d_rows == 1) or (d_rows == 2 and d_cols == 1): print("YES") else: print("NO")
f666c74c83483ba3e51e46e07713082abc9e881b
ChrisClear/Coding_Dojo_Coursework
/Python/Python_Fundamentals/Fund_Completed/funwithfunctions.py
2,132
4.40625
4
""" Fun with functions project by: Troy Center troycenter1@gmail.com Assignment: Fun with Functions Create a series of functions based on the below descriptions. Odd/Even: Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and spec...
d3b16d607ac116a36f8f2d59ddbb4b45c5d624ed
myousufkhan360/Python-basic
/python basics/part 2/l2-t3.py
312
3.96875
4
list_name = ["Huma" , "Hina" , "Alina" , "Serat"] print("Hello "+str(list_name[0])+" You are invited to a Dinner") print("Hello "+str(list_name[1])+" You are invited to a Dinner") print("Hello "+str(list_name[2])+" You are invited to a Dinner") print("Hello "+str(list_name[3])+" You are invited to a Dinner")
90f2ca3dea8371168cfa10ca322dac0e5f03670e
RumorsHackerSchool/PythonChallengesSolutions
/Guy/edX/MITx:6.00.1xIntroductionToComputerScienceAndProgrammingUsingPython/vara varb.py
213
3.78125
4
None varA = 'asd' varB = 10 if type(varA)==str or type(varB)==str: print ("string involved") elif varA > varB: print("bigger") elif varA == varB: print("equal") elif varA < varB: print ("smaller")
fffbbf1a79b9c8f069d523813a579bd846d2e6af
realpython/materials
/python-doctest/calculations/calculations.py
1,092
4.28125
4
"""Provide several sample math calculations. This module allows the user to make mathematical calculations. Module-level tests: >>> add(2, 4) 6.0 >>> subtract(5, 3) 2.0 >>> multiply(2.0, 4.0) 8.0 >>> divide(4.0, 2) 2.0 """ def add(a, b): """Compute and return the sum of two numbers. Tests for add(): >>...
0b29bd1054aefc1d101a5ec43f395c2f38ac3a98
everdein/CS320-Programming-Languages
/Python/Assignment3/grammar_generator.py
1,606
4.0625
4
# This class is a grammar generator. class GrammarGenerator: # Asks the user what file to read. @staticmethod def get_file_name(): print("What is the file name?") # file_name = input() file_name = "simple.txt" # file_name = "sentence.txt" g.read_file(file_name) ...
9636226e7a2ee985b4572001aa1245aae1262d48
yhx52385/leetcode-in-home
/part2-linkedList/19-remove-nth-node-from-end-of-list.py
849
3.875
4
# @Time : 2021/5/1 9:35 # @Author : yhx52385 # @Email : yhx52385@163.com # @File : 19-remove-nth-node-from-end-of-list.py # @software: PyCharm # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def ...
de4636ff8cafcc6bffdb0b6e3eb5348fa7b4af88
sandeepshiven/python-practice
/object oriented programming/oops2/deck2.py
2,038
3.90625
4
import random class Card(): def __init__(self,suit,value): self.suit = suit self.value = value def __repr__(self): return f"{self.value} of {self.suit}" def __str__(self): return f"{self.value} of {self.suit}" class Deck(): suits = ["Hearts","Diamonds","Clubs","...
3c4cb6f630a5b768e70261dcfa7760b387af2b76
EscapeB/LeetCode
/Longest Substring Without Repeating Characters.py
1,748
3.8125
4
# Given a string, find the length of the longest substring without repeating characters. # # Example 1: # # Input: "abcabcbb" # Output: 3 # Explanation: The answer is "abc", with the length of 3. # Example 2: # # Input: "bbbbb" # Output: 1 # Explanation: The answer is "b", with the length of 1. # Example 3: # # Input: ...
21a60dcd1d55a7a940cddff4065cd10da724257f
cptn3m0grv/Python-Hackerrank
/Itertools/itertools-combinations-with-replacement.py
190
3.515625
4
# itertools-combinations-with-replacement from itertools import combinations_with_replacement as cwr word, size = input().split() for i in cwr(sorted(word), int(size)): print(''.join(i))
84541c4b976c37721060b76ac2acf32dc5f3e8d7
PdxCodeGuild/class_crow
/Code/jesse_pena/labs/lab_25.py
3,138
4.09375
4
class ATM(object): def __init__(self, name = '', balance = 0, transaction_list = []): self.name = name self.balance = balance self.transaction_list = [] def check_balance(self, name): return self.balance def deposit(self, deposit_amount): self.balance += de...
28ebf7b8953288ca3dae13e9994605d1402c6cbf
soroush-mim/AUT_Pattern_Recognition
/4/code/P3/c.py
2,345
3.515625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def pca(data , n_component): """performs PCA on a given dataset and return reduced data Args: data (m*n numpy array): [m samples that each has n faetures] n_component ([int]): [num of pca components to keep] Returns: ...
5da2fe9919ab118e4988dd958429def6cac58d4b
inka000/projet_python
/bin/distance_calculation.py
492
3.671875
4
'''distance_calculation module distance_calculation module allows to calculate distance between two Atomes instances ''' #!/usr/bin/python3 from math import sqrt from pdb_reader import * from classes import * def distance(atom1, atom2): ''' Calculates and returns the distance between two Atome instances ba...
4a73915049c20e93743dc8a9cc2054d230d11477
thesinbio/RepoUNLa
/Seminario de Lenguajes/Práctica/01.programarcadegames/Práctica20 Bucles avanzado.py
1,373
4
4
# Triángulo de números x = 10 y = 11 for i in range(y): for k in range(x-i,0,-1): print(" ", end=" ") for j in range(1,i): print(j, end=" ") for k in range(i-2,0,-1): print(k, end=" ") print("") print("") # Triángulo de números x = 10 y = 10 for i in range(y): for k in r...
b45279d03fcb4920113bad0cc4743db01790700e
Smithmichaeltodd/Learning-Python
/Chaos.py
397
4.03125
4
def main(): loop = 'True' while True: print("Welcome to the chaos program\n") x = eval(input("Please chose a number between 0 and 1: ")) y = eval(input("Please chose a 2nd number between 0 and 1: ")) n = eval(input("Please chose a number of iterations: ")) for i in range (n): ...
ef3709eb86293abbf78f3a775f8da3fb800805f5
Andchenn/Lshi
/day03/bud.py
261
3.78125
4
# 定义不定长位置参数 def show_msg(*args): print(args) # 定义不定长位置参数 def show(*args): # print(args, type(args)) print(args) # 解决办法:对元组进行拆包 show_msg(*args) # show_msg(args) show(1, 2)
03f31c352bf45e7bebd8ddfbac460a6f56e8f3f6
KULDEEPMALIKM41/Practices
/Python/Python Basics/9.typecompatibility.py
441
3.78125
4
#Type compatibility =>we are check compatibility on two or more different different # data type. if datatype is compatible so code is execute successfully. # but data type is not compatible than code is generate Error. a='hello' #string b='world' #string c=a+b #execute print(c) #p...
ab538571fb089d83a89d4c069885b14f44cf4d5f
skollr34p3r/UdemyCourses
/Python3_Bootcamp/Loops/rpsv3.py
4,744
4.34375
4
# This is the third iteration of the automated version of RPS where a user battles a "computer" # opponent in a game. I added looping to allow a best x out of x approach. The variable winning_score # determines the amount of wins necessary by the computer or player to exit the program from random import randint g...
d4a7adabdadd3e793a38ec7b37afb3932d2d4556
james-sorrell/spr
/src/GameController.py
3,905
3.640625
4
import threading import time import config as c class GameController(): """ Game Controller Class This class controls the game logic, it is passed in the ui controller through it's constructor and uses it to interface with the ui. """ def __init__(self, uic): # UI Cont...
45256313555c47de3f12f261b53d1b45fff13396
llv22/pyalgorithm
/03_linkedlist/Intersection_Two_Linked_Lists.py
3,590
3.734375
4
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.3' # jupytext_version: 0.8.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # lang...
2cad28b71f6b4f1588618831923c9b58f621cd75
homg93/PS
/workbook Edition pt.1/2902.py
134
3.6875
4
name = input() len_name = len(name) for i in range(len_name): if ord(name[i]) >= 65 and ord(name[i]) <= 90: print(name[i],end='')
091f8ce5ddbdf9e319ac87502ec7ed6b3599165d
Kyeongrok/python_algorithm
/etc/geeks_of_geek/02_easy/02_string_after_backspace.py
193
3.546875
4
str = "###abc#de#f#ghi#jklmn#op#" result = [] for chr in str: if chr == "#": if len(result) != 0: result.pop() else: result.append(chr) print(result) print(result)
ca96a1c1f7373009bec11f2abab75c54bc7a70f5
nilsso/challenge-solutions
/euler/python/02/02-v02.py
452
3.625
4
# Number 2, v2 # Prompt: By considering the terms in the Fibonacci sequence whose values do # not exceed four million, find the sum of the even-valued terms. from math import sqrt phi = (1+sqrt(5))/2 evenPhi = 2*phi+1 # = phi**3 def evenFib(lim): n = 2 while n < lim: yield n n = round(n *...
e1e1cc59cdee48765f8e5f2308f881bdd0c5e06a
joshuap233/algorithms
/leetcode/hot100/581.py
2,053
3.6875
4
# https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/ # 581. 最短无序连续子数组 from typing import List class Solution: """ 进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗? 思路: 很明显是双指针 设置双指针 left,right 例子: [2, 6, 4, 8, 10, 9, 15] 6, 4, 8, 10, 9 6 之前...
263ac07627d71f95773efa9b82ab129592bf161a
ItsMrTurtle/PythonChris
/Unit 8 Libraries/Lesson36 GUI Random Color Button.py
839
4.03125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 1 15:57:28 2020 @author: Christopher Cheng """ import tkinter import random def changeColors(): r = random.random() if r < 1/3: window.configure(background = "red") window.update() elif 1/3 <= r < 2/3: window.configure(background = "...
d5e6e9cc5e0c6af95f45b57b1655066f99efb887
Miguelpellegrino/Test
/drops.py
920
3.890625
4
def retornos(retornos): # print para observar los valores return print(retornos) def plic_plac_ploc(numero): if type(numero) == int: #Cree un diccionario para trabajar por Clave Valor gotas = {3:'Plic', 5:'Plac', 7:'Ploc'} #Cree un mensaje que por defecto esta vacicio mensaj...
07b6e218ad64d813c3093547268a3f2258a6079b
jfriend08/LeetCode
/LowestCommonAncestorofaBinaryTree.py
1,900
3.765625
4
''' My Submissions Question Solution Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow ...
56c43655bc93c236f8b07d6439257717f6269f83
FelixOnduru1/100-Days-of-Code
/Day63/library-start/main.py
2,461
3.5
4
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy # import sqlite3 app = Flask(__name__) # Creates a new database called books-collection # db = sqlite3.connect("books-collection.db") # Creates a cursor that modifies the database # cursor = db.cursor() # ...
dc2b6655b0bd62cd140c34f9adc554ac5d2ca732
Shwaubh/HackerrankSolutions
/easy/string/Mars Exploration.py
327
3.578125
4
import textwrap as t def num_change(s): if s=='SOS': return 0 else: x = 0 if s[0]!='S': x+=1 if s[1]!='O': x+=1 if s[2]!='S': x+=1 return x s = t.wrap(input(),3) x = 0 for i in s: x = x + num_change(i) p...
9d07e49e52bcdc31d5fd67def815154300ebd795
zhengjiani/pyAlgorithm
/leetcodeDay/April/prac1111.py
1,103
3.8125
4
# -*- encoding: utf-8 -*- """ @File : prac1111.py @Time : 2020/4/1 9:35 上午 @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm 划分出最大嵌套深度最小的分组 """ class Solution: """用抽象栈进行括号匹配,奇偶分组""" def maxDepthAfterSplit(self, seq): ans = [] d = 0 for c in seq: if c ...
f772a60f1eb382a7f9b9309416d8b2e7151835f4
sunnysoni97/csv_parser_py
/csv_parser.py
3,139
3.5
4
import os def print_line(): sz = os.get_terminal_size()[0] for i in range(sz): print('-',end='') print('') def ret_metrics(data, attr): cols = len(attr) rows = len(data) return (cols,rows) def check_validity(data,cols,rows): flag = True for i in range(rows): colt = len(data[i]) if(colt!=cols): flag ...
14e47c497589264cb3e6dea8b9a655c03d66fbe6
bitnahian/info1110_s2_2019
/week03/odds_reversed.py
165
3.65625
4
i = 100 # Initialise your counter while i > 0: # Set proper while condition if i % 2 == 1: # Do something print(i) i -= 1 # Decrement your counter
f78ca56001c44dc0fbb39b024c552d0498b56463
GraydonHall42/Python-For-Data-Scientists-University-of-Calgary-ENSF-592
/assignment-3-encryption-GraydonHall42/encryption.py
2,760
4.25
4
# encryption.py # Graydon Hall # # A terminal-based encryption application capable of both encoding and decoding text when given a specific cipher. # Detailed specifications are provided via the Assignment 3 git repository. # You must include the main listed below. You may add your own additional classes, functions, va...
b58b607eba9c73a053d315f906e33063af0154ad
zeppertrek/my-python-sandpit
/python-training-courses/pfc-sample-programs/func_example_001_a_with_its_use.py
537
3.75
4
# func_example_001_a_with_its_use.py # Please refer to func_example_001_without_its_use.py # # Use def to create a function # # Note - This function does not return any value # Three arguments/parameters are being passed from the calling program to this function def printthreelines (firstlinechar, middleli...
2e88a8de3b8367bdf669bac54c2c56a994955605
PrtagonistOne/Beetroot_Academy
/lesson_28/task_1.py
823
4.15625
4
""" Task 1 Implement binary search using recursion. """ from typing import Iterable, Union def search(seq: Iterable[Union[int, str]], item: Union[int, str]) -> int: """Return index of the item if present, otherwise returns -1""" def binary_search(sequence, start, stop): if stop >= start: ...
21eb58e90c6f28a9dc765364646fdb424e4db278
monalan/myGitProject
/tryforPython/hello_world.py
547
3.78125
4
message="Hello python world!" print(message) message = "hello python crash course world!" print(message.title()) class Dog(): def __init__(self,name,age): self.name = name self.age = age def Squat(self): print(self.name + ": hello") my_dog = Dog('lucy',1111) print("name:",my_dog.n...
4429414286493652206bbad544bcae05b5c4faf0
MarceloVasselai/pythonDesafios
/Ex020.py
351
3.734375
4
from random import shuffle aluno1 = str(input ('Informe o nome do aluno 1: ')) aluno2 = str(input ('Informe o nome do aluno 2: ')) aluno3 = str(input ('Informe o nome do aluno 3: ')) aluno4 = str(input ('Informe o nome do aluno 4: ')) alunos = [aluno1,aluno2,aluno3,aluno4] shuffle(alunos) print ('A nova ordem de apre...
2e1c4239a32807810638df01132dff3404d2d74b
AndyLee0310/108-1_Programming
/HW002.py
665
3.625
4
""" 一元二次方程式 一元二次方程式,aX^2 + bx + c = 0,輸入a, b, c, 求 方程式的兩個實根。 --------------- 輸入說明 第一個數(int) a 第二個數(int) b 第三個數(int) c --------------- 輸出說明 第一個實根 x1 = ((-b)+sqrt(b*b-4*a*c))/(2*a) 第二個實根 x2 = ((-b)-sqrt(b*b-4*a*c))/(2*a) x1, x2 輸出到小數點第一位 print("%.1f" %x1); --------------- Input 1 -2 1 Out...
36bfbf77dbe9192161412c46b262cfae7e0c044c
justinzuo/myp
/day1/myrandom.py
1,121
4
4
import random # random.choice()随机选取参数中的子元素 if __name__ == '__main__': mstr = "abcdefghijklmn" # 临时存储 tstr = "" #循环六次,取出六个字符 for i in range(6) : v = random.choice(mstr) #拼接成字符串 tstr+= v print(tstr) random.shuffle将传入的参数的子元素随机打乱位置 if __name__ == '__main__': #创建一个列表 ...
08af2fb7db6c809de13734929af5f4c452e0e612
youngvoice/myLeetcode_python
/calculate.py
12,924
3.5625
4
# 227. Basic calculate II ''' class Solution: def calculate(self, s: str) -> int: slist = self.get_legal_list(s) pass # remove whitespace and composite multible bit number def get_legal_list(self, s): ret = [] temp = "" for c in s: if c == " ": ...
68a19592105b3349f1f231046775131b2c0431ad
TolgaGolet/Random_LSB_Steganography
/RandomLSB.py
5,305
3.734375
4
import binascii, cv2 import numpy as np import sewar from matplotlib import pyplot as plt import random def convertStringToBinary(string): return bin(int.from_bytes(string.encode(), 'big')) def convertBinaryToString(binary): n = int(binary, 2) return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode() ...
e4255295a354bfd8222b0a9f25ea4a9bec42b9a7
pauljs/HotColdData
/replacementAlgorithms.py
9,197
3.828125
4
'''LRUQueue.py''' from Queue import PriorityQueue from Queue import Queue import time import calendar from abc import ABCMeta import random '''class for least recently used algorithm''' class ReplacementQueue(object): ''' Checks whether the ReplacementQueue is full. Returns True if it is full and false ot...
719fb0755cda5056b5a8342b93b244a49f95985d
tonper19/PythonDemos
/basic/infinite_loop.py
199
4.15625
4
name = '' # while name != 'Toffee': # name = input('Enter a name: ') for numero in range(1,10): print(numero) numero = 0 while numero < 10: print(numero) numero = numero + 1
f1a94721f6ac3894efc667461130e8ae55c1e59b
diegodpgs/ViajandoEmBytes
/Perceptron/perceptron.py
2,160
3.546875
4
import math class Perceptron: """ DATA FORMAT data = [[xa1,xa2,xa3,xa4...xan,ay], [xb1,xb2,xb3,xb4...xbn,by], . . . [xz1,xz2,xz3,xz4...xzn,zy]] where xn is a feature and y is the target expected. Both have to be numeric. """ def __init__(self,data): self.data ...
889988d941927bc0cd15d1c9fac04677956ed854
askdjango/snu-web-2016-09
/class-20160928/report/정동휘_식품생명공학과/googoodan.py
263
3.765625
4
number = int(input("구구단: ")) if number < 10 and 1 < number: for i in range(1,10): result = number*i print('{a} * {b} = {c}'.format(a=str(number), b=str(i), c=str(result))) else: print("구구단은 2부터 9까지입니다 :)")
7057c2c487b8f8c0f3684a6e90f05a023f8ddcae
dgonzalo05/M5.Pt2
/M5.Pt2/P11_cerca1caracter.py
379
4.09375
4
# encoding: utf-8 # Programa que cerca si un caràcter es troba a o no (a una frase) i el mostra per pantalla. st = raw_input("Escriu alguna cosa: ") put = raw_input("Escriu un caràcter: ") con = 0 while con < len(st): if put == st[con]: result = "El caràcter '"+put+"' apareix a "+st break else: result = "El car...
d4e9f804d27a719ae37470d82a6411024003626f
MashuAjmera/Algorithms
/hamiltonian.py
1,044
3.765625
4
# Problem: Hamiltonian Cycle # Author: Mashu Ajmera # Approach: Backtracking # Time Complexity: # Space Complexity: # GFG: https://www.geeksforgeeks.org/hamiltonian-cycle-backtracking-6/ def check(s,g,n,vis): ans=0 for i in range(1,n): if vis[i]==-1: ans+=1 if g[s][i]==1: ...
650211ab1eada678de322b0ccc1521bd856fea52
kaci65/Nichola_Lacey_Python_By_Example_BOOK
/Numeric_Arrays/num_range.py
367
4.21875
4
#!/usr/bin/python3 """Array: numbers must be between 10 and 20""" from array import * numArray = array('i', []) for i in range(0, 5): num = int(input("Please enter a number between 10 and 20: ")) if num >= 10 and num <= 20: numArray.append(num) else: print("Outside the range") print() prin...
bc0fc63d25c493630368859093d129f523e88418
Yousef497/Python-for-Everbody-Specialization
/Course_2 (Python Data Structures)/Chapter_9/Exercise_9_04.py
545
3.734375
4
fname = input("Enter file name: ") try: fhand = open(fname) except: print("File cannot be found:",fname) quit() counts = dict() for line in fhand: line.rstrip() if line.startswith("From "): if len(line) < 1: continue words = line.split() counts[...
c2478945f23be1aa190f5c73bc10259f6b922b5e
Eason13245/AE401-Python-
/2020. 6. 2 回家作業.py
361
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 2 21:03:53 2020 @author: gaoyixun """ import turtle Ray = turtle.Turtle() Ray.color('blue') Ray.shape('turtle') canvas = turtle.Screen() canvas.title('Turtle window') canvas.bgcolor('white') for x in range(0,60,2): Ray.forward(x) Ray.lef...
ea6951d9a926a86230c5f9f283d0ad796f0be401
MrBenjaminLeb/viirs-data
/src/eumetsat/common/geo_utils.py
1,070
4.03125
4
# -*- coding: utf-8 -*- ''' Created on Feb 9, 2011 @author: guillaume.aubert@eumetsat.int ''' import math def deg_to_rad(val): """ convert degree values in radians """ return (val * math.pi)/180.00 def rad_to_deg(value): """ convert radians to degrees """ (value * 180.00)/ math.pi def distance(lat1,...
1e8b04c3607c17ccb13e28b1090e222ff3bb8b7f
anassinator/ecse543
/as1/rectangle.py
1,852
3.859375
4
class Rectangle(object): def __init__(self, width, height, bottom_left_x, bottom_left_y): self._width = float(width) self._height = float(height) self._center_x = float(bottom_left_x) + width / 2.0 self._center_y = float(bottom_left_y) + height / 2.0 self._top = bottom_lef...
7687550be9be737e0f60c7501669a60a455c8791
matthewlootens/sort_search_algorithms
/merge_sort.py
2,144
4.1875
4
def mergesort(input_list): """ input_list: a list of any n integers, duplicates allowed Returns a tuple: sorted list in non-decreasing order; and a count of inversions. """ def merge(left_list, right_list): nonlocal inversion_count#Allows for this function to have closure ...
4d143034781509f170b7ba87d3ab803e98db01b0
JayIvhen/StudyRepoPython2014
/home_work/lesson3/Diykstra.py
2,043
3.765625
4
#!usr/bin/python """Diykstra algorithm""" __author__ = "JayIvhen" def search_function(room, x, y, path): print x, y, room[x][y]['path_length'] path.append((x,y)) if room[x][y]['x'] == 10 and room[x][y]['y'] ==10: print 'Finish!!' global path = path return if room[x][y]['UP_check'] == False: room[x][y]['...
830e22e15f52ce5d1d0eb65a39c1ea345caadf5a
gokarna123/Gokarna
/classwork.py
333
4.125
4
from datetime import time num=[] x=int(input("Enter the number:")) for i in range(1,x+1): value=int(input(" Please Enter the number: ")) num.append(value) num.sort() print(num) num=[] x=int(input("Enter the number:")) for i in range(1,x+1): value=int(input(" Please Enter the number: ")) num.reverse()...
969f2679ef804d582202829a9d216accd056da4b
Mindo-Joseph/ProjectEuler100Challenge
/multiples3and5.py
169
3.984375
4
def multiples3and5(number): total = 0 for i in range(number): if i%3 == 0 or i%5 == 0: total+=i return total print(multiples3and5(19564))
8563ff08b1cdda9f463b5856aac896f9cd3dc1d1
hpine19/Purple-cheesecakes
/problem3 copy.py
867
3.796875
4
#robotx= 0 #roboty= 0 #north= 2 #south= 3 #west= 4 #east= 5 #random(2,5) #if 2 #move robot 2 coordinates north #if 3 #move robot 3 coordinates south #if 4 #move robot 4 coordinates west #if 5 #move robot 5 coordinates east import random def twoDRandomWalk(n= 100, printOn= False): n= 0 location= 0 coun...
1b44ff7a01a4998b83f75778925b8b09ffe7e3ca
tiredant/challenge-solutions
/romans.py
1,348
3.546875
4
import sys def romans(x): marker = 0 bench = [] while marker < int(x): difference = int(x) - marker if difference >= 1000: marker += 1000 bench.append("M") elif 1000 > difference >= 900: marker += 900 bench.append("CM") elif 9...
9227a9c005d41eaed7b244a53c2187229d014c3f
jakehoare/leetcode
/python_1_to_1000/883_Projection_Area_of_3D_Shapes.py
1,371
3.921875
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/projection-area-of-3d-shapes/ # On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. # Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). # Now we view the project...
a6391e05468eb3a42dca978a4a0aa015a77d770e
DannyHalstead/Ch.07_Graphics
/7.1_Flag.py
1,537
3.65625
4
''' FLAG PROJECT --------------- Make your flag 260 pixels tall Use the scaling image on the website to determine other dimensions The hexadecimal colors for the official flag are red:#BF0A30 and blue:#002868 Title the window, "The Stars and Stripes" I used a draw_text command and used 20 pt. asterisks for the stars. W...
bc4e5e8af3ea7569bf39dcf4074f823ce02ba01b
HannahW432/new
/module1.py
554
4.0625
4
def change_frequency(frequency_changes): current_frequency = 0; for change in frequency_changes: if (change[:1] == "+"): current_frequency = current_frequency + change[1:] else: current_frequency = current_frequency + change[1:] print (str(current_frequency)) def ...
d7df371297fc8c0aa1fc8cbca47ccd30603688e8
Risto97/simple-sat
/src/sudoku/sudoku.py
5,542
3.578125
4
import numpy as np # https://github.com/MorvanZhou/sudoku def generate_sudoku(mask_rate=0.5): while True: n = 9 m = np.zeros((n, n), np.int) rg = np.arange(1, n + 1) m[0, :] = np.random.choice(rg, n, replace=False) try: for r in range(1, n): for ...
b92dea7810c42718b32ec1689708dd9b5df21282
aftabanjum4451/Python-kick-Start-Repo
/Python Practice Question/Practice mod17.py
4,140
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 22 11:02:49 2020 @author: aftab """ #Q Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return t...
51f83e8f423b4ed7b7252d3f7a394586b1825cd0
TemirT27/webdev2019
/week8/infromatics/arrays/g.py
141
3.53125
4
m = int(input()) arr = [int(a) for a in input().split()][:m] reverse_a = arr[::-1] for i in range(0, m): print(reverse_a[i], end=' ')
f8a7e1e3b2401bb9c4e79a266a523ffb4040f63b
ckpmumbai/python
/1.2.py
121
3.84375
4
Firstname=input("enter firstname:") Lastname=input("enter lastname:") wholename =firstname+lastname print(wholename)
876698a96fe413952c0332cac440276320d6c751
Botany-Downs-Secondary-College/speedingticket-ChrisLiangBDSC
/speeding_ticket.py
3,755
3.96875
4
speed = 0 speed_limit = 0 wanted_list = ["Jones", "Eric", "Dylan"] fines = [] summary_list = [] over_limit = 0 statement = "" user_answer = "" def user_inputs(): global speed global speed_limit while True: try: speed = int(input("\nWhat was the speed you were going at? : ")) ...
68a9f0c50395c900413dbec89737a22e155fd0d6
ayushig-29/91Docial-Task
/3.py
305
3.90625
4
#: Write a Python program to convert the Python dictionary object (sort by key) to #JSON data. Print the object members with indent level 4 import json str = {'a': 5, 'c': 7, 'b': 3, 'd': 4} print("Original String:") print(str) print("JSON data:") print(json.dumps(str, sort_keys=True, indent=4))
93f592fc315c339ba8e15679dd434a29235a1a08
omoh09/Python_First_Task
/AOC.py
522
4.25
4
#Create Basic Calculator for Area of a Circle import math from math import pi while True: try: print(''' Write a Python program which accepts the radius of a circle from the user and computes the area. ''') radius = float(input ("Input the radius of the circle : ")) ...
26baf45d4f39d6f5a38f845730866b71ee4dd84a
20130353/Leetcode
/target_offer/二叉树/二叉树的右视图.py
798
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : 二叉树的右视图.py # @Author: smx # @Date : 2020/2/18 # @Desc : # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rightSideView(self, root):...