blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1553be860e9185d62d893effae91eb0204267c70
varrtix/varscripts
/tools/files_rename.py
4,725
3.5625
4
#! /usr/bin/env python3 # encoding=utf-8 import os, sys, shutil def moveFunc2(targetPath, rootPath = '.'): probe = False fileList = os.listdir(rootPath) for fileName in fileList: filePath = os.path.join(rootPath, fileName) if os.path.isdir(filePath): moveFunc2(targetPath, filePa...
31d2e1af2b301292ac334cda5b0e3654413aca02
FranckCHAMBON/ClasseVirtuelle
/Term_NSI/devoirs/4-dm2/Corrigé/S8/E3.py
856
3.515625
4
""" Prologin : Épreuve régionale 2003 Exercice : Grand écart https://prologin.org/train/2003/semifinal/grand_ecart """ def ecart(nb_tableau: int, tableau: int) -> int: """Cette fonction prend en paramètre un tableau de nombres entiers, et qui recherche, dans ce tableau, la plus grande différence, entr...
20087d1cc263803d28b633112605cb6485c98861
rschwa6308/Misc
/DuoLingoProblem.py
999
3.53125
4
with open("Hangman/words_alpha.txt") as f: WORDS = f.read().split() SUBWORDS_MAP = {} for word in WORDS: for i in range(len(word)): subword = word[:i] + word[i+1:] if subword not in SUBWORDS_MAP: SUBWORDS_MAP[subword] = [] SUBWORDS_MAP[subword].append((word, i)) def vali...
10268740e6db99b977c6660fd290149d15eec4ed
JKD1987/Python
/Python/strFnTest.py
934
4.125
4
#String Function Handling message = "hello! how are you all!!" print("Default Message: ", message) print("Message length: ", len(message)) print("Capitalized first letter: ", message.capitalize()) print("Message in upper case: ", message.upper()) print("Message in Lower case: ", message.lower()) print("Message...
8d79248128ec0fba583365384d965fa8abdaa591
apuroop98/Projects
/myide.py
3,716
4
4
from tkinter import * # tkinter is used to create GUI Applications from tkinter.filedialog import asksaveasfilename, askopenfilename import subprocess # The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. file_path = '' def set_file_path(pa...
1d81e3cebace17cf767971126a418e353d9a4c03
gosch/Katas-in-python
/2019/july/MovingAverage.py
906
3.6875
4
class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.size = size self.values = [0] * size self.pos = 0 self.acu = 0 self.n = 0 def next(self, val: int) -> float: if self.n < self.size: ...
48b4aed5d19a203d35446e602ed5ef66c778954a
melodyre/PythonPractice
/final test/test.py
185
3.6875
4
''' 中国大学慕课,Python学习,期末考试 考试时测试文件 ''' class point(): def __init__(self,x,y): self.x = x self.y = y x=point(3,2) print(x.z )
a58e809501a21ed079e397077a380b75398b3c26
subhasisj/python-projects
/Exercises/for-ladi/01. The-Beginning.py
316
3.796875
4
def add_two_numbers(a, b): return a % b def check_what_happens(value1, value2): return value1 * value2 if __name__ == '__main__': # print(add_two_numbers(7, 2)) # print(check_what_happens(5, 'Ladi')) ladi = "xyz" ladi = 5 ladi = 'xyz' ladi = 5 print(ladi)
0c249dcdf67bc49e483bc3f2d3023649880bbff3
Crasti/Homework
/Lesson8/Task8.2.py
968
4.28125
4
""" Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class ExDivisionByZerro(Exception): def __...
1ddd0a4bb048d13a6996546e5caf176b4c89fedb
jxxiao/leetcode
/python/023_Merge_k_Sorted_Lists.py
641
3.78125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None result = [...
e1ec84f19b8ed193fd0dae4b46a1a35bd186a6f6
raymondhk/Python
/Fundamentals/multiples_sums_average.py
747
4.53125
5
#part 1: write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. def odd_num(): for i in range(1, 1000, 2): print i print odd_num() #part 2: create another program that prints all the multiples of 5 from 5 to 1,000,000 def multi_five(): for...
25a1e054e66b034af92b509382ef390af5d03108
mario2018/hrank-solution
/NewYearChaos/minimumBribes.py
1,679
4.25
4
''' Complete the function minimumBribes. It must print an integer representing the minimum number of bribes necessary, or "Too chaotic" if the line configuration is not possible. minimumBribes has the following parameter(s): q: an array of integers Input Format The first line contains an integer t, the number of test ...
997b84cb47fa703dc194125f0ba6da4f2b8d55e1
Shreyash-310/ML_algorithm_practice
/Multiple regression.py
1,059
3.890625
4
# Multiple Linear Regression # Importing the libraries import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score # Importing the dataset dataset = pd.read_csv('50_Startups.cs...
ac349089d30cbd803f7e2a850d03cebe3abf007c
coolstoryjoe-bro/self-taught-journey-
/PersonalPractice/While loops/While Practice.py
2,051
4.0625
4
toppings_quest = "\nWhat pizza toppings would you like? " toppings_quest += "\n(Enter 'done' to send the toppings.) " message = "" active = True while active: message = input(toppings_quest) if message == 'done': active = False else: print(f"Adding {message.title()} to you pizza.") movi...
a5300cf1c1e1c3013104379147561fafe267c573
jacksonyoudi/python-note
/notebook/threadprocess/exp2.py
268
3.546875
4
#!/usr/bin/env python # coding: utf8 from threading import Thread class MyThread(Thread): def run(self): print 'I am threading' Thread.run(self) def bar(): print 'bar' t1 = MyThread(target=bar) t1.start() print 'over'
626443259ff7b657b63e6959dec8b2a8611bd490
nayankhade/Python-programs
/ConvertVariableByTypecasting.py
187
3.921875
4
x=1 y=1.0 z=1j print(type(x)) print(type(y)) print(type(z)) """ Convert int into float, float into int, int into complex """ a=float(x) print(a) b=int(y) print(b) c=complex(x) print(c)
a64df3b8f885f80e5008cee0a98e718575326f54
BazhenovaSvetlana/1sem
/turtle1e10.py
116
3.796875
4
import turtle as t t.shape('turtle') n = int(input()) for i in range(n): t.circle(50, 360) t.left(360 / n)
0143d19059fe61d031d621fbddee0065b3e835a8
WandersonGomes/URIJudge
/problem_2866.py
370
3.75
4
#PROBLEM 2866 #link = https://www.urionlinejudge.com.br/judge/pt/problems/view/2866 #PYTHON 3 quantidade_testes = int(input()) for i in range(0, quantidade_testes): linha = input() resposta = "" for letra in linha: valor_letra = ord(letra) if valor_letra >= 97 and valor_letra <= 122: ...
d47d58f6e24fb58f2c430fdb0f1c2586562aca89
OnerBerk/b-f-Python-flask
/petitjeu/code.py
429
3.65625
4
number = 7 userInput=input("tape y si tu veux jouer :").lower() #lower transforme tout en minuscule facilite les comparaison if userInput == "y": userNumber = int(input("choisi un chiffre entre 0 et 10 :")) if userNumber == number: print("bravoooooooo !!!!") elif abs(number - userNumber) == 1: ...
355eb45f9017f2e136dee9cdcc34f1cb1777e2da
anandmpandit/python-scripts-1
/prime-number/code.py
198
3.984375
4
num = 7 if num > 1: for i in range(2, num): if (num % i) == 0: print("Not Prime") break else: print("It's Prime") else: print("Not Prime")
ed9bc02ab0801a09fefe100dc18594612351ec6d
Yashverma7089/PythonAssignment
/List Assignment/List_22.py
271
4.25
4
# Write a Python program to find the index of an item in a specified list. L = ['G','w','a','l','i','o','r'] i = input("Enter element you want to know index : ") try: S = L.index(i) print("The index of",i,"is :",S) except Exception as e: print("Error :",e)
dc4dbd088324f45e46c09bf9b4eb7f4814a834ca
pqnguyen/CompetitiveProgramming
/platforms/interviewbit/Subtract.py
858
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from collections import deque class Solution: # @param A : head node of linked list # @return the head node in the linked list def subtract(self, A): stack = deque(...
940a72db95aae1dc8450968ee374a296b5ea3f91
Nadirlene/Exercicios-python
/Exerciciospython2/Dicionário/e094.py
1,227
3.5625
4
lista = [] cadatsro = {} lista = [] somaIdades = média = 0 while True: cadatsro['nome'] = str(input('Nome: ')) while True: cadatsro['sexo'] = str(input('Sexo: [M/F] ')).strip().upper()[0] if cadatsro['sexo'] in 'MF': break print('ERRO! Por favor, digite apenas M ou F.') c...
fb7fddf6a68819ebc0acb604114518cffe19eed4
LofiWiz/CS-1400
/exercise2/exercise2.4.py
494
4.34375
4
# Seth Mitchell (10600367) # CS 1400 # Exercise 2.4 # 4: Converting Fahrenheit to Celsius: fahrenheit = float(input("What is the temperature in degrees fahrenheit?: ")) celsius = float((fahrenheit - 32) * 5/9) print(f"The temperature {fahrenheit} F is = {celsius} C") # original Celsius to Fahrenheit exampl...
643c113c21b5177db37d7ca6de6cc24183876441
purushottamkaushik/DataStructuresUsingPython
/BitManipulation/SingleNumber.py
348
3.5625
4
#def singleNumber(nums): # return (3 * (sum(set(nums))) - sum(nums)) // 2 def singleNumber(nums): mydict = dict() for num in nums: if num not in mydict.keys(): mydict[num] = 1 else : mydict[num] = mydict.get(num) + 1 print(mydict) return [k for k,v in mydict.items() if v==1][0] nums = [1,0,1,0,1,0,99...
5d62a09b45faab9e1740b53a72f897ffe624ac98
perritodlp/python-course-platzi
/perros.py
1,308
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # class Perros(object): #Declaramos la clase principal Perros def ladrar (self): print ("""GUAAAUU GUAAAUU!""") def grunir (self): print ("""GRRRRRR GRRRRR""") class Caniche (Perros):#La clase secundaria hereda de la clase principal perros ...
8bb12a3a221f95156685f1ddc0219891207a36f3
wangJmes/PycharmProjects
/pythonProject/pythonStudy/chap13/demo9.py
566
4.21875
4
# 练习 # 开发者:汪川 # 开发时间: 2021/8/24 11:20 a = 20 b = 100 c = a + b d = a.__add__(b) print(c) print(d) class Student: def __init__(self, name): self.name = name def __add__(self, other): return self.name + other.name def __len__(self): return len(self.name) stu1 = Student('张三') stu2...
8b76b2fbd4f5742939c2b059c34b535e2d6626f6
forkcodeaiyc/skulpt_parser
/run-tests/t227.py
97
3.90625
4
a = (1, 2, 3) b = ("a", "b", "c") for x in a + b: print(x) print(("a:", a)) print(("b:", b))
4f467b7ae282a5253250121e35c0eb575f56b426
Mennovdjagt/ALDS
/Week2/opdracht5.py
988
4
4
class linkedList: def __init__(self, value = None): self.value = value self.tail = None def append(self, value): if self.value == None: self.value = value return if self.tail == None: self.tail = linkedList(value) return s...
58de1c4f7139221177dbef5ddccbe0fbc935499d
Maryanali/PythonLeapYearCalculator
/LeapYear.py
311
4.34375
4
#!/usr/bin/env python3 #check what year it is and check whether or not it is a leap year year =int(input("What year is it? ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year") else: print("Not leap year") else: print("Leap year") else: print("Not Leap year😎")
4f47c3921b3ded3fdc98342ecc15e2502b23f928
andreluismoreira/Codigos-em-Python
/Lista.py
121
3.515625
4
numeros = [0, 1, 2, 3, 4] for i in range(0, len(numeros)): multiplicacao = numeros[i] * 4 print(multiplicacao)
9cb49f57da970373f9f2e11546f9e817a3264e2e
vitor-mafra/learning_python
/jogos/jogos.py
486
3.734375
4
import jogo_forca import jogo_adivinhacao def escolhe_jogo(): print("*********************************") print("*******Escolha o seu jogo!*******") print("*********************************\n") print("(1) Forca\n(2) Adivinhacao") jogo = int(input("Digite o jogo que voce quer jogar: ")) if(jogo == 1): print("...
23508409f6d2bd14e7fae47d488dd4d4171c8142
shantanu609/Binary-Search-4
/Problem1.py
1,714
3.578125
4
# Time Complexity : O(log n) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach # we have to find the h index. So total number of papers - the index shuold be less than or equals to th...
05f3f4c59048b1cf1bfc38cfc658eb3b3ff004ac
adurham198/PythonCodeChallenges
/Stairs.py
424
4.09375
4
#Anton Durham #7/30/2019 #Desc: This program is the classic stairs of recursion problem #solved by the fibonacci sequence's algorithm. def main(n): l1 = [] if (n == 0): return 1 elif (n == 1 or n == 2 or n == 3): return n #these if and elif statements are just base cases ...
04f3b7471959d55bd76b16f496bbc3994e9dee2f
OzzieShazam/chess
/Michael/chessshit2.py
3,535
3.859375
4
from enum import Enum class Color(Enum): WHITE = 0 BLACK = 1 class Piece(Enum): PAWN = 0 KNIGHT = 1 BISHOP = 2 ROOK = 3 QUEEN = 4 KING = 5 class Board: def __init__(self): self.board = [[None]*8 for i in range(8)] self.turn = Color.WHITE s...
1afa13d9ffc6a919033d867f5e1de518b95bbd41
VladyslavPodrazhanskyi/First_repl
/tutor_tasks/share_of_apples.py
201
3.53125
4
n = int(input('input number of pupils: ')) k = int(input('input quantity of apples: ')) share = k // n basket = k % n print(f'Every pupil receives {share} apples, {basket} apples leaves in the basket')
ab92ab558da671ea5f9752ef84988995e2473ade
luid95/python-course
/02-variables-y-tipos/tipos.py
620
3.53125
4
# Indica que no tiene nada la variable nada = None # cadena cadena = " Hola soy Luis Morales" cadena = " Desarrollador web" entero = 99 flotante = 4.2 booleano = True lista = [100, 20, 30, 40, 100] listaString = [44, "treinta", 30, "cuarenta"] tuplanoCambia = ("master", "en", "python") diccionario = { "nombre": "L...
fc5f252a7269a6bf2ebc7536154f7077282b1c12
gorillacodes/HelloWorld-
/Reversing no..py
147
4.21875
4
print(input("Enter a number: ")[::-1]) #num = input("Enter a number") #for c in reversed(num): #print(c, end='')
e0a3b87e73f2cc73eb961a689be123638040fde6
minhlong94/Theoretical-Models-in-Computing
/Lab 4 - Optimization and HyperOpt/Steepest Descent Method.py
1,429
4.03125
4
from sympy import diff, solve, Abs x, y, h = s.symbols('x y h') # f = (x - 3)**2 + (y - 2)**2 # Lab exercise f = 2*x*y + 2*x - x**2 - 2*(y**2) # TMC Optimization slide example print("This program solves {} using Steepest Descent Method".format(f)) inix = int(input("Input initial value x: \n")) iniy = int(input("Inp...
8b904667eea4f5baff0d49fb22b0dae198e301f0
nicolasmonteiro/Python
/Exercício(tuplas,listas e dicionário)/Q1Tupla.py
482
4.125
4
times = ('Sport', 'Náutico', 'Santa Cruz', 'Salgueiro', 'Central', 'Afogados', 'Vitória', 'Petrolina', 'América', 'Flamengo Arcoverde') for t in range(0, len(times)): if (t >= 0 and t < 3): print(t+1, "º", times[t]) if (t >= 6 and t <= 9): print(t+1, "º", times[t]) print("Times em ord...
b6d2b9a71638473ba0010c707a4cad732f0bbe89
ArtosLIO/OOPHomework
/Homework2/homework2.py
950
3.953125
4
class Employee(object): def __init__(self, name, email, salary): self.name = name self.email = email self.salary_for_day = salary def work(self): return "I come to the office." def check_salary(self, working_days): return "Salary for {} working_days: {}".format(work...
d7e61e51108fdaf7efabb568be8305c083728a67
luciorgomes/Rotinas
/transpose_clipboard.py
434
3.953125
4
# ! /usr/bin/python3 # transpose_clipboard.py - transpõe o conteúdo de um coluna constante no clipboard em linha com itens separados por # vírgula e manda o resultado para o clipboard import pyperclip def transpose_clipboard(): mem = pyperclip.paste() mem = mem.split() transposed = ','.join(mem) pype...
72c59edf1e6b9df1f182566ac78edd28446e7fce
Bogomil94/pythonProject
/Exercise2.5.py
323
3.703125
4
p= float(input("Principal = ")) r= float(input( "interest rate = ")) n= float(input( "annual compounding periods = " )) t= float(input( "number of years = ")) a= p*((1+r/n)**(n*t)) a2= round(a,2) print( "final amount = ", a2) percent= ((a-p)/p)*100 percent2= round(percent,2) print( "percent increase = ", percent2, "%")...
e8042a50b132e9412282c889f2f5330006251bc8
CheRayLiu/LeetCode
/medium/house_robber_II.py
1,173
3.703125
4
""" You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically co...
047bac9d0376e1ec511b0aae18feacd9abe1483a
boundshunter/da-new-s4-code
/作业/购物车/购物车-作业-1203.py
5,479
3.671875
4
__author__ = 'sujunfeng' shopping_menu=[ ("Iphone X",8999), ("Mac pro",17999), ("Bike",999), ("Balance car",1999), ("Book",59), ("IWatch",3999) ] import sys with open("user_info_list.txt",'r') as f: info=f.read() user_info_dict = eval(info) def shopping_list(): # 打印商品列表 print('\0...
cf0997d452182588285a27553381517f394ced85
achntj/2-semesters-of-python-in-HS
/min.py
444
4.125
4
#Write a program to check if the minimum element of a tuple lies at the middle position #of the tuple n=int(input("Enter number of characters in tuple1: ")) t1=(tuple()) for i in range(0,n): a=int(input("Enter value for tuple: ")) t1+=(a,) length=len(t1) if length%2==0: mid=length//2 else: mid=(length...
4418c135c0dab27f420c8ce11ed9fc3e2f990f3c
gyang274/leetcode
/src/0400-0499/0435.none.overlapping.intervals.py
1,560
3.640625
4
from typing import List class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: """sort w.r.t start point + dynamic programming: O(N^2) """ # sort w.r.t start intervals.sort() # n: num of intervals n = len(intervals) # dp: max num of intervals can be kept w.o. ...
10f51ee5f97bae66502db4a4b505f1de4c12305e
weizt/python_studying
/正则表达式/05-re.complie.py
616
3.609375
4
# compile 编译 # 在re模块中,可以使用re.方法名 调用函数,也可以使用re.compile得到一个对象,再调用函数 import re # 直接调用函数 m = re.search(r'm.*a', 'dskjafdmkldsjal') print(m) # <re.Match object; span=(7, 14), match='mkldsja'> # 先使用compile创建对象,再用对象调用函数,效果等同于上 x = re.compile(r'm.*a') m1 = x.search('dskjafdmkldsjal') m2 = x.search('dlskajfmklsdakasfdsafdsa...
93521703e76dd0a284a0e907e88278de42b80ab7
Jatin345Anand/Python
/CorePython_Evening/05-MenuDriven/02-Eval.py
539
4
4
def calculator(x,y, opr): # if ch == "1": # return x + y # elif ch == "2": # return x - y return eval(x+opr+y) print(""" 1. Add 2. Sub 3. Mul 4. Div """) user_choice = input("Enter your choice : ") num_1 = input("Enter first number : ") num_2 = input("Enter second number ...
3ca4f35fc8bcfd1d31b80701bf41253e27cb1e06
maykjony90/py3_projects
/learning_python/math_functions/kinematic_formulas/Second_Kinematic_Formula.py
1,597
4.125
4
# Solve for time, acceleration, final velocity or initial velocity # by using First Kinematic Formula. # Usage: enter the known values. Enter 'x' for unknown value. # def second_kinematic_formula(initial_velocity, final_velocity, displacement, time): if initial_velocity == 'x': ...
78bf7a2cf582904c2d923947bb89331dfa9acd43
laoohh/leetcode-python
/66 - Plus One.py
1,575
3.6875
4
# Given a non-empty array of digits representing a non-negative integer, # plus one to the integer. # # The digits are stored such that the most significant digit is # at the head of the list, # and each element in the array contain a single digit. # # You may assume the integer does not contain any leading zero, # exc...
2688764456e34943311fb82c4775068c4d17932f
davpapp/GeneFinder
/gene_finder.py
9,718
4.0625
4
# -*- coding: utf-8 -*- """ The Going beyond part is in the going_beyond function. @author: David Papp """ import random from amino_acids import aa, codons, aa_table # you may find these useful from load import load_seq def shuffle_string(s): """Shuffles the characters in the input string NOTE: this...
6abfa5569f4b8792c15b52354ad9c3b49f757c19
ALLYOURSR/oag_int_python
/objects/NeuralNet.py
867
3.640625
4
import tensorflow as tf class NeuralNet: def __init__(self, input_placeholder, output_placeholder, linear_output_layer, error_tensor, train_tensor, summaries, graph, scope): self.input_placeholder = input_placeholder self.output_placeholder = output_placeholder self.error_tensor = error_ten...
8a3853c9a8b81da469b6ea65472a4076c42b7f68
Patrickyyh/CSCE110
/List_test/list.py
1,878
4.03125
4
my_list = [] for num in range(10): my_list.append(num) my_seocndList = list(my_list) for ele in my_seocndList: print(ele,end = ' ' ) print() if bool(my_seocndList) and bool(my_list): print("Both of them have the elements") else: print("one of the them does nothave the value") ## List compehension ...
c0e66184207473dd70b8a0695cb2beda457f2a6a
leafeecs/interview
/algorithms/sorting/practice/bubble_sort_test.py
930
3.765625
4
import random import timeit start_time = timeit.default_timer() def bubble_sort(data): for i in range(len(data) - 1): for j in range(len(data) - 1): if data[j] > data[j + 1]: data[j], data[j + 1] = data[j + 1], data[j] return data end_time = timeit.default_timer() data_li...
1fd2a41b4f8a168b5e954f55aaed273653560900
jaijaish98/ProblemSolving
/count_good_nodes_in_binary_tree.py
2,080
3.953125
4
""" Count Good Nodes in Binary Tree Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. Example 1: 3 / \ 1 4 / / \ 3 1 5 Input: root = ...
dc833bfd18670d94ac7143a3be8c6009ae7eed1f
Paalar/TDT4110
/Øving 2/karakter.py
1,224
3.765625
4
while True: try: karakter = eval(input("Hva er poengsummen?\n")) except (NameError, SyntaxError): print("Dette går ikke.") while type(karakter) == float: print("dette går ikke!") karakter = eval(input("Jeg trenger en gyldig poengsum!\n")) while karakter<0 or karakter>100: print...
7b52d91c56fa7033e37135c6ad2db39b8af62cab
brahmaduttan/ProgrammingLab-Python
/CO2/CO2/11lambda.py
147
3.59375
4
square = lambda s : s*s rectangle = lambda l,b : l*b triangle = lambda b,h : (b*h)/2 print(square(7)) print(triangle(7,15)) print(rectangle(10,5))
78d6a6add7641520e9474979c8a4499336eb1534
pawwahn/python_practice
/exam/iterators.py
177
3.5
4
a = [1,2,3,4,5,6,7,8,9,0] #print(a.__next__()) print(type(a)) a.iter() itr = iter(a) print(a.__next__()) print (itr) print (next(itr)) print (next(itr)) print(a.__sizeof__())
41a1c013399d7e2f282e383bb711d6ae022fb936
MajesticTaco/python_triangle_xy
/python_triangle_xy.py
819
4.21875
4
import math print ('Enter the requested inputs to calculate the Area and Perimeter') x1 = float(input('Enter the value of X1: ')) y1 = float(input('Enter the value of Y1: ')) x2 = float(input('Enter the value of X2: ')) y2 = float(input('Enter the value of Y2: ')) x3 = float(input('Enter the value of X3: ')) ...
c1911fab1a85c254d255c604b29fea5d2604324d
Zhenye-Na/leetcode
/interview/wepay/reverse-polish-notation.py
2,888
3.96875
4
""" Reverse Polish Notation input可以是double,返回也是double,然后不保证input valid。 需要自己写error handling。然后followup问如果有很多别的运算符,类似根号啥的 """ import math from abc import ABCMeta, abstractmethod class Expression(object, metaclass=ABCMeta): @abstractmethod def calculate(self, left, token, right=None): pass class Two...
72ba3d062f000afc4cd563b9292d1ffab8cd56c1
dovilemureikaite/python_unit_2
/MODULE_1/module_1.py
13,961
4.34375
4
# Mod1_2-1.1_Intro_Python.ipynb # _______________________________________________________ # ## TASK 1 # # [ ] assign a string 5 or more letters long to the variable: street_name # [ ] print the 1st, 3rd and 5th characters street_name = "Gedimino" print("1st:",street_name[0]) print("3rd:",street_name[2]) print("5th:",s...
69eedf6960de3a4bb376c000388f6f22f1660fa5
chi-feng/AoC2019
/day03/day3.py
793
3.609375
4
dxdy = {"U": (0, 1), "R": (1, 0), "D": (0, -1), "L": (-1, 0)} def get_coords(path): # coords[(x, y)] = minimum number of steps to reach (x, y) coords = dict() x, y = 0, 0 steps = 0 for segment in path: dx, dy = dxdy[segment[0]] length = int(segment[1:]) for i in range(lengt...
6fa542f7581c925bdd1a819f17e69dd565ae732e
jelizalo/python-challenge
/PyPoll/main.py
1,749
3.890625
4
import os import csv #CSVpath to first csvpath1 = os.path.join('election_data_1.csv') with open (csvpath1, 'r', newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') next(csvreader) #defining the variables votes = 0 candidates = {} for row in csvreader: #finding total number of votes votes ...
c9394ecf93f0359a8b6db6cb7688644e69c8556f
aar2dee2/Factorial-Function
/main.py
624
4.46875
4
def factorial_funct(n): """define a variable called product. We can't set it as 0, as anything multiplied by 0, will always return 0.""" product = 1 for num in range(1,n+1): product *= num return product def recursive_factorial(n): if n>1: return n * recursive_factorial(n-1) else: return ...
414120a087b5d5fcc3b72d596dcbba0dd1e51c72
Monsieurvishal/Peers-learning-python-3
/programs/to verify given number.py
181
4
4
num = 3.4 # Try these two variations as well: # num = 0 # num = -4.5 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
4a183a5d440bbe100357aea97887e74b308bb80c
jinbao-x/python
/pycharm/22--列表元素的排序与反转.py
492
4.21875
4
# 使用sort直接修改列表里元素的顺序 ls = [5, 8, 1, 10, 13] ls.sort() # sort默认为升序 sort()是列表里专有的方法,而sorted对于所有可迭代序列均可以使用 print(ls) ls.sort(reverse=True) # 设置为降序 print(ls) # 想修改元素顺序,并返回新的列表,则使用sorted ls = [13, 78, 34, 12, 90, 1] ls_new = sorted(ls, reverse=True) print(ls) print(ls_new) # 反转列表里的元素 ls = [23, 56, 7, 8, 23, 90, 45] ls....
62d281e6ed3db58f2bdcaefe96c9d8d79792a7da
qlhai/Algorithms
/剑指offer/032-2.py
868
3.890625
4
from collections import deque from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: ...
db0d6378fbe2e47ddb6488a66e5427a5e6594c92
samuelcheang0419/python-labs
/solutions/lab-8/ml_solutions.py
5,673
3.9375
4
import numpy as np import sklearn def load_dataset_regression(filename): """ Loads the dataset from the file. Shuffles it, then adds it to NumPy matrices. Input: filename - the name of a .csv file to load. Output: X, Y - NumPy arrays extracted from the .csv file. X is the data,...
79d238f0418e45cb08cc7cab987032a7fc5e02c5
IgorFrutuoso/Renomeador_de_nota_fiscal_pdf_e_xml
/Renomear aquivos.py
1,343
3.765625
4
import re import os import shutil print('Renomeador de arquivos by Frutuoso') pasta = r'C:\Users\User\Downloads\notas' #local da pasta onde estâo os aquivos numero_inicial = int(input('Digite o numero inicial: ')) #Número da primeira nota numero_final = int(input('Digite o numero final: ...
943be7e30886952b862d851eac642b817647f3d7
jipson7/unix-lm-toolkit
/scripts/line_extract.py
673
3.96875
4
import sys def year_in_line(line, year): return (line.split()[-3] == str(year)) def line_is_printable(line): try: line.decode('ascii') except UnicodeDecodeError: return False else: return True def strip_data(line): """Removes the year column and number of books column....
1fb4185313748ab87afc76aa7ae63a426d8456f6
paren8esis/Style_Transfer
/utils.py
1,405
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Various utility functions for style transfer. """ import numpy as np import keras.backend as K def mean_subtraction(x): ''' Subtracts the ImageNet mean value from given image. Parameters: ----------- x : ndarray The image to subt...
07f426fcd234ae933b54714029ed1aa345f9a6fb
ellafrimer/shecodes
/python_way/plus_one.py
290
4.09375
4
""" a function that takes a number as a list of numbers from 1-9 an returns the next number: (5,2)-(5,3) (9,9)-(1,0,0) """ def plus_one(digits): string = ''.join(map(str, digits)) new_number = int(string) + 1 new_digits = list(map(int, str(new_number))) return new_digits
a30362b562a45fa330667229766ef646a2eba592
lelufig/program
/list/list3/list3-17a.py
239
4.0625
4
a = int(input("何月ですか:")) if 3 <= a <= 5: print(f"{a}月は春です") elif 6 <= a <= 8: print(f"{a}月は夏です") elif 9 <= a <=11: print(f"{a}月は秋です") elif 1 <= a <= 12: print(f"{a}月は冬です")
dca1d6314cbbbc58829dcd077f95faa805486230
Capoaleman/Advent-of-code-2020
/Day15_2020.py
825
3.75
4
# December 15th Advent Calendar of Code 2020 # https://adventofcode.com/2020 # By Capoaleman INPUT = [2, 0, 1, 7, 4, 14, 18] def next_num(turn, num): tmp = data.get(num, 0) data[num] = turn if tmp == 0: return tmp else: return turn - tmp def play(top): turn = le...
425e1242273d014390eea640253cd72bf62726e9
ajaygc95/advPy
/.history/lab1/DataBase_20210127230920.py
1,049
3.890625
4
import sqlite3 class Database: def __init__(self): self.conn = sqlite3.connect('temperature.db') self.c = self.conn.cursor() def createTable(self): with self.conn: self.c.execute('CREATE TABLE IF NOT EXITS temperature (year int , temperature )') def create(self, y...
f0187c20e09b400ba9299a56186586c25c48d466
natiawhitehead/-MasterInterview_Udemy
/LeetCode/_1431_kids_with_candies.py
626
3.984375
4
# Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. # For each kid check if there is a way to distribute extraCandies among the kids such that he or # she can have the greatest number of candies among them. Notice that multiple kids can have t...
22075590803d94960e43833a6a1071b5a49da444
Atul240202/AtulJha_Python_Learning
/tables.py
300
3.90625
4
#Table of any random number till 10 #No installation of any library required #By - Atul Jha def main(): num = int(input('Which number you want to multiply:')) print('Here is your table') for i in range(1, 11): print(num, 'x' , i, '=' ,num*i) if __name__ == '__main__': main()
7a4a7a2bf269d2aafcb697e81cea13431920fad0
Sai-Shyam123/Python-Basics
/Strings.py
813
3.90625
4
# Strings brand1 = 'amiGoscode' print(brand1.upper()) print(brand1.lower()) print(brand1.capitalize()) print(len(brand1)) print(brand1.replace('e', 'E')) print(brand1 == "amiGoscode") print(brand1 != "amiGoscode") print("code" in brand1) print("code" not in brand1) # Multiline comments comment = "My Name Is Khalil A...
4ef3815b9c7ce0f21d10f8149f3d093c770fcc5f
jamalarain/PythonCodes
/14.MySQLPython pgm.py
2,576
3.671875
4
# Example to connect myDB import mysql.connector conn = mysql.connector.connect(user='root',password='system1',host='localhost') mycursor=conn.cursor() mycursor.execute('SHOW TABLES') print(mycursor.fetchall()) # database connector. import mysql.connector conn = mysql.connector.connect(user='root',password='system1'...
c005cfe3f9db4612d17a11195bbd360a1caad6fc
Goryaschenko/Python_GeekBrain_HW
/lesson_4/5_list.py
608
3.921875
4
""" Задание 5: Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce(). """ from functools import reduce...
d2d42fdab6a5c468987c87aff77c2502ee71bedb
ajay-cz/ASSIGNMENT1_BLR_B2_G097
/binary_tree.py
8,099
3.984375
4
# -*- coding: utf-8 -*- class EmployeeBinaryTreeNode(object): """ Class that represents a BinaryTree Node. a EmployeeBinaryTreeNode contains a left child, right child & value of the current Node. The child nodes of this node in-turn would follow the properties of a EmployeeBinaryTreeNode """ def _...
e1c10b4e69aab442525fd8802c7e23f0e88f2a63
kntiwary/ML
/test2.py
575
3.953125
4
# # def extend_list(val, list=None): # if list is None: # list = [] # list.append(val) # return list # # # list1 = extend_list(10) # list2 = extend_list(123, []) # list3 = extend_list('a') # # print("list1 = %s" % list1) # print("list2 = %s" % list2) # print("list3 = %s" % list3) def extend_list(va...
29b2d79e0d15a927714fcd2c51497a285bdb8927
akashgupta-ds/Python
/35. Relational Operators.py
1,035
4.40625
4
#------------Relational Operators ----------------- # >,<=,<,>= a='durga' #'durga' b='akash' print("a>b is ", a>b) # True based on A & D print("a>=b is ", a>=b) # True based on A & D print("a<b is ", a<b) # False based on A & D print("a<=b is ", a<=b) # False based on A & D # Based on unicode...
536bf0d00b9459447786b6977e39129cace4a97b
jiangshen95/UbuntuLeetCode
/ExcelSheetColumnNumber.py
350
3.515625
4
class Solution: def titleToNumber(self, s): """ :type s: str :rtype: int """ number = 0 for ch in s: number = number * 26 + ord(ch) - ord('A') + 1 return number if __name__=='__main__': s = raw_input() solution = Solution() pri...
c50242551fbbeef4081837eee0873855bf1a7523
evierkim/Battleship
/ComputerPlayer.py
9,803
3.5625
4
from Player import Player import random class ComputerPlayer(Player): def __init__(self): super().__init__() self.oHit = False self.shotHit = False # tells us if the current shot just made was a hit self.direction = 0 # 0 = below, 1 = left, 2 = above, 3 = right self.r = 0 ...
13f1a52e50e0df7b1baafbeb6ad7a57b0ee6df18
nickpascucci/AppDesign
/stats/stats.py
2,618
4
4
#! /usr/bin/env python """A simplistic statistical calculator.""" # Enable floating point division by default. from __future__ import division import math __author__ = "Nick Pascucci (npascut1@gmail.com)" def get_avg(seq): """Calculate the average of a sequence of numbers. Args: seq - A sequence of numb...
d5238770ae553f4280ca40770c571bf9e0da3fb7
saisahanar/python-letsupgrade-
/DAY 5 ASSIGNMENT/q1.py
458
3.734375
4
# [0,1,2,10,4,1,0,56,2,0,1,3,0,56,0,4] # Sort by increasing order but all zeros should be at the right hand side def pushzerotoend(arr,n): count=0 for i in range(n): if arr[i]!=0: arr[count]=arr[i] count+=1 while count<n: arr[count]=0 count+=1 r...
c7996a65a9df1646297541be99dcc18fc41f01a5
tomasmansson/king
/Nio liv importera lista.py
1,543
3.59375
4
#!/usr/bin/env python import random import mysql.connector as mariadb mariadb_connection = mariadb.connect(user='', password='', database='') cursor = mariadb_connection.cursor() cursor.execute('SELECT ord FROM hemligaord'); rows=cursor.fetchall() ordval_list=[] for i in rows: ordval_list.append(i[0...
c0b5872d30ff52af7060cd60a4cc28e1bb2de99d
sklin/dsp_hw
/hw1/c_cpp/cal_acc.py
501
3.625
4
#!/usr/bin/env python2 import sys if len(sys.argv) < 3: print "[Usage] cal_acc <result_file> <answer_file>" sys.exit(0) resultFile = sys.argv[1] answerFile = sys.argv[2] result = open(resultFile) answer = open(answerFile) result = [line.strip().split()[0] for line in result.readlines()] answer = [line.stri...
8eb8f5dc607d2ca7b9b8ee4a31750ddd8b59f8d7
glawrence/geoff-does-stuff
/python/collections/dict_intro.py
1,658
4.6875
5
# see https://docs.python.org/3/tutorial/datastructures.html # A dict or dictionary is made up of key/value pairs def collection_display(collection_name, example_collection): print("Processing:", collection_name, example_collection) example_dict = {6:"Six", 7:"Seven", 8:"Eight", 9:"Nine"} collection_display("Dic...
bd71e6ce622ab39becc0953741fdc8f87e992204
samuelcm/estrutura_decisao
/triangulo2.py
1,462
4.375
4
#Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar #se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, #se o mesmo é: equilátero, isósceles ou escaleno. #Dicas: #Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que #o terceiro; ...
a21d2175b1dcc5b4a69247aa9eff418ccac4927a
Vishakha05-02/Data-Type
/Tuple data type.py
978
4.59375
5
#!/usr/bin/env python # coding: utf-8 # In[ ]: #python data type---> Tuple---> immutable data type. we cannot change any itme of Tuple. # In[3]: #Empty tuple My_tuple = () type(My_tuple) # In[5]: My_tuple = ("apple", "banana", "cherry", "mango") print(My_tuple) # In[7]: My_tuple[1] # In[8]: print(My...
d8cc2a056be6396442ae127c2e6f5642f8b9aa75
Ahmed-Araby/CarND-LaneLines-P1
/Region_of_interest.py
2,541
3.59375
4
import numpy as np import cv2 def display(image): # ****************************************** will be removed ************************************************************ cv2.imshow("tmp" , image) cv2.waitKey(0) cv2.destroyAllWindows() return def ROI(image): """ - X is a column. - Y is ...
ddebb40448ed9aae9227f1bbf314eed34c25a594
Aasthaengg/IBMdataset
/Python_codes/p02987/s667881397.py
189
3.8125
4
s = input() s_list = [] for i in s: s_list.append(i) s_list.sort() if len(set(s_list)) == 2 and s_list[0] == s_list[1] and s_list[2] == s_list[3]: print("Yes") else: print("No")
b35adc1f50bed5ff30c3fa34e23a13f0ed668528
Loschmidt-constant/Physics-Simulation
/pendulum/pendulum_conserved.py
580
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 11 14:03:08 2019 @author: A.Nishimura """ from matplotlib import pyplot as plt import math k = 10 a = 0.1 b = 0 dt = 0.01 t = 0 theta = a phi = b J = 0 theta_list = [] conserved_list = [] t_list = [] while t < 10: t += dt theta += phi*dt phi += -k*math.si...
4333f426ece2f8d0c02293bf0f4847224baa1b66
pedrohov/Python-Pacman
/scripts/player.py
1,804
3.65625
4
# Disciplina : Linguagens Formais e Automatos # Aluno : Pedro Henrique Oliveira Veloso # Matricula : 0002346 from movingobject import *; class Player(MovingObject): def __init__(self, speed, name): # Instancia um novo objeto movel: MovingObject.__init__(self, speed, name); # Pontuac...
5e21879a8f86fb57441886e7f5cb8f234051c53a
AbdullahJatt/PythonLearning
/Assignment#1.py
763
4.1875
4
print("Hello world") print("My name is Abdullah") print("This is my first class") #Errors in print function # prin("Error") word T is missing # print'error' parenthesis missing # prit ("error") word print wasnot completed # print(error) commas missing # print"error" par...
af7cd72a56d76b7826077d4feedbbd8a77e6dae4
Lmineor/Sword-to-Offer
/bin/53.py
191
3.6875
4
def CountNum(s,tar): s.sort() count = 0 for cha in s: if cha == tar: count += 1 return count s=[1,2,3,4,5,3,2,3,2,3,2,33,2] tar = 3 print(CountNum(s,tar))
8f8dc35825b5ed75e64976f60ae078b3f2630492
intelligenerator/inundatio
/src/utils.py
870
3.59375
4
def clip(value, lower, upper): """Clip a given value between a lower and upper bound. """ return lower if value < lower else upper if value > upper else value def pad_bbox(box, padding=20, max_width=512): """Pad a bounding box. box: `list [`tuple` [int, int], `tuple` [int, int]] Bounding ...