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
c02541a3df4aeaeab10a662bcffc63bcc0280e2d
BrunoCA-xD/dataScienceMatathon
/DecisionStructures.py
1,994
3.921875
4
# 1 # x, y = [int(i) for i in input("Insira dois nunmeros separados por espaço").split()] # print(x if x > y else y) # 2 # x = float(input("Digite um numero")) # print("positivo" if x > 0 else ("negativo" if x < 0 else "neutro")) # 3 # x = input("Digite seu sexo[F/M]") # print("Feminino" if x == "F" or x == "f" else ...
216a77621325a3d917ff8932aceae0b241b6880d
ychingrain/660-Automated
/ConverTemp.py
749
4.28125
4
# Please modify the following program to now convert from input Fahrenheit # to Celsius def doConversion(): tempInFAsString = input('Enter the temperature in Fahrenheit: ') tempInF = int( tempInFAsString ) tempInC = round(((tempInF - 32) * 5/9),1) print("The temperature in Celsius is %f degrees." %(tem...
cf3a494426e87ad5d7a100433588122025966cfc
lgorham/CodingChallenges
/stock_prices.py
1,051
4.125
4
def get_max_profit(stock_prices): """ Takes in a list of stock prices, with the index position as the time of price, and returns what prices you should have purchased/sold the stock """ low_index = low_price(stock_prices) sell_price = high_price(stock_prices[low_index:]) buy_price = stock_...
9d232cd4c569c1e623ba42d6b7e49998835b7cc0
Roenski/Orbit-Simulator
/Scripts/tui.py
10,512
3.5
4
from simulation import Simulation from route import Route from state import State from solar_system import Solar_system from satellite import Satellite from satellite import State as SatState from unit import x_unit, m_unit, t_unit from read_planets import Read_planets ''' Text-based user interface. ''' class TUI: d...
4c61c366f361c22f4c25229e48305e06659a1298
neighlyd/algo_practice
/interview_questions/arrays_and_strings/string_rotation.py
654
4.21875
4
""" Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to is_substring (e.g. s2 = 'waterbottle' is a rotation of s1 = 'erbottlewat') """ def is_substring(s1, s2): """ Because s1 would be a rotation of s2, its edges would create the full substring when a...
8f2cc32eb800180b08015b222280be7ec3812211
yzl232/code_training_leet_code
/Gas Station.py
1,264
3.890625
4
''' There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas s...
e6049a7170cb840d7550523237e18b9918938bab
Jathy/MyWorkplace
/Python/MultiProcessing/test2_queue.py
436
3.5
4
# utf-8 # python3.5 import multiprocessing as mp def job(q): res = 0 for i in range(1000): res += i + i ** 2 + i ** 3 q.put(res) if __name__ == "__main__": q = mp.Queue() p1 = mp.Process(target=job, args=(q,)) p2 = mp.Process(target=job, args=(q,)) p1.start() p2.start() ...
5404dedc0070788fe63435201fa51ee1aeb0cde8
akjalbani/Test_Python
/Misc/Recon_tools/recon1.py
1,368
4.28125
4
''' This script allows the user to input a hostname or IP address, and then choose to either resolve the hostname to an IP, resolve an IP to a hostname, or scan for open ports. If the user chooses to scan for open ports, they can also specify a range of ports to scan. ''' import socket def get_ip(host): try: ...
1188e3cae06f3a5dc634195dc99f9df9be8ae498
jillnguyen/Python-Stack
/Fundamentals/type-list.py
865
3.875
4
list1 = ["my home", 19, -5, "is", 2, "old"] list2 = [2,3,1,7,4,12] list3 = ["Coding", "is", "fun"] def list_type(arr): my_sum = 0 string = "" counter_str = 0 counter_num = 0 for i in range (0, len(arr)): if isinstance(arr[i], int) or isinstance(arr[i], float): my_sum += arr[i] ...
ab5b54a893ac062e0b4ce3d14d1d35736e05c189
Shrutikabansal/DataStructureandAlgoritms
/DynamicProgramming/subset_sum_problem.py
1,786
3.578125
4
''' Subset Sum Problem Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not. Input: The first line contains an integer 'T' denoting the total number of test cases. Each test case consists of two lines. First-line contains 'N', represe...
0a75c48838893d8cf5e9da9d7f7c93fbbdc7da22
GomathiRajendran/Implementation-of-DataStructures-in-Python
/4. Queue/Circular Queue.py
1,911
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 15 00:56:22 2020 @author: R GOMATHI """ class CircularQueue(object): def __init__(self, limit = 10): self.limit = limit self.queue = [None for i in range(limit)] self.front = self.rear = -1 # for printing the queue def __str__(self)...
e075a07198d3e11a81d51716a8aa60b9b8674a52
joshua2352-cmis/joshua2352-cmis-cs2
/Functions.py
2,510
3.984375
4
import math def add(a,b): return a + b add(3,4) #subtracts a and b def sub(a,b): return a - b sub (5,3) #A function that multiplies and b def mul(a,b): return a*b mul(4,4) #A function that divides the float value 2.0 an 3 def div(a,b): return a/b div(2.0,3) ...
d881059257320174f9067fb552767b770c88e074
ruby3532/fun
/fun1.py
331
3.984375
4
def add(x, y): return x + y result = add(3, 4) print(result) def average(numbers): # avg = sum(numbers) / len(numbers) return sum(numbers) / len(numbers) # a = average ([1, 2,3]) # 若沒有回傳就無法將 function 的結果記錄下來 print(average ([1, 2,3])) print(average ([23, 32, 6])) print(average ([180, 34, 92]))
fe66933c7add3cf5f2ace475e1a2d7851c7ab4f9
kenfox0115/learning_python
/reading_and_writing.py
298
3.5
4
file_object = open("test_file.txt", 'w') file_object.write('Hello World') file_object.write("This is our new text file,") file_object.write("and this is another line.") file_object.write("Why? Because we can.") file_object.close() read_file = open("test_file.txt", "r") print(read_file.read())
85317cae89a56f64b288606955def81feda3ae79
codenstar/19a91a0507_Karthik_python_Assignments
/ass1.py
872
4.21875
4
''' 1. Write a Python Program to read the contents of a file and count the size of file then count how many times "CSE" is existed in the file. ''' import os file1 = open('SampleCSE.txt','r') data = file1.read() print('Details of the File is') print(data) size = os.path.getsize('SampleCSE.txt') print('Size...
33d02e6f552135e8c361b59eb63c1cb94c69803a
ahmetceylan90/firstApp
/Introduction/Lesson6/for8.py
236
4.0625
4
myList =["a","b","c","d","e","f","g"] for i in myList: newList =[] newList.append(i.upper()) print(newList) myList =["a","b","c","d","e","f","g"] yeniListe= [] yeniListe = [x.upper() for x in myList] print(yeniListe)
e42257695e2e6b46aee3961127f2bc31326b226c
himanshuhx/Python_Trees
/venv/Binary_Trees/InorderTraversal.py
835
3.640625
4
#Recursive approach class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: self.ans=[] def helper(root): if not root: return helper(root.left) self.ans.append(root.val) helper(root.right) helper(root) r...
a65f0b21e96f0ecd041abe8327a05ce2008efd68
Espfre/phonetic_test
/Main.py
1,327
3.828125
4
#!/usr/bin/python2 import WordlistCreator import Helper import Spelling import Stats def main(): random_word_fetcher = WordlistCreator.CreateWordList() random_word_fetcher.fileread("words.txt") helper = Helper.Helper() spelling = Spelling.Spelling() print("") print("") print ("welcome to ...
918fe0146beeba444cf4ad5e6eb1f0a9b8804809
XiaoxiaoMa95/Basic-Python
/2. Python基本图形绘制/2-实例2. 函数封装的Python蟒蛇绘制程序.py
474
3.546875
4
import turtle def drawSnake(radius, angle, length): turtle.seth(-40) for i in range(length): turtle.circle(radius, angle) turtle.circle(-radius, angle) turtle.circle(radius, angle / 2) turtle.fd(40) turtle.circle(16, 180) turtle.fd(40 * 2 / 3) turtle.setup(650, ...
bac6f882013fd25c2dab05f64f229f8978ef3ca3
mpreddy960/pythonPROJECTnew
/python_practice_all_remember.py
13,301
3.921875
4
a = (2,3,4,5,6) print(a) print(type(a)) string = ("prathapreddy",34,434,45,12,76,87,67,76,76,34,45,"confidence","aim","tecnology","goal","sad","happy") print(string) print(type(string)) print(string.count(76)) print(string.count(45)) print(string.index("confidence")) print(string.__len__()) print(str(string)) print(lis...
240df0c4dbce906dbb401d1327494a66094732f9
MarKuchar/intro_to_algorithms
/11_SearchingAlgorithms/linear_search.py
647
4.25
4
# Linear Search # - unsorted list of data # - search for the target in a linear manner (one by on) # - Time Complexity: O(n) # IN the worst case, it will take def linear_search(items, target): """ Return the index of the target in the items. Return -1 if the target not found :param items: a list of ite...
fda81c62300eedac67571613a26b1432bf2155bc
zhouzhousc/11python-
/130道代码/5.排序算法篇/插入排序.py
714
4.0625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: Carl time:2020/9/16 def insert(lst, index): """ 列表lst从索引0到索引index-1 都是有序的 函数将索引index位置上的元素插入到前面的一个合适的位置 :param lst: :param index: :return: """ if lst[index - 1] < lst[index]: return tmp = lst[index] tmp_index = index ...
2c1bc2b1e87679c0596f7d1f03ca3a722557fca3
shoya123/my-basic-algorithms
/python/mergeSort.py
722
3.640625
4
# マージソート import math def margeSort(arr): def m(head, tail): if head < tail: mid = math.floor((head + tail) / 2) m(head, mid) m(mid + 1, tail) l = arr[head: mid + 1] r = arr[mid+1: tail+1] k = head while len(l) >...
1f554520eac7554142b47105e74d16f8f1eec844
Mellodica/AprendendoPython
/AulaSenai26.py
893
4.15625
4
""" a) Converta a temperatura de Celsius para Fahrenheit (0 °C × 9/5) + 32 = 32 °F b) Converta a Temperatura de Fahrenheit para Celsius (32 °F − 32) × 5/9 c) Retorne verdadeiro se o número for PAR e falso se o número for IMPAR d) faça um programa que peça as 4 notas bimestrais e mostre a media e) faça um programa que ...
bca26633acecbbe7ef2d798112fba852dd53a826
aymanesarrar/baby-python-steps
/file.py
855
3.828125
4
import os # works like pwd command print(os.getcwd()) # listing files inside a directory print(os.listdir('/mnt/c/Users/hp/Desktop/react-projects/REACT/crash/python_training')) # os.chdir() will change the current working directory # os.path.abspath() returns an absolute path form of the path passed to it # os.path.rel...
5c6a3eb0c0dcf15f2673e7ec4cce3ba534da66cf
danapaduraru/Python-Programming
/Lab_1/ex_6.py
483
4.5625
5
# Write a function that converts a string of characters written in UpperCamelCase into lowercase_with_underscores. def convert_string(string): new_string = "" for letter in string: if letter.islower(): new_string += letter else: new_string += "_" new_string ...
6b7e9aa2830abbe76a382230ffb9f4e539a37dfb
joaquinhojman/Simulacion-TP1
/Ej4.py
3,886
3.609375
4
#Para la siguiente funcion: #A) Definir su funcion de densidad de probabilidad #B) Calcular y graficar la funcion de probabilidad acumulada y su inversa #C) Utilizando el generador de numero aleatorios implementado en el item b # del ejercicio 1, genere numeros al azar con la distribucion propuesta #D) Realice los g...
ed036e01a07a045b48b2980aa81c34140fbb7f62
webfanrc/algorithms-greedy
/week #3/test.py
1,353
3.59375
4
class Node: def __init__(self,freq): self.left = None self.right = None self.father = None self.freq = freq def isLeft(self): return self.father.left == self def createNodes(freqs): return [Node(freq) for freq in freqs] def createHuffmanTree(nodes): queue = ...
3591687661442fa2249dd169380ce55f47f60796
OnionXDD/Python-study
/pycook/ch1/18_namedseq.py
1,304
4.21875
4
"""1.18 Mapping Names to Sequence Elements 问题: 通过名字匹配序列元素 解决方法: 使用collections.namedtuple() """ from collections import namedtuple Subscriber = namedtuple('Subscriber',['addr', 'joined']) sub = Subscriber('jonesy@example.com', joined='2012-10-19') print(sub.addr) print(sub.joined) addr, joined = sub Sto...
7ea27b712e9f3bf4faedd2dbf71d2dd720123209
Aries5522/daily
/2021届秋招/leetcode/拓扑排序/合并区间.py
292
3.5625
4
data = [[1, 'B'], [1, 'A'], [2, 'A'], [0, 'B'], [0, 'a']] #利用参数key来规定排序的规则 result = sorted(data,key=lambda x:(x[0])) print(data) #结果为 [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')] print(result) #结果为 [(0, 'a'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A')]
e5157cc18ceacf0502d1ca4b9b3932a0fdf1fc46
Alex-dar-g/Python_for_courses
/task_9.2/task_9_3.py
1,050
4.5625
5
"""Создать декоратор для функции, которая принимает список чисел. Декоратор должен производить предварительную проверку данных - удалять все четные элементы из списка.""" import functools from typing import Optional def decorator_for_remove_even_numbers(func): """Function for remove even numbers""" @functools...
03113abe3c139130d1b181b465ac7e37664cd687
masterziedis/python
/assertion.py
370
3.890625
4
# def add(x, y): # assert x > 0 and y > 0, "Both most be pos" # return x + y # print(add(2,10)) # print(add(2,-10)) def eat_junk(food): assert food in [ "alus", "pica", "kebabai", "saldainiai" ], "food must be junk food!" return f"NOM NOM NOM I am eating {foo...
593cb178ab31bfabbd1011105c704c30eae21d73
Kayem023/Known-Password-Attack
/Code/DBUtil.py
1,502
3.875
4
import sqlite3 class Database: def __init__(self): self.db = "Auth.sqlite3" def addUser(username,password): try: conn = sqlite3.connect('Auth.sqlite3') c = conn.cursor() sql ='''INSERT INTO AUTHENTICATION(Username,Password) VALUES(?,?)''' ...
f56ab788bcc5212bed12f202e16d79be19aa263b
Houndof/reporepo
/diccionario.py
806
3.609375
4
""" diccionario{} nombre_de_diccionario={"nombre clave":"valor"} #lista persona = ["marce", 32, "programador"] #diccionario dic_persona = {"nombre":"Marce", "Edad":32} dic_persona["Edad"] """ #crear un diccionario persona con las claves nombre, edad, estatura e imprimi cada uno de los valores de las claves # un pr...
29ae7bb98bc10522ad3fca6f9f2ee6e6d9119dc1
Makhanya/PythonMasterClass
/Functions2/kwargsexercise.py
547
3.734375
4
def combine_words(word, **kwargs): if kwargs: if "prefix" in kwargs: for x in kwargs: return kwargs[x]+word if 'suffix' in kwargs: for y in kwargs: return word+kwargs[y] else: return word print(combine_words("child")) # 'child' p...
4a2b9a07a6cb754843abcc4e4ba493d2eb5cda00
ksheetal/Python-code
/sort_min_index.py
1,926
4.25
4
def find_index(list1, lower_bound, upper_bound,mini_index): ''' Objective : to find the index of minimum number of sublist of list intput parameters : list1 : given list lower_bound : starting index of given sublist upper_bound : last index of given sublist mini_index : minimum index of give...
3e8a96cbb37ea5f4b1229faa5afc96cd7285f8c5
Akshay-agarwal/DataStructures
/LinkedLists/reverse.py
407
3.71875
4
from singlell import Singlell def reverse(n): next = None prev = None current = n.head while current: next = current.next current.next = prev prev = current current = next n.head = prev s = Singlell() s.insert_head(2) s.insert_head(3) s.insert_head(4) s.insert_h...
955bd4d079061c48c6fca854d0d39ba8c4b17fa7
sea-of-fog/python-projects
/chapter-2/guess-the-number.py
385
4.09375
4
# a guessing name import random as rand maxi = 20 correct = rand.randint(1,maxi) cnt = 0 while True: cnt += 1 guess = int(input("What is your guess? ")) if guess < correct: print("Your guess is too low") elif guess > correct: print("Your guess is too high") else: break pr...
5efcef7068f33c4edba73cf0d5b0a05ae7a72e08
SafonovMikhail/python_000577
/000560SoloLearnPy01/000560_02_12_SimpleCalc_20190917.py
2,079
4.03125
4
#000560_02_12_ex01_SimpleCalc_WhileQuit.py # рассмотрим главное меню # while True: # print ('Options') # print ('Enter "add" to add two numbers') # print ('Enter "subs" to substract two numbers') # print ('Enter "mult" to multiply two numbers') # print ('Enter "div" to divide two numbers') # print ('Enter "end"...
fc2ec9a3fba54d2d3049efa15971b44d22b668bb
osvaldoxdjr/python-execises-portuguese
/029_exe2.py
362
4.21875
4
""" Escreva um programa que recebe uma lista de números até que seja dada a entrada -1, e depois imprima todos os números pares da sequência que são pares. """ numeros = [] numero = int(input("Digite o número: ")) while numero != -1: numeros.append(numero) numero = int(input("Digite o número: ")) for num in numer...
61e2a4fa8c1a70fee78937fabac08ad29b588a07
disaisoft/python-course
/project2/app.py
1,159
3.875
4
""" Te proponemos escribir un programa en Python que nos permita calcular la ganancia de una criptomoneda (Nombre y Cantidad), si ésta se negocia por una cantidad de días indicada por el usuario y a una ganancia fija indicada también por el usuario. Al terminar, el programa debe indicar la ganancia en cantidad de ...
6407b9bcd92c22d4e11497aa51d4327f2767c20c
rjshk013/pythonlearning
/checkdirectory_fileexists.py
439
3.921875
4
# Python program to explain os.path.exists() method # importing os module import os # Specify path path = '/usr/local/bin/' # Check whether the specified # path exists or not isExist = os.path.exists(path) print(isExist) # Specify path path = '/home/ubuntuclient/Desktop/f...
74c1e47e1b037a70c5a29e9ca1fb3c87505c9cea
c940606/leetcode
/518. 零钱兑换 II.py
724
3.59375
4
class Solution: def change(self, amount, coins): """ :type amount: int :type coins: List[int] :rtype: int """ lookup = {} def helper(target,coins): if target == amount: return 1 if target > amount: return...
19ea61ed8bbeaf7b7b5d072ebb23ae8800033f42
CedricKen/Python-GUI
/Others/Change Count.py
5,367
3.765625
4
import tkinter from tkinter import ttk root = tkinter.Tk() root.title("Change Counter") #separator line ttk.Separator(root).grid(row=2, columnspan=5, sticky="ew") #Input Integers dollarCoins = tkinter.IntVar() halfDollars = tkinter.IntVar() quarters = tkinter.IntVar() dimes = tkinter.IntVar() nicke...
f8ffce9ea4785197e450a151987f635dfeffa975
Siddhant-tec/30_Days_of_Code_HackerRank
/q23_day26.py
628
3.734375
4
return_date = input().split() return_day = int(return_date[0]) return_month = int(return_date[1]) return_year = int(return_date[2]) due_date = input().split() due_day = int(due_date[0]) due_month = int(due_date[1]) due_year = int(due_date[2]) def compute_fine(): fine = 0 if return_year > due_year: fi...
8c05f5c20923f3852f130806e61aa8388485602d
amruthasree1998/TCS-DIGITAL-SOLVED
/combination.py
580
4
4
#Write a program to print all the combinations of the given word with or without meaning (when unique characters are given). def convertToString(a): k="".join(a) #join the elemets of list with "no space" print(k) def permute(a,first,last): if(first==last): convertToString(a) else: f...
a60e4d1f68b794ec9e67bc18e6a5c3c3a4776b11
MukeshDubey1420/Students_Doubts_Solved
/dictionary_problem.py
233
4.1875
4
dict = { "MUKESH DUBEY":29, "SANT":18, "ISHAN":56, "ROHIT":27 } print "welcome to the dictionary" key=raw_input("ENTER KEY TO FIND VALUE :") if key in dict : print "VALUE IS :",dict[key] else: print "not found"
f4d7dd6f3767fea124175873918ca3de4c2709b0
Gwebbers/alien-invasion
/alien.py
2,699
4.15625
4
import pygame from pygame.sprite import Sprite class Alien(Sprite): """A class to represent an alien""" def __init__(self, tou_settings, screen): """Initialize the alien and starting position""" super(Alien, self).__init__() self.screen = screen self.tou_settings = tou_settings...
79e749b618ceb5fde3f82e241ca7e075fb374734
hulaba/GeeksForGeeksPython
/Greedy/WWP.py
564
3.625
4
class WWP: @staticmethod def run_wwp(input_sequence, maximum=6): line = "" words = input_sequence.split(" ") for word in words: if len(line + word) < maximum: line += "{0} ".format(word) elif len(line + word) == maximum: line += wor...
e7504e0fa04a58e92a0370641ecfaeea0f268e7a
Honobono/udacity_homework
/programming_foundations/mini_project_2.py
461
3.765625
4
# Mini project: draw flower shapes import turtle window = turtle.Screen() sarah = turtle.Turtle() sarah.speed(10) sarah.color("blue") for parallelogram in range(60): #repeat 10 times sarah.forward(100) sarah.left(60) sarah.forward(100) sarah.left(120) sarah.forward(100) sarah.left(60) ...
6df540e2a115b1ba46d0a998127aa342267ea60d
hoik92/Algorithm
/algorithm/work_7/array_rotation.py
711
3.734375
4
def rotation(m): global N result = [[0] * N for _ in range(N)] for i in range(N): for j in range(N): result[j][N-1-i] = m[i][j] return result for tc in range(1, int(input())+1): N = int(input()) m = [0] * N for i in range(N): m[i] = list(map(int, input().split())...
04a334b1af1d982dfcf0a6e8ac8a46caf2f59eca
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_053.py
491
4.125
4
def main(): height = int(input("Please enter the starting height of a hailstone: ")) if(height == 1): print("Hail stopped and height 1") while( height > 2): if((height % 2) == 0): height = int(height/2) print("Hail is currently at height", height) if((height %...
b2181b3876eeab3f75d583495258d9323c7a8f45
Yoasted/python
/webaccess.py
2,457
3.734375
4
#C:\Documents\coding #webaccess.py #author: Yoast #version: 1.01 #last accessed: 14/10/15 #Description: Program used to check whether a website can be accessed, so that it can be scraped. from bs4 import BeautifulSoup import requests def menu(): menuop = input(""" Welcome to the WebCrawler program. What would you...
322dc89d72fc9ac4b621a5b6891e790da3139613
AndrewAct/DataCamp_Python
/Introduction to Deep Learning with Keras/2 Going Deeper/05_Prepare_Your_Dataset.py
1,823
3.984375
4
# # 8/9/2020 # In the console you can check that your labels, darts.competitor are not yet in a format to be understood by your network. They contain the names of the competitors as strings. You will first turn these competitors into unique numbers,then use the to_categorical() function from keras.utils to turn these n...
2323a6bd824d4444883c50a016414031b1766df0
kazhiryu187/myProgramming
/pythonut.py
738
4.15625
4
# Get numbers from user num1, num2 = input('enter 2 numbers: ').split() # Converts strings to regular numbers num1 = int(num1) num2 = int(num2) # Adds values and stores in sum sum = num1 + num2 # Subtract values and stores in difference difference = num1 - num2 # Multiply values and stores in product ...
0ad5694022b0cf619376022e52b65f36146826bf
pbchandra/Top-Gear-projects
/problem9.py
413
3.796875
4
def fun_args(*arg): a = complex(arg[0], arg[1]) b = complex(arg[2], arg[3]) c = a + b print("\n Addition of two numbers is", c) c = a - b print("\n Subtraction of two numbers is", c) c = a * b print("\n Multiplication of two numbers is", c) c = a / b print("\n Division ...
7bb1acb97bd65934f77fcc60d6f4616ab12aa28a
kamalnainx/PYTHON
/python 2pm weekend April 2021/py26_try_Except.py
1,185
4
4
# x=10 # print(x) # print(x) # x=10 # try: # print(x) # except: # print("x not found.") # try: # print(x) # except NameError: # print("var name is not found") # try: # print(x) # except NameError: # print("var name is not found") # except: # pri...
4e6a417b9e959baf99bddf0aa8abc13cb7d32f9c
iblub1/Computer-Vision-Exercises
/Übung4/assignment4_solution/problem2.py
6,277
3.6875
4
import numpy as np def cost_ssd(patch1, patch2): """Compute the Sum of Squared Pixel Differences (SSD): Args: patch1: input patch 1 as (m, m, 1) numpy array patch2: input patch 2 as (m, m, 1) numpy array Returns: cost_ssd: the calcuated SSD cost as a floating point value ...
095be8e95ef0c7d2a6a00e792fceb8794da8b0f0
Eustaceyi/Leetcode
/189. Rotate Array.py
2,000
3.828125
4
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. My solution, O(n) time O(k) space """ if not nums: return k = k % len(nums) temp = nums[len(nums)-k:] nums[k:] = n...
7837830edfc0abac7bbbd21fd265927b371f7296
chaksamu/python
/venv/MOLOR.py
757
3.609375
4
###MOLOR means class Student: def __init__(self): print("Auto method") def add(self,a,b): #self.a=a #self.b=b #s=self.a+self.b s=a+b #print(s)1 return s s1=Student() #s1.mlo(2,3) 1 print(s1.add(2,3)) class Stud: def __init__(self): prin...
38725689a415415edeeb0968657c111ceba0af2c
HyunIm/Baekjoon_Online_Judge
/Problem/8595.py
188
3.609375
4
n = int(input()) data = input() sum = 0 tmp = '0' for i in data: if '0' <= i <= '9': tmp += i else: sum += int(tmp) tmp = '0' sum += int(tmp) print(sum)
f13a3383432b5ffc8a2cee9ab195ea6856f608a9
henry232323/async-recipes
/async-recipes/future.py
4,275
3.90625
4
""" Three classes. The First, a Future will wait until it's result is set or an error is set If the result is set, it will return the result. If an error is set, it will raise the error. The Second, a Task wraps a coroutine or another Future, and will pass everything forward until it is done. The...
c0798e7fc951c936eaa9bfe130efc9f417fe23e0
bexiturley/pands-problem-set
/plot.py
1,116
4.09375
4
# Solution to problem 10 # Rebecca Turley, 2019-03-21 # plot.py # import the module matplotlib.pyplot and bind it to the name plt import matplotlib.pyplot as plt import numpy as np # return evenly spaced values up to 5 x = np.arange(5) # as I only gave one a single list or array to the plot() command, matplotlib as...
53c39f6b5f1eab9d15148339c85d3fd128d94a89
T-Dogg-PO/cs50_psets
/piglatin.py
316
3.8125
4
from sys import argv def main(): print(f"{pig_it(argv[1])}") def pig_it(text): #your code here text_list = text.split() for word in text_list: if word.isalpha(): word = [word[1:] + word[:1] + 'ay'] else: word = word return (' '.join(text_list)) main()
03077a1f7aa8cb1371010378900478efe892cc8f
Aishu67/aishwarya
/amstrong.py
119
3.8125
4
num=input() s=0 for i in range(len(num)): s+=pow(int(num[i]),3) if str(s)==num: print("yes") else: print("no")
ea6503eeca340102a3abe465f80723b231af4a4a
dstark85/mitPython
/midterm/closest_power_open.py
370
3.546875
4
def closest_power(base, num): ''' base: base of the expoenential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base ** exp is closest to num Note that the base ** exp may either be greater or less than num In case of a tie, return the smaller...
22129a393732c8b45585729458d94aac83971883
glennpinkerton/csw_master
/csw/python/course/for_loops.py
1,329
4.21875
4
# For loops act on iterators. Iterators an be a bunch of different # things: lita, ranges, tuples (read only), functions that use the # yield statement to pause and send back an intermediate result. # For loops are a big part of any programming language. Only a tiny # bit of them is shown here. # Looks like se...
554d424c058971ec288c5b1fe13001ea79a6bbbc
javierunix/ca_computerscience
/CS102/TreeTranversal/tree.py
514
3.71875
4
from collections import deque class TreeNode: def __init__(self, value): self.value = value self.children = [] def __str__(self): stack = deque() stack.append([self, 0]) level_str = "\n" while len(stack) > 0: node, level = stack.pop() if level > 0: level_str += "| ...
d92e30ef6585c888cf6e2d2bfb7ac361de4781a4
djtongol/python
/file_extractor/fileExtractor7.2.py
957
4.09375
4
# Reads, extract, and compute data from a file def confidenceAverage(): #gets user input fname = input("Enter file name: ") try:fh = open(fname) except:fh = open('mbox-short.txt') count=0 digits=[] for line in fh: ...
f382471e2f56c8a4588ac3a8b4a862c78ca160eb
katya1242/PythonScripts
/CodeWars/CountingDuplicates.py
1,049
4.25
4
#Write a function that will return the count of distinct case-insensitive alphabetic characters # and numeric digits that occur more than once in the input string. The input string can be # assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. ###### Example # "abcde" -> 0 # no ch...
fb85f45182eec8f8a67073a2b561f3882677c5cd
morgankb17/cis122
/Week 6/cis122-assign06-random.py
1,090
3.90625
4
''' CIS 122 Summer 2020 Assignment 6 Author: Morgan Bartlett Credit: Description: Program that reads a .txt file and prints the amount of numbers, any comments, the sum of the numbers, and their average. ''' import math import os from cis122_assign06_shared import pad_left, pad_right while True: user = input("Ente...
5c1c8c69f9fd199cb0f5c72b46cbff82f4cd7456
evgeniykruglov/python_mediasoft
/homeworks/revert.py
679
4.03125
4
#Написать программу, которая берет словарь и меняет местами ключи и значения. import pprint dictionary = dict(key1='value1', key2='value2') print ('Before revert:') pprint.pprint (dictionary, width=30) # Создаем список ключей keys = list() for i in dictionary.keys(): keys.append(i) # Меняем местами ключ и значие...
ba8d0448590dd3856f911b406d96a834190d3a2c
porregu/unit11
/breakout.py
8,329
4.34375
4
#Guillermo Porres 1/17/2020 the purpose of this program is the midterm project for intro. computer science and learn how to build a breakout gae with all the knoledged learned in the semester. import pygame, sys from pygame.locals import * import brick import paddle import ball def GAME_OVER(main_surface): ''' ...
0331f14827f588fbd89bded14b46e5e323c1f51b
LorenzoVaralo/ExerciciosCursoEmVideo
/Mundo 2/Ex071.py
762
4.09375
4
#Crie um programa que sinule o funcionamento de um caixa eletronico. No inicio, pergunte ao usuario # qual será o valor a ser sacado(numero inteiro) e o programa vai informar quantas cedulas de cada # valor serão entregues. Obs. Considere que o caixa possui cedulas de R$50, R$20,R$10 e R$1 print('=' * 30 + '\nBANCO...
752ea643de5e23e66b24c47615e2c0568f71ba02
tjkhara/notes
/python/courses/colt_steele/20_lambda_functions/12_any_and_all.py
137
3.5
4
print(all([0,1,2,3])) print(all([char for char in 'eio' if char in 'aeiou'])) print(all([num for num in [4,2,6,8,10] if num % 2 == 0]))
23c9a77b6e61cd459ee413e057b722cb96f6720f
PauloVilarinho/algoritmos
/atividades_aleatorias/ProblemaMilena.py
285
3.765625
4
altura = float(input("Digite sua altura")) peso = float(input("Digite seu peso")) imc = peso/(altura**2) print("Imc = %.2f" %imc) if imc > 40 : print("paciente possui obesidade grau 3! porfavor tomar as providencias!") else : print("ta de boas pode comer seu biscoito negresco!")
4cf9eaa31dde1a2ad564e48a2cb5c465194ad700
Awesomechick4242/ScienceSummerCamp-Files
/untitled-2.py
2,098
4.09375
4
def main(): gender = input("Male or Female (m/f)") if (gender == "m" or gender == "f"): print("") if gender == "m": malestory() elif gender == "f": femalestory() else: print("Invalid Selection") def malestory(): #code for males...
4831acc0b14068f194fc808bb89dc980710f8b55
nadavWeisler/IntroToCS
/IntroToCS_ex11/ex11.py
13,226
3.671875
4
############################################################# # FILE : ex11.py # WRITER : Nadav Weisler , weisler , 316493758 # EXERCISE : intro2cs ex11 2019 # DESCRIPTION: ############################################################# from itertools import combinations class Node: def __init__(self, data, pos=Non...
d8f3dfab2dfd830080d66012f9964cebca6ac129
yuumiin/Algorithm
/BFS/BFS.py
742
3.546875
4
""" BFS 기본 코드 1. 탐색 시작 node를 큐에 삽입하고 방문 처리 2. 큐에서 node를 꺼내 해당node의 인접node 중 방문하지 않은 노드를 모두 큐에 삽입하고 방문처리 3. 2번 과정 반복 """ from collections import deque def bfs(graph, start, visited) : queue = deque([start]) visited[start] = True # 큐가 빌 때까지 while queue: v = queue.popleft() print(v, end...
6db4ede608f8a6b9e6fde323d7a4f885944c918a
xxweell/exerciciosPython
/ex022.py
744
4.125
4
nome = str(input('Digite seu nome completo: ')).strip() # metodo pra excluir os espaços da string print('Analisando seu nome...') print('Seu nome em maiúsculas é {}'.format(nome.upper())) print('Seu nome em minúsculas é {}'.format(nome.lower())) print('Seu nome tem ao todo {} letras.'.format(len(nome) - nome.count(' '...
606cc51fb250a4468a0235f677c7f5c4b67ddbbb
Chalmiller/competitive_programming
/python/leetcode_top_interview_questions/dynamic_programming/unique_paths.py
1,074
4.09375
4
from typing import * import unittest class Solution: def uniquePaths(self, m: int, n: int) -> int: """ Task: How many unique paths are there to guide the robot from the start to finish Intuition: I think this is a backtracking problem, but I'm unsure of its implementation Algorithm...
8d07202a09f112b6fb7a71041ed4ef4e7a180fd7
vishnuchauhan107/pythonBasicToAdvance
/python_notes_by_vishnu/vch/string_program/find().py
231
3.78125
4
s="Learning Python is very easy" print(s.find("Python")) #9 print(s.find("Java")) # -1 print(s.find("r"))#3 print(s.rfind("r"))#21 s="durgaravipavanshiva" print(s.find('a'))#4 print(s.find('a',7,15))#10 print(s.find('z',7,15))#-1
7717277e30c37b88e04164653eb323453f0bf6ab
juyingnan/PythonScripts
/Midterm1.py
2,226
4.09375
4
#!/bin/python # Yue Chen import string def function_a(): aSentence = raw_input("Please input a sentence: ") vowel = 0 consonant = 0 vowel_list = 'aeiouAEIOU' consonant_list = 'qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM' for character in aSentence: if character in vowel_list: ...
72378310169ad5c9926f0daf6ea54f998d544a1e
doomnonius/advent-of-code
/2020/day17.py
2,594
3.65625
4
from typing import Dict, List, NamedTuple, Set from itertools import combinations, product ## Don't need to make a whole plane, with empty spots 'n shit. Can do like I did in day 24. class Coord3d(NamedTuple): x: int y: int z: int def neighbors(self): return {Coord3d(x[0], x[1], x[2]) for x in product([-1, 0,...
3a127df5b683628b85475928de7ccb4c9f3ef8bd
carlguo866/TechX-ComputerVision
/classes/day1to5/lab3.py
3,682
3.609375
4
import numpy as np import matplotlib.pyplot as plt import math # convert points from euclidian to homogeneous def to_homog(points): """ your code here """ points_homog = np.zeros([points.shape[0]+1,points.shape[1]]) points_homog[:-1,:] = points points_homog[-1,:] = 1 #print(points_homog) ...
f760d009944d89ae9f179e449d026422b205b9c3
catchonme/algorithm
/Python/242.valid-anagram.py
185
3.53125
4
#!/usr/bin/python3 class Solution(object): def isAnagram(self, s, t): return sorted(s) == sorted(t) sol = Solution() res = sol.isAnagram("anagram", "nagaram") print(res)
ab9a926ac07dda4e00dfd4ccdd2719439aa31330
kmarden1/Python-2021
/term 3/Whatever.py
1,382
4.0625
4
from tkinter import * class Application(Frame): def __init__(self,master): super(Application, self).__init__(master) self.grid() self.create_widgits() def create_widgits(self): self.lbl = Label(self, text="Enter password to get access to the meaning of life!") self.lbl....
0be2affddcd6baf6f0b59a66eb34412de3da5783
CarlosAntonioITSZ/Curso-Python
/Listas/Exercise2.py
408
4.28125
4
#Exercise2 ''' Create a list and initialize it with 5 character strings read by keyboard. Copy the items from the list into another list but in reverse order, and display their items on the screen. ''' #@CarlosAntonio list1=[] for i in range (0,5): list1.append(input("Enter a character: ")) list2=[] list2....
371e414e96ca4807b3f5495b9bc45ec25c20780a
korzeniowska18/Python-Exercises---WSB-Software-Tester
/My_Fun_with_Python/zapisy_pliku.py
2,276
3.5625
4
#można użyć różne permissions: w, r+(read and write), a(append) MojPlik = open("przykladowy.txt", "w") print("Nazwa pliku " + MojPlik.name) print("Permissions " + MojPlik.mode) MojPlik.write("Lista na zakupy:\nChlebek: 1\nMleko: 2\nSzynka: 1 kg") MojPlik.close() MojPlik = open("przykladowy.txt", "r") print("Czytam...
4c09b4711595f0ab3847130eaad615e4284af33f
johnroge/100days
/movie_data.py
1,138
3.734375
4
#!/usr/bin/env python3 """ use defaultdict for movie database """ import csv from collections import defaultdict, namedtuple, Counter vie_data = 'https://raw.githubusercontent/com/pybites/challenges/' \ 'solutions/13/movie_metadata.csv' vie_csv = 'moves.csv' Movie = namedtuple('Movie', 'title year score')...
659d72f5b8a2186fae09abda17adf292beb34e66
MukeshDubey1420/Students_Doubts_Solved
/regular expression2.py
366
3.9375
4
from re import match , search , sub str='My name is Python ..... Hello everyone ' if match('name', str): print ' found using match function' else : print ' not found' if search('name', str): print ' found using search function' else : print ' not found' str="my name is sant" st=sub(' ','-',str) str...
e1051349af40553b9fc5138c352dff892afe39d4
agate-agate/learnpython_homeworks
/homework2/2_files.py
1,415
3.84375
4
""" Домашнее задание №2 Работа с файлами 1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0 2. Прочитайте содержимое файла в перменную, подсчитайте длинну получившейся строки 3. Подсчитайте количество слов в тексте 4. Замените точки в тексте на восклицательные знаки 5. Сохраните ре...
752383f19c4db3e0fb30c49554f402499ed7a4a4
alexjustbarcelona/ap1-codis-2017-2018
/2017-10-04 Més Python/p2.py
452
3.5
4
from jutge import read # La funció maxim, donats dos enters retorna un enter que és el seu màxim. def maxim(a, b): if a > b: return a else: return b # La funció maxim3, donats tres enters retorna un enter que és el seu màxim. def maxim3(a, b,c): return maxim(maxim(a, b), c) # Programa...
aa7dc4da3c5e4fa8278df12b3851fe87a0d564e7
Supercodero/PyCrashCourse
/PyUnitPractice/test_cities.py
442
3.65625
4
import unittest from city_functions import city_function class CityTestCase(unittest.TestCase): def test_city_country(self): format_name = city_function('santiago','chile') self.assertEqual(format_name,'Santiago,Chile') def test_city_country_population(self): format_name = city_functio...
96b4db875f6fb7b9484fff8592aebfbe59e47a1a
lucaskf28/520
/aula2/quad.py
215
3.84375
4
#!/usr/bin/python3 # quad = lambda x: x*x # for k in range(10): # print(quad(k+1)) # for i in range(10): # print((lambda x: x*x)(i+1)) quadrado = [(lambda x: x*x)(y+1) for y in range(10)] print(quadrado)
32b167836d3ab3af590aa974a326853b03632cc9
aliciaberger/P2_SP20
/Notes/NotesB/import_me/new_pandas.py
508
3.515625
4
import random import pandas as pd # lists > dicts > series/dataframes # Pandas series (1d array) s = [random.randrange(100) for x in range(10)] my_series = pd.Series(s) print(type(my_series)) print(my_series) # Pandas DataFrame (2d spreadsheet (kinda)) # make from dict d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]} df ...
4f4950a895cb497b80be326588a66795af437245
bonjonson/course-67
/week 3/3377-2.py
63
3.546875
4
from math import pi r = float(input()) p = 2 * pi * r print(p)
21cc351ad3ef6871fd5171f3ba3cc80c568a6b6f
xuxiaoyu89/python
/basic_functions_and_algorithms/detect_cycle.py
731
3.671875
4
# detect cycle in a directed graph ''' idea: use DFS to travel through all the nodes, and mark the one visited. if we travel to a visited one ''' from collections import defaultdict def solve(n, prerequisites): visited, stack, m = set(), set(), defaultdict(list) for i, o in prerequisites: m[i].a...
602c142b560902138f0406f6eb316844fb586cca
samcaek/classification
/utils/number_checker.py
721
3.78125
4
class NumberChecker: """ Utility class to check numbers. """ @staticmethod def is_float(value): """ Checks if the value is a float. :param value: The value to check. :return: True if the value is a float, False if not. """ try: float(valu...
7411b82055cf80b9f25079fbc88631711157f126
thiagovictoria/Coursera
/(01)_PYTHON USP/SEMANA_02/(04)_Exercícios de Programação/05_Praticar_tarefa_de_programação_(Lista_01)_03.py
114
3.96875
4
num = int(input("Digite um número inteiro:")) dezena = (num//10)%10 print ("O dígito das dezenas é", dezena)