blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f26595359090e2d0ff9962e9ee039aef9ff3e855
nshiroma/HotWheelRaceTrack
/HWslowmotion.py
1,699
3.546875
4
#!/usr/bin/python # Slow Motion # For this to work you need to have MP4Box installed # You can do this by using: # sudo apt-get install gpac import picamera import subprocess # To be able to use MP4Box from within this script import time ###################################### # Config data ###########################...
98b17e547f7349f99beff0c96131e9fc0e539af6
adibl/corsera_algoritems
/my_solutions/1-algorithmic-toolbox/4-divide-and-conquer/majorityElement.py
925
3.5
4
n = int(input()) arr = [int(x) for x in input().split()] def count(arr, var, start, end): count = 0 for i in range(start, end + 1): if arr[i] == var: count += 1 return count def majority(arr, start, end): if start + 1 == end: if arr[start] == arr[end]: return a...
a3112720df571598431b76eeb84fd4dd5ccb42a1
Pooja165-chintha/FST-M1
/python/Activity7.py
129
3.859375
4
number= list(input("Eneter number in the list").split(",")) sum=0 for n in number: sum+=int(n) print('Sum is : ',sum)
08e24ac0221c3921911b6865632256d308b6d468
Pooja165-chintha/FST-M1
/python/Activity8.py
201
3.734375
4
number_list= list(input("Enter list of numbers: ").split(",")) firstElement=number_list[0] lastelement=number_list[-1] if firstElement==lastelement: print(True) else: print(False)
940c2d48d75a124bac621031f9acddae87047ef4
brandondudley1775/ip_range_separator
/ip_range_separator.py
6,234
3.71875
4
#!/usr/bin/python import sys import string #Reads multiline files with CIDR notation or dash-separated IP ranges #and outputs one or more files with one IP address per line. This script #assumes that all IPs are within real ranges (e.g. not 192.168.257.23) #and that IP ranges are either line separated, comm...
3a10731baf5ba240ebe9de8b835f10df1a0f77dc
mforoni/codility
/codility-python/lesson1/binary_gap.py
1,892
4.03125
4
import util.strings def solution(N): """ A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. Th...
91392d09e8e07269d2a14c5f1c2b645ce36affe8
Who8MyLunch/euler
/problem_003.py
1,978
3.75
4
from __future__ import division, print_function, unicode_literals """ Largest prime factor ==================== The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? Notes ===== I have an idea, but I think it will be more brute force than elegant. Set value...
027be3101bde23ee730765caad9e8007308fa36e
tm11ajn/advent-of-code-2020
/day-6/puzzle-1/code.py
845
3.65625
4
import sys import re def main(): # Read file file_name = sys.argv[1] List = [] done = False with open(file_name, 'r') as file: while not done: string = "" while True: line = file.readline() if not line: done = True break if line == "\n": ...
305c682a8837748b901642b09e9b7c3fd42038a4
cros-nash/login-code
/forget.py
1,318
3.5625
4
import settings import emailsender import re import csv def main(): cemail = input("Enter email address linked with account: ") r1 = re.compile("@gmail\.com") if r1.search(cemail): with open('accountlist.csv','r') as f: reader = csv.reader(f, delimiter=',') for row in reader...
42e07b84644769753f2c00367b52eb8e80621dab
mrevilg/Pyble
/Functions.py
3,425
4.125
4
# Passing Lists to a Function # 3D Printing service, based on 2D Client Submissions def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing Model: " + current_design) completed_models.append(current_design...
1077da31c67125636c41d22aed5e7359d13ce82d
bobbybabra/codeGuild
/basics/dictIterate.py
1,016
4.1875
4
people = {} people['Bob'] = 22 people['Carol'] = 47 people['Justin'] = 14 for i, k in people.items(): print (i,k) #for i in people.keys(): # print (i) list(people.keys()) print people.keys() # print(people) people = {} ########### from quiz solution, this dict is not formatted #### correctly, but the point...
94ab72552d7a3f74fdc0b97c7b9b4a9e9bf1bf37
bobbybabra/codeGuild
/basics/loops.py
178
4.03125
4
list = ['apple', 'orange', 'grapes', 'last item'] num = -1 for items in list: print items num += 1 print num number = 0 while number < 100: number += 1 print number
063316d8d511523b0796a203e7bf6dbb6bf9fa4c
bobbybabra/codeGuild
/basics/functions.py
181
3.953125
4
'''a simple addition FUNCTION''' def add(a, b): c = a + b print c ### a better way is to simply say print a + b number_1 = 20 number_2 = 35 add(5, 6) add(number_1, number_2)
7e753a93aa959f96c5f900d303614e49067ed015
Zach201/compcamps2019
/GameMK1.py
3,255
4.0625
4
import time #Imports a module to add a pause #Figuring out how users might respond answer_A = ["A", "a"] answer_B = ["B", "b"] answer_C = ["C", "c"] yes = ["Y", "y", "yes"] no = ["N", "n", "no"] #Grabbing objects pistol = 0 flower = 0 required = ("\nUse only A, B, or C\n") #Cutting down on duplication #The story is...
7b52830d8c088d6792593d85f7a9f52fe1b8ea22
xipengwang/IntroAI
/random/words.py
1,219
3.703125
4
#!/usr/bin/env python3 import enchant import sys def checkCondition(solution, position, unique): if (unique): return len(solution[0:position+1]) == len(set(solution[0:position+1])) return True def solveCPS(values, size, checkCondition, unique): """Finds a solution to a backtracking problem. v...
acf1238f2f25e2ba32b1c0086b1a75bcc0c6905a
gauravbachani/Fortran-MPI
/Matplotlib/tutorial021_plotColourFills.py
1,484
4.15625
4
# Plotting tutorials in Python # Fill colours inside plots import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl mpl.style.use('default') x = np.linspace(-2.0*np.pi, 2.0*np.pi, 201) C, S = np.cos(x), np.sin(x) plt.plot(x, C, color='g', label='Cosine') plt.plot(x, S, color='r', label='Sine') # ...
28ce6b89b2867dae447af51389cf210563533690
gauravbachani/Fortran-MPI
/Matplotlib/tutorial026_subplot2grid.py
1,924
3.71875
4
# Matplotlib Plotting Tutorials # Subplots - using subplot2grid # Specify the plot position and span as grids # No multiple configurations! Single Configuration! # Replication of figure from https://matplotlib.org/users/gridspec.html import numpy as np import matplotlib.pyplot as plt ## Simple figure - no spans # Cre...
92fe5488c49209389f08764575bfac4a74141dc4
StephenH69/CodeWars-Python
/7-get-min-max.py
341
3.59375
4
# Implement a function that returns the minimal and the maximal value of a list(in this order). def get_min_max(seq): return (min(seq), max(seq)) print(get_min_max([1,2,6,98,4,1])) # test.assert_equals(get_min_max([1]), (1, 1)) # test.assert_equals(get_min_max([1, 2]), (1, 2)) # test.assert_equals(get_min_...
60a97cefda9fa31dda0b46740b8dc5de42bc17fe
StephenH69/CodeWars-Python
/8-total-amount-of-points.py
1,606
4.25
4
# Our football team finished the championship. The result of each match look like "x:y". # Results of all matches are recorded in the collection. # For example: ["3:1", "2:2", "0:1", ...] # Write a function that takes such collection and counts the points of our team in the championship. # Rules for counting points...
57f3618fc797fa6bec6c896585f94685b2265337
StephenH69/CodeWars-Python
/8-blue-and-red-marbles.py
1,517
4.1875
4
# You and a friend have decided to play a game to drill your # statistical intuitions. The game works like this: # You have a bunch of red and blue marbles. To start the game you # grab a handful of marbles of each color and put them into the bag, # keeping track of how many of each color go in. You take turns reac...
7c86e26e0bea599be21bc9a00c788f2e9e63cef4
VaishnaviBandi/6063_CSPP1
/m4/p3/longest_substring.py
1,431
4.3125
4
'''Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first subst...
6a0b387037d58a6b93b8e5cbbb5ed850f489734c
VaishnaviBandi/6063_CSPP1
/m3/iterate_even.py
92
3.890625
4
num = 2 while num<=10: print("print" + " " + str(num)) num=num+2 print("print Goodbye!")
b61b666855df35a0968802a9018d3baf29187cc2
VaishnaviBandi/6063_CSPP1
/m22/assignment1/read_input.py
426
4.375
4
''' Write a python program to read multiple lines of text input and store the input into a string. ''' def main(): """python program to read multiple lines of text input and store the input into a string.""" string = '' no_of_lines = int(input()) for each_line in range(no_of_lines): string =...
56dc2261a7a1404e882c59f9865441b989ae9661
abdirahmanfarah/Practice-Code-Reviews
/Python/challenge.py
5,230
4.1875
4
# Do not remove these imports. You may add others if you wish. import sys # Args: # matrix: an NxN list of lists containing the matrix to check # Returns: # The string "VALID" if matrix contains a valid sub-sudoku solution, and # "INVALID" otherwise # Question Prompt (1 of 1) # Problem Statement # You are wor...
6ca7f62b0c7af599c7622fe21a4867e705909b90
abdirahmanfarah/Practice-Code-Reviews
/Python/pra2.py
3,541
3.703125
4
# def compress(s): # # hash = {} # counter = 1 # arr = [] # new_string = '' # if s is None or len(s) == 0: # print("No string") # for i in range(len(s)): # if i == len(s) - 1 or s[i] != s[i+1]: # arr.append(s[i]) # arr.append(counter) # count...
264245a0748c7c261abf311076a164b9cd1f4379
aaronspindler-archive/CSCI1030U
/Labs/lab04.py
1,453
4.375
4
#Date: October 8th 2015 #Practising printing the statment testing 1 2 3... print("testing 1 2 3...") #Printing numbers, variables, and num equations x=8 print(x) print(x*2) #Defining other variable types name = "Carla Rodriguez Mendoza" length = 14.5 width = 7.25 #Printing statments print("X: ") print(x) print("Nam...
c963572441370df082f5a49f0e38fcc05f6d595d
artbb/gb_python
/hw8_7.py
2,215
4.0625
4
""" 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число». Реализуйте перегрузку методов сложения и умножения комплексных чисел. Проверьте работу проекта. Для этого создаёте экземпляры класса (комплексные числа), выполните сложение и умножение созданных экземпляров. Проверьте к...
07928bf8f78cf903841482be70c0ccf0d9d0fb9b
artbb/gb_python
/hw1_3.py
510
4.03125
4
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, # пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. number = int(input('Введите любое целое положительное число: ')) number_nn = int((f"{number}{number}")) number_nnn = int((f"{number}{number}{number}")) print(f"{number} + {num...
c292fb1ec8da2f22368ea96bbea2a0d9a9c2456c
artbb/gb_python
/hw3_4.py
1,525
3.859375
4
"""4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. Подсказка: попробу...
fcf797b741b31215d44684056807336655a29638
artbb/gb_python
/hw2_2.py
642
4.21875
4
# 2) Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются # элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить # на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). data = input('Введите не менее 3 симв...
7007ff4c5d4cd9ae59ba9642bf27f5b38c6af4d1
artbb/gb_python
/hw3_2.py
1,048
4.25
4
""" 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. """ def user_data(name, surname, bir...
4fb702c805c49158523034a2327e93f38790942f
artbb/gb_python
/hw4_4.py
1,154
4.03125
4
"""4. Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения задания обязательно использовать генератор. Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 4...
809b7e6800024a1882b48e230fcb671af8d41301
textbook/eleanor-rigbot
/eleanorrigbot/extract.py
835
3.796875
4
"""Functionality to clean tweet content for processing.""" import re VALID_PUNCTUATION = r'.,;:?!\'' CLEAN_TEXT = re.compile(r'(?:^|\s)[a-z{}\s]+(?:$|\s)'.format(VALID_PUNCTUATION)) def extract_phrase(text): """Extract the text of the tweet for phrase testing. Here the phrase to test is defined as the long...
f21dfdc3897a2fc94b736ff1be34f4ac9f0d5531
fergatica/python
/TGIF.py
728
3.65625
4
def main(): counter = 0; for i in range(1, 13): if i == 1 or i == 3 or i == 5 or i == 7 or i == 8 or i == 10 or i == 12: # months that have 31 days for j in range(1, 32): counter += 1 if counter % 7 == 3 or counter == 3: print(str(j) + "...
8173efa090c03f5141c35aa1cd3252a5cf6f6c99
fergatica/python
/JSON.py
823
3.625
4
import json import csv #read from json #to csv stop_ID;stop_name def main(): input_name = input("Enter the name of the input file: ") output_name = input("Enter the name of the output file: ") is_open = False try: f = open(input_name) is_open = True except FileNotFoundError: ...
f04204d437587e8b8eaba7b8afe7ff5948e34f34
fergatica/python
/vowels_and_consonants.py
375
3.890625
4
def main(): user_sting = input("Enter a word: ") vowels= 0 consonants = 0 for ch in user_sting: if ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u": vowels += 1 else: consonants +=1 print("The word " + user_sting + " contains " + str(vowels) + " v...
f531f682244358abfb07aff0ea716df29cf732ff
fergatica/python
/Bored.py
113
3.796875
4
user = "n" while user != "y": user = input("Bored (y/n) ") type(user) else: print("well lets stop")
d73c6d65f3e1939ec15dd4a8a5ac2acd91c0f46d
fergatica/python
/sharing_the_expenses.py
2,989
4.0625
4
file_name = input("Enter the name of the file: ") file_is_open = "" expense_dictionary = {} name = "" expense = "" try: f = open(file_name, 'r') file_is_open = "yes" except FileNotFoundError: print("Error: file", file_name, "cannot be read.") erroneous_line = False if file_is_open == "yes": line = f.r...
8e1997b194cd3c70b844333b9a91b1a8ffee002b
fergatica/python
/triangle.py
578
4.21875
4
from math import sqrt def area(first, second, third): total = (first + second + third) / 2 final = sqrt(total*(total-first)*(total-second)*(total-third)) return final def main(): first = input("Enter the length of the first side: ") first = float(first) second = input("Enter the length of th...
682ff1ce0ef28d4635a3c682ca7353d5214d8fe5
fergatica/python
/RockPaperScissors.py
647
3.953125
4
playerOne = input('Player 1, enter your choice (R/P/S): ') playerTwo = input('Player 2, enter your choice (R/P/S): ') if playerOne == playerTwo: print("It's a tie!") elif (playerOne == "P" and playerTwo == "S") or (playerOne == "p" and playerTwo == "s"): print("Player 2 won!") elif playerOne == "P" and playe...
3b1e773be979a6937c726040696c8fdc5121cde8
rajiv8/openCv_Files
/basicOperation.py
1,401
3.578125
4
# basic Operations import cv2 img = cv2.imread("./static/messi.jpg") img2 = cv2.imread("./static/Lenna.jpg") print(img.shape) # returns rows,columns and channels print(img.size) # total no.of pixels print(img.dtype) # returns datatype # b,g,r = cv2.split(img) #splitting the three channels # resizing the image ...
ddbff8ad108bc86c7d6405448fab709eb5c9a31a
naeem-hasan/t9-cipher
/t9_cipher.py
2,211
3.640625
4
class T9Text(object): _keys = { '2': "abc", '3': "def", '4': "ghi", '5': "jkl", '6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz", '0': " " } def __init__(self, text): assert type(text) is str, "Requires a string!" self.text = text.lower() def to_keystrok...
309abbebfb108ce7588b1eb06768a80a43c39f6b
drsnyder/snippits
/pe/gridsum.py
2,641
3.578125
4
def read_grid(file): grid = [] data = open(file).read() for line in data.split('\n'): rowdata = line.split(' ') if len(rowdata) == 0 or rowdata[0] == '': break grid.append([int(val) for val in rowdata]) return grid def compute_max_adj_n(grid, n): maxn = 0 ...
1daab7bf69ff959df3e183ef05d9469a833db416
Vuudi/push_swap
/push_swap.py
1,311
3.6875
4
from collections import deque import random def pb(a: deque, b: deque, moves: list): b.append(a.pop()) moves.append('pb') def sb(b: deque, moves: list): tmp1 = b.pop() tmp2 = b.pop() b.append(tmp1) b.append(tmp2) moves.append('sb') def pa(a: deque, b: deque, moves: list): a.append(...
47dbff44a9730354bb563a9d0f6e82997f388bbd
ttaylor14/PNation
/Old Files/loop_test2.py
2,527
3.5
4
# Goal is to edit the actual tempdf instead of the templist # determine how to transform functin to eliminate the need for the temp_list # Then clean up function to allow it to be reused in the add Keeper Sal function to reduce code length import pandas as pd # import files rosters = pd.read_csv('data/rosters.csv')...
aa5ff55c4033297cdf4bd0a16c41d2ebaf5a0808
Ajithjaya/DataScienceProjects
/PythonBasics/ControlFlow.py
3,699
4.15625
4
# if statements # x = int(input("Please enter an integer : ")) x = 34 if x < 0: x = 0 print('Negative replaced with zero') elif x == 0: print('Zero') elif 0 < x <= 42: print('Value is between 0 and 42 :' + str(x)) # print only takes strings no other variables else: print(x) # for statement word...
bab8f089af924d2df10611bbcd730a212105d443
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork_7_20200630/Task2.py
372
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 30 20:05:41 2020 @author: oleksiy """ givenFirstString = set(input("Enter firts string: ")) givenSecondString = set(input("Enter second string: ")) unitedSetOdStrings = sorted(set.union(givenFirstString,givenSecondString)) print(givenFirstString) ...
bf9c0b4e212cb8ca4e4348926834c738011ed666
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork_5_20200619/Task2.py
832
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 23 15:26:26 2020 @author: oleksiy """ import string enteredText = input("Enter your text: ") newLine = "" i = 1 for letter in enteredText: if (i == 4) and (letter in string.ascii_letters): newLetter = ord(letter) - 3 print(newL...
9514caf7bef250e2917c6444326ed88f4d03886d
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork_8_20200703/Task3.py
609
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 4 11:28:04 2020 @author: oleksiy """ def checkDate(day, month, year): dayInMonth = [31,28,31,30,31,30,30,31,31,30,31,30,31] if month < 1 or month > 12: return False elif day < 1 or day > 31: return False elif month > dayInMonth[mont...
73e533eb61406588d414c94797d1e1b0a7d1db06
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork20200602/Task4.1/Task4.py
867
3.671875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jun 2 22:05:07 2020 @author: oleksiy """ a = "" b = "" a = raw_input("Enter a: ") b = raw_input("Enter b: ") a = int(a) b = int(b) print a + b print a - b print a * b print a / b name = raw_input('What is your name?\n') age = raw_input("How old ar...
dca44bc3966a3216cb1af935461edb6c05f94be7
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork_3_20200612/Task5.py
1,245
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 13 19:31:27 2020 @author: oleksiy without checking if user enter letters """ try: money = int(input("Enter value of UAN to exchange:")) if money <= 0: print("Unable to exchange", money," UAH") elif money % 200 == 0: pr...
b1e97a67f6e6db7d6500ff0b518164c0df4b8740
alexfreed23/OleksiiHorbachevskyi-PythonCore
/Python/PythonCore/HomeWork/HomeWork_20200731/calculator/task1_calc.py
520
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 31 19:33:07 2020 @author: oleksii """ import calculator print(calculator.summ(10,5)) print(calculator.diff(30,5)) print(calculator.product(2,5)) print(calculator.fraction(25,5)) print("-"*10) from calculator import summ,diff print(summ(5,5)) prin...
14dd42d3b85469fd2a0df0411dbed98967c8efce
THACKERRILKER/passwordcracker
/cracker.py
617
3.734375
4
from random import * user_pass = input("Şifrenizi Giriniz: ") password = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M','1','2','3','4','5','6','7','8','9','...
a8ad09b9e8ba85067526a6eb731e58908559ca59
LukasSilvaSantos/python_solutions
/curso_em_video/atvidades de manipulação de textos/desafio22.py
562
4.21875
4
#Crie um programa que leia o nome completo de uma pessoa e mostre: #O nome com todas as letras maiúsculas. #O nome com todas as letras minúsculas. #Quantas letras ao todo (sem considerar os espaços.) #Quantas letras tem o primeiro nome. MeuNome = str(input(' digite seu nome!: ')).strip() print(f' Analisando seu...
3a973945d4a1d6bc324628bb60764e0310a7342f
LukasSilvaSantos/python_solutions
/faculdade/pratica.py
351
4.03125
4
nota1 = float(input('Qual foi a sua nota na primeira materia?: ')) nota2 = float(input('Qual foi a sua nota na segunda materia?: ')) nota3 = float(input('Qual foi a sua nota na terceira materia?: ')) if (nota1 >= 7 and nota2 >= 7 and nota3 >= 7): print('Parabéns, você passou em todas as materias!') else: print(...
63f3824ef398440e8cc1950da02441b0b677670f
LukasSilvaSantos/python_solutions
/faculdade/exercicio5.py
1,018
4.3125
4
print('CAlCULANDO... \n + = ADIÇÃO \n - = Subtração \n * = Multiplicação \n / = Divisão.') operação = input('qual operação deseja fazer?: ').lower() while (operação != 'sair'): numero1 = float(input('digite um valor: ')) numero2 = float(input('digite um valor: ')) if (operação == '+'): soma = numero...
a611e581fe7bdfc34201343f31aefda1da9a8475
LukasSilvaSantos/python_solutions
/URI/Área do Círculo.py
80
3.53125
4
raio = float(input()) n = 3.14159 area = n * (raio**2) print(f'A={area:0.4f}')
4d4bb38b7b850e0c5402cb3327abb62652082122
LukasSilvaSantos/python_solutions
/faculdade/exercicio1FAculdade.py
590
3.859375
4
print(' vamos calcular o desconto nos produtos. \n digite na tela o valor do produto é o valor do desconto. \n OBS: (Não coloque nenhum caracter no valor do produto ou do desconto, só coloque os números.)') preçodoProduto = input('qual o preço do produto?: ') desconto = input('qual o valor do desconto?: ') if (preçodoP...
f1cce93493e1204ea4e2d8eeee5a7d612e208120
LukasSilvaSantos/python_solutions
/faculdade/exerciciowhile2.py
505
3.71875
4
valor1 = int(input('digite um valor: ')) if valor1 >= 100: cedulas100 = valor1 // 100 valor1 = valor1 - cedulas100 * 100 if valor1 >= 50: cedula_50 = valor1 // 50 valor1 = valor1 - cedula_50 * 50 if valor1 >= 20: cedula_20 = valor1 // 20 valor1 = valor1 - cedula_20 * 20 if valor1 >= 10: cedu...
b024afabdd981863e78cf8be0aaeaf2a5736725b
drozol/python01
/workhome/Day_03_01.py
945
4.15625
4
# 1. Napisz program do przeliczania stopni Celsjusza na Fahrenheita i odwrotnie (wyświetlając wzór i kolejne obliczenia) rodzaj = input ("Jakie stopnie będziesz podqwał do przeliczenia Fahrenheit / Celsjusz wpisz F lub C - ") temperatura = float(input ("Podaj liczbę stopni: ")) if rodzaj == 'F' or rodzaj =='f':...
0beb262b39901354110ad27d430421e432716b79
drozol/python01
/workhome/Day_03_03.py
502
3.734375
4
# 3. Napisz program, który rysuje prostokąt o zadanych rozmiarach (wysokość i szerokość) za pomocą znaków | (bok) - (góra/dół) + (wierzchołek) wysokosc = int(input ("Podaj wysokość prostokąta : ")) szerokosc = int(input ("Podaj szerokość prostokąta : ")) licznik = 0 print ("+"+((szerokosc-2)*"-")+"+") whil...
cb216f313f89ef6478ff4a47a9e28d3e35374d08
drozol/python01
/workhome/Day_03_02.py
332
3.5625
4
# 2. Napisz program, który poda pierwszą i ostatnią cyfrę podanej liczby podana_liczba = input ("Podaj liczbę : ") dlugosc_liczby=len(podana_liczba) ostatni_znak=dlugosc_liczby-1 # print(dlugosc_liczby) print ("Pierwszy znak liczby to: "+podana_liczba[0]) print ("Ostatni znak liczby to: "+podana_liczba[ostatni_z...
fc682bb78df44ffbf14daef98ee76d8e51403fae
KhanAjmal007/Data-Structures-and-Algorithms-Specialization-Coursera
/Course_1-Algorithmic_Toolbox/Week-4/Excercise_Challenges/6_closest_points/closest.py
1,320
3.53125
4
import math def dist(a, b): return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) def naive_minimum_distance(a): min_value = float('inf') for i in range(len(a)): for j in range(i + 1, len(a)): temp = dist(a[i], a[j]) if temp < min_value: min_value = temp...
951a89c145479c0328aedbf259975aef2f1fb439
KhanAjmal007/Data-Structures-and-Algorithms-Specialization-Coursera
/Course_2-Data_Structures/Week-1/Excercise_Challenges/1_brackets_in_code/check_brackets.py
698
3.875
4
def matching(left, right): return (left + right) in ["()", "[]", "{}"] def is_balanced(text): stack = [] for i, c in enumerate(text): if c in ['(', '{', '[']: stack.append([c, i]) else: if c in [')', '}', ']']: if len(stack) == 0: ...
e23b77737946b5fa855d99c096844766a590ff8c
daniel-soriente/Perl2Python
/tests/demo05.py
151
3.5625
4
#!/usr/bin/python2.7 -u # Demo for Subset3 - .., ++, -- for i in xrange(0, 2+1): while (i < 3): i -= 1 print "Minus: %s" % (i) i += 1 i += 1
1b4e1c9c0876cdb94ffdde4557982375b9fcd307
saimanoharhm/Python_Hack
/tip_calculator/Tip_Calculator.py
387
4.09375
4
print("Welcome to the tip Calculator") bill = float(input("What was the total bill? ₹")) split = int(input("How many ppl to split the bill?")) percentage = int(input("What percentage tip would you like to give?")) tip = percentage / 100 * bill + bill Split_Amount = round((tip/split),2) Split_Amount = '{0:.2f}'.format(S...
4759102abec8e63275e2d78ac6677ad9746990bf
jerry1ye10/YeJ-Softdev
/17_db-nmcrnch/db_builder.py
1,717
4.03125
4
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O def main(): DB_FILE= "foo.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops command = "CREATE TABLE {table_name}(name TEXT, age INTEGER, id INTEGER PR...
065c27bd731c6b5fbeee139e36e9680abe235a50
dlwptmd001/CS-498-Introduction-to-Deep-Learning
/MP1/models/perceptron_org.py
3,314
4
4
"""Perceptron model.""" import numpy as np from tqdm import tqdm class Perceptron: def __init__(self, n_class: int, lr: float, epochs: int): """Initialize a new classifier. Parameters: n_class: the number of classes lr: the learning rate epochs: the number of ...
e468bc22f31d6230a392eed9071c6f8ecdaf83ff
zxr111/MachineLearning
/naive_bayes/lottery_game.py
1,771
3.703125
4
import random as rd def lottery_game(total_round=10000): ''' 有三张彩票 只有一张中奖你买走一张然后老板当场开了一张没中 给你个机会:你可以用剩下的一张换你手里的 换不换? 求概率 :return: 返回我买的彩票中奖的概率和交换后中将的概率 ''' #我抽到奖的次数 cnt_my_win = 0 #交换抽到奖的次数 cnt_cg_win = 0 for _ in range(total_round): lottorys = get_rand_lotterys() ...
e32a7feb39f3e7d1b232323d983bb8e901aac0bf
Malinovka/cs50
/Python/readability/readability.py
569
3.921875
4
import re import sys # Prompt user for text text = str(input("Enter text: ")) # Split text into sentences sentences = re.split(r'[\?\.\!]\s', text) # Split text into words words = text.split() # Count number of letters letters = 0 for i in range(len(text)): if text[i].isalnum(): letters += 1 # Calculat...
35b61e1f1a673f4a0353914fae5b565ef50d14b6
danielbjorkman88/Python
/Codility/Dominator.py
1,813
3.90625
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 3 15:22:27 2020 @author: malyr """ # Author: Wouter Coppieters # # 1. Dominator # # A zero-indexed array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. # For example, consider array A such t...
b93ccb55c9b65b44617646a2e9422453b08bc1cb
borgg9/Data-Science-with-Python-Beginners
/4_loops.py
422
4.0625
4
count = 0 # Variable declaration in python while count <=5: print(count) count += 1 #This is same as count = count + 1 ## next ilustration while(count < 5): count += 1 print ('count value has reached' + count) # Example with for loop for i in range (1, 10): if(i%5 =s= 0): break print(i) else: print('This...
c9c4682bbb07824b287f406b97addf19cc4f61b3
sujithnj88/DataScience
/Numpy/11_viewAndCopy.py
921
3.6875
4
import numpy as np placesToVisitOnWorldTour = np.array(["Paris", "Tahiti", "Berlin", "Rome", "Amsterdam", "Tokyo", "Barcelona", "Maldives"]) print(f'placesToVisitOnWorldTour : {placesToVisitOnWorldTour}') # Deep copy. New copy of array will be generated and any changes mad...
cde9bcc5e82bcde91440813e69485805e0cde819
sujithnj88/DataScience
/Numpy/8_typesOfAray.py
894
3.5
4
import numpy as np oneDimArray = np.arange(9) print(f'oneDimArray.dtype : {oneDimArray.dtype}') ################################################################################################# # Data types declaration during array creation floatArray = np.arange(9, dtype='float') print(f'floatArray.dtyp...
2a274fb9317a78f1ee0595459deed86bbab7c45a
halder555412/Newton_School_Repository
/pairsum.py
1,231
3.796875
4
#You are given an array A of size N, and you are also given a sum. #You need to find if two numbers in A exists such that their sum is equal to the given sum. #If yes, print 1, else print 0. def hasArrayTwoCandidates(A, arr_size, sum): A.sort() #sort the array l = 0 r = arr_size-1 # traverse the a...
e5f9e5c8cc657bf9ebdbc4eb3c3a41dcef82ea90
mark818/scheme
/1.py
1,312
4.0625
4
class Rlist: """A recursive list consisting of a first element and the rest. >>> s = Rlist(1, Rlist(2, Rlist(3))) >>> s.rest Rlist(2, Rlist(3)) >>> len(s) 3 >>> s[1] 2 """ class EmptyList: def __len__(self): return 0 def __repr__(self): r...
4683537ce9b8565c779407bca07abe00992279a9
franciscomelov/Apuntes
/reto_dataAcademy/21_listas.py
631
4.125
4
# Nos permite guardar varios valores en una sola variable numero = 3 otro_numero = 4 numeros = [1, 2, 3, 4, 5, 5, 6, 1] print(numeros) # [1, 2, 3, 4, 5, 5, 6, 1] objetos = ["hola", 2, True, "a", 2.5] # Accediendo a los elementos lista = ["a", "b", "c"] lista[0] # a lista[1] # b lista[3] # IndexError # AÑADIEND...
97f909eb58658e4d37811dbc982774cb44ade432
franciscomelov/Apuntes
/reto_dataAcademy/12_conversor_modulos.py
610
3.796875
4
def conversor(tipo_pesos, valor_dolar): pesos = input(f"¿Cuantos pesos {tipo_pesos} tiene?: ") pesos = float(pesos) dolares = pesos / valor_dolar dolares = round(dolares, 2) dolares = str(dolares) print("Tienes $" + dolares + " dolares") menu = """ Bienvenido al conversor de monedas 💰 1 - pe...
a0aa1296ba24c02986052816b781660fa022b4ec
hjungj21o/Interview-DS-A
/lc_bloomberg.py/430_flatten_multilevel_doublyLL.py
1,292
3.9375
4
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': if not head: return None prev = N...
6c08922949d144e4fc67c2a167f2cb4cc1ae1348
hjungj21o/Interview-DS-A
/lc_bloomberg.py/451_sort_char_by_freq.py
1,708
4.03125
4
# Given a string, sort it in decreasing order based on the frequency of characters. # Example 1: # Input: # "tree" # Output: # "eert" # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # Example 2: # Input: #...
e63094b8a8351924742363fd1e2517272fd2a7e2
hjungj21o/Interview-DS-A
/lc_bloomberg.py/114_flatten_binary_tree_to_linked_list.py
1,223
4.40625
4
# Given a binary tree, flatten it to a linked list in -place. # For example, given the following tree: # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ # 6 # Definition for a binar...
7a4a5c390a7e9d66b3cb4cab2fad9c79ea1589cc
hjungj21o/Interview-DS-A
/lc_bloomberg.py/611_valid_triangle_num.py
1,625
3.8125
4
# Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. # Example 1: # Input: [2, 2, 3, 4] # Output: 3 # Explanation: # Valid combinations are: # 2, 3, 4 (using the first 2) # 2, 3, 4 (u...
cc55d1da1d03434e9195aad5cb7981047772c4e0
hjungj21o/Interview-DS-A
/lc_bloomberg.py/2_add_two_num.py
1,583
3.796875
4
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. # You may assume the two numbers do not contain any leading zero, except the number 0 itse...
29655af2451bdb184e14f307b4451a76ee375133
hjungj21o/Interview-DS-A
/lc_linked_list_practices/19_remove_nth_node_from_end_of_list.py
1,094
3.953125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if not head: return None dummy = ListNode(0) dumm...
e34f79a5dbe72d7e8fff2f46b5f89f9de50f673a
hjungj21o/Interview-DS-A
/lc_88_merge_sorted_arr.py
959
4.21875
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # Note: # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space(size that is equal to m + n) to hold additional elements from nums2. # Example: # Input...
d647fc1babadb96e9d4268d9cd97255efa479bc1
hjungj21o/Interview-DS-A
/lc_bloomberg.py/21_merge_sorted_list.py
913
4.15625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) curr = dummy while l1 and l2: ...
3284aec1b1c5fc45e82b1e4648cf1f0714e74bce
aaroncymor/leetcode
/easy/maxdepth.py
679
3.734375
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def maxDepth(root): if not isinstance(root, TreeNode): raise ValueError("not treenode object") if root == None: return 0 if root.left =...
fd0b97ba8762872341b1f336fc7aba5da948abc7
ritamganguli/mini-projects
/calculator/Calculator.py
7,908
4.34375
4
print("This Is A Calculator") print("The Following Task Can Be Done:") print("--------------------------------") print("Press 1 For Addition") print("Press 2 For Substraction") print("Press 3 For Muliplication") print("Press 4 For Divison") print("Press 5 For Calculating Trignometric Ratioes") print("------------------...
d6ad453797db98afd65c72d06de5ff833acad93c
cxb1004/TalkRobot
/study/python/test_count.py
760
3.515625
4
# from collections import Counter # # #统计词频 # colors = ['red', 'blue', 'red', 'green', 'blue', 'blue'] # # result = Counter(colors) # print(result) # print(list(result.elements())) # # sortWordCount = sorted(result.items(), key=lambda item: item[0], reverse=True) # print(sortWordCount) import numpy as np vocab = [] # w...
1bfb07e4bc1844ddfbc899d80ec054e313afde42
nsavla007/Python-Project-On-VG-Sales
/exam_practice.py
498
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 6 11:19:42 2018 @author: neelsavla """ # Import numpy as np # Import numpy import numpy as np #create the lists for height and weight # Create array from height with correct units: np_height_m np_height_m = np.array(height) * 0.0254 # Create array ...
a8242252ac207c8121d7f75859a97bcd9b873875
orsnes-privatskole/python-oppgaver
/calculator-deluxe.py
2,869
4.125
4
import time # Calculator - Deluxe Edition # Name and version info version_info = "MyCalculator - Deluxe Edition v0.3" # Function for getting menu choice def get_menu_choice(): # Variable used to align the menu to a common width menu_width = 30 # List of available menu options valid_menu...
df3fd15ee20e78e279087a1f040b3a637e67fa1d
Sparky-Chad/Codebreaker_2020
/6_Task/Bad Code/b.py
5,749
3.84375
4
import numpy as np def binary(num, length=8): """ Format an integer to binary without the leading '0b' """ return format(num, '0{}b'.format(length)) class fec_hamming(object): """ Class responsible for creating hamming block codes and then encoding and decoding. Methods p...
c79d00c01e3578e3c70690cf7f6a8fcbc53a0305
shrey27tri01/rap
/scheduling.py
7,992
3.515625
4
import os import csv import random import adjacencylist as G import edges as E import copy import numpy # for chaitin's algorithm import interview as I def genetic_algo(graph, color): # mid is the color # chromosomes is the population, ie, list of colors (basically, list of graphs) chromosomes = [] ...
bedadb4b08c7948671b36351714d98849b6c2a29
OscarRayleigh/stat
/stat1/stat1.py
7,673
3.78125
4
# une fonction permettant à l'utilisateur d'implémenter une valeur numérique # entière n strictement positive et de la renvoyer : impln() def impln(): user_input = float(input("Entrez une valeur numérique positive strictement entière : ")) if ((user_input % 1) == 0) and user_input > 0: return int(user_...
61ac9bb6a943ff4df131b179efc70eeefbf2c602
MarcosRS/python_practice
/0_hello.py
365
4.09375
4
print('Hello World') myName = input('What is your name?') print('Hello' + myName) print(len(myName)) print(str(len(myName) * 10)) # If you dont want a new line after a print you can do print('cool', end='') print('awesome') # If you want to specify a separaton for multiple print arguments you can do print('cool'...
deab4c799195b9bd5b92f3052f10a7ec2c1f1826
MarcosRS/python_practice
/01_strings.py
1,548
4.21875
4
#escaping characters \' , \" , \t, \n, \\ alison = 'That is Alison\'s cat' print(alison) #you can also use raw string and everythig will be interpreted as a string rawStr = r'nice \' \n \" dfsfsf ' print(rawStr) # multiline strings. this iincludes new lines as tab directly. Useful when you have a large string mul = ...
826f8b1888a671dd4c5013758068d4b2fb649bb1
MarcosRS/python_practice
/3_for_loops.py
831
3.953125
4
for i in range(4): #this actually creates a list [0,1,2,3] print(i) range(0,4) # will print range(0,4) list(range(0,4)) #will print the actual list [0,1,2,3] #for huge number with (lest say an increment of 2) you can do: list(range(1,100,2)) # [0, 2 ,4, 6......] #You ou can also use the len technique with the ...
a2359c7bb6b162c6dd3149c4be0ad262a746d0e5
Mohan110594/Backtracking-3
/n_queens.py
2,022
3.859375
4
// Time Complexity : O(n!) // Space Complexity :o(n*n) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : None // Your code here along with comments explaining your approach we have used backtracking in this problem.every time we place a queen at a position we check if it...
3a968c4d069e7ad6130464b872eb7703bd0cf24c
ChaoZeyi/DeepLearning
/tensorFlow_ex/official_tutorial/codes/ex03_MNIST.py
1,318
3.515625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("F:\github\DeepLearning/tensorFlow_ex\official_tutorial\codes\MNIST_data/", one_hot=True) mnist.validation.labels mnist.train.images #####################input 28*28=784 pixes ############### x = tf.plac...
c899ae39957dc75221110be441670016040002d4
Rachelami/Pyton_day-1
/ex 03.py
291
4.125
4
num = 3 def is_even(number): if isinstance(number, int) == True: if number == num: print("True") return True else: print("False") return False else: print ("This is NOT an integer") exit() is_even(5)