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
d8535699ca0452de9baa55ca77d5c54a6f39ad99
Lguo0128/adventofcode
/day1.py
367
3.578125
4
# coding=utf-8 import math,os # file = input("Enter the input file:") file = 'D:\pythonlearn\inputs\input-day1.txt' print("--------") with open(file,"r") as rf: lists = rf.readlines() sum = 0 for i in range(0,len(lists)): lists[i] = lists[i].strip('\n') inputNum = int(lists[i]) sum = sum + math.floo...
80ce393577f87705cd53f159d777aaf3ad435d9a
JuhiSrivastava/Data-Structures
/C2 - Week3/parallel_processing.py
2,742
3.875
4
#Python3 #week -3 - assign2 def Parent(i): return (int)((i-1)/2) def LeftChild(i): return 2*i +1 def RightChild(i): return 2*i +2 def ShiftUp(arr,i): while i>0 and (arr[Parent(i)][1] > arr[i][1] or (arr[Parent(i)][1] == arr[i][1] and arr[Parent(i)][0] > arr[i][0])): arr[Parent(i)],arr[i] = arr[i...
739034e2f8c06a3d70766e4416e35bee381cb0e8
hmatsuse/repository_hitoshi
/42projects/piscine_reroaded/preopen01/ex06/my_sort.py
648
3.515625
4
d = { 'Hendrix':'1942', 'Allman':'1946', 'King':'1925', 'Clapton':'1945', 'Johnson':'1911', 'Berry':'1926', 'Vaughan':'1954', 'Cooder':'1947', 'Page':'1944', 'Richards':'1943', 'Hammett':'1962', 'Cobain':'1967', 'Garcia':'1942', 'Beck':'1944', 'Santana':'1947', 'Ramone':'1948', 'White':'1975', 'Frusciante':'1970', 'Tho...
9e97c660b3fd9deb38dcb7582772897755ffa6d4
Solertis/Graphical-Calculator
/Graphical_Calculator.py
31,610
3.65625
4
from sys import exit import math from random import randint import pygame from pygame.locals import * pygame.init() # set up window WINW = WINH = 600 assert WINW > 400 and WINH > 400, "Window's width and height too small." pygame.display.set_caption("Graphical Calculator") windowSurface = pygame.display.set_mode((WIN...
795d381c7a51c2f71b49fd8fa37120839c853a24
prem17101996/HackerRank
/Python Evaluation.py
195
3.671875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT t=input() t=list(t) t.remove("p") t.remove("r") t.remove("i") t.remove("n") t.remove("t") s="".join(t) print(eval(s))
9c2e32698347baff6edc07f7081ff6f6d1075f86
prem17101996/HackerRank
/Set.Add().py
200
3.90625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) lst=[] for i in range(n): country=input() lst.append(country) lst=set(lst) lst=list(lst) print(len(lst))
984fbec0fbc10bc1b2f022fd58e77bd1473b1930
prem17101996/HackerRank
/Extra Long Factorials.py
363
3.625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'extraLongFactorials' function below. # # The function accepts INTEGER n as parameter. # def extraLongFactorials(n): mul=1 for i in range(1,n+1): mul=mul*i print(mul) if __name__ == '__main__': n = int(in...
1627d8b56f4764f82d27d53b5e9ee86bff581e98
prem17101996/HackerRank
/Migratory Birds.py
876
3.65625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'migratoryBirds' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY arr as parameter. # def migratoryBirds(arr): ar=list(set(arr)) lst=[] for i in ar: lst....
b311a527c7c89677ab366fcc1317c629013c3dc7
Phil-Gith/Study
/Web_Crawler/ch11/ch11_8.py
396
3.84375
4
# ch11_8.py import sqlite3 conn = sqlite3.connect("myInfo.db") # 資料庫連線 sql = '''SELECT name, gender from students where gender = "F"''' results = conn.execute(sql) allstudents = results.fetchall() # 結果轉成元素是元組的串列 for student in allstudents: print(student) conn.close() ...
7631df2daca2edfc9c7c5e7058f687f4928da671
Phil-Gith/Study
/Web_Crawler/ch11/ch11_10.py
488
3.765625
4
# ch11_10.py import sqlite3 conn = sqlite3.connect("myInfo.db") # 資料庫連線 sql = '''DELETE from students where id = 2''' results = conn.execute(sql) conn.commit() # 更新資料庫 results = conn.execute("SELECT name from students") allstudents = results.fetchall() # 結果轉成元素是元組的串列...
6686a42f411df907e99fe9b6d1c9def7d616c2b0
TruongHuynhTrungNghia/university
/product/university.py
1,771
3.953125
4
#! /usr/bin/python3 # from product.undergraduate import Undergraduated # from product.graduate import Graduated from undergraduate import Undergraduated from graduate import Graduated students = [] graduate_stus = [] def represents_int(str ): try: int(str ) return True except ValueError: return False def s...
174498e6baea030b358a9f58757d26ddc7a78501
mjj4791/python-buienradar
/tests/test_urls.py
3,629
3.5
4
"""Test for URL utilities.""" from urllib.parse import parse_qs, urlparse from buienradar.urls import ( json_precipitation_forecast_url, radar_url, xml_precipitation_forecast_url ) def parse_qs_dict(url): """ Parse a url and get a dictionary of query string elements in a dictionary. Raises V...
15fd7e3cf8e7f831287b0238146f690cd76153c4
fifoteam/python-tools
/python_lib/sub_func.py
15,722
3.921875
4
#coding=utf-8 import re ## ------------------------------------------------------------------------------------- ## ȷһʡ\b means word boundary, basically. Can be space, punctuation, etc ## ------------------------------------------------------------------------------------- def find_word(text, search): result =...
04ab817ad9b5d6296ac37b8ccfee69c8cb1471f7
fifoteam/python-tools
/learn_python/py6.py
252
3.609375
4
def odd(x): return x % 2 temp=range(10) print temp show=filter(odd,temp) print show print list(show) print 'list view' print list(filter(lambda x : x % 2, range(10))) print 'second view' print list(map(lambda x : x * 2, range(10)))
3d029bb4b237c474928f4be76dae35fbd3f273ee
Tiago-hub/exercicios
/python/1/main.py
711
3.875
4
path = 'file.txt' separator = ' ' def count_odd(file_name): f = open(file_name,'r') sequence = f.read().split(separator) count = 0 for number in sequence: number = int(number) if(number%2): count+=1 return count def count_even(file_name): f = open(file_name,'r')...
d102eb0df0592bb5c0bcf5309893958ad74ccabf
joseraz/data_science_journey
/LeetCode/Easy/Valid Palindrome.py
303
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 8 17:23:00 2020 @author: joera """ def isPalindrome(s): x = '' for i in s: if i.isalnum(): x += i.lower() return x==x[::-1] x = "A man, a plan, a canal: Panama" print(isPalindrome(x)) y = "race a car" print(isPalindrome(y))
43d48be511d478df160c7bc9ac9097eef37f039c
joseraz/data_science_journey
/Learning New Things/lambda functions.py
345
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 22:48:47 2020 @author: joera """ # Normal function form def square(a): return a*a result = square(5) print(result) # My first lambda function f = lambda b : b*b test = f(5) print(test) # Second lambda function # Why does this not work? g = lambda x,y : x + y ...
b6d80ef9717838b51d02a4a5a5ab01c81b746967
nguyentaijs/basic_algorithm_and_structure
/2021.06.05_Buoi4_NguyenThanhTai/w4_bai2_cach2.py
717
3.96875
4
_inputStr = input("Input separated by space char: ") _input = _inputStr.split() print("Input : ", _input) def swapValue(_input, i, j): temp = _input[i] print("Swap {}[{}] with {}[{}]".format(i, _input[i], j, _input[j])) _input[i] = _input[j] _input[j] = temp for i in range(len(_input) - 1): print('---[i = {}]--...
25c88d06d81a6eb61cc3399c04ebf1439a3f97f3
nguyentaijs/basic_algorithm_and_structure
/2021.06.05_Buoi4_NguyenThanhTai/w4_bai4.py
643
3.875
4
balance = int(input("Init balance: ")) transactionStr = input("Input transaction separated by space char: ") transactions = transactionStr.split() isWithDraw = False for item in transactions: if item.isalpha(): if item.lower == "w": isWithDraw = True else: isWithDraw = False if item.isdigit(): if isWith...
37690e091d858f0ac79c4a8cd537d0f4e7ca1121
JustinPrivitera/Schedule-Planner
/node.py
945
3.625
4
class node: def __init__(self, name, index): self.name = name self.index = index def getName(self): return self.name def getIndex(self): return self.index def setName(self, newname): self.name = newname def setIndex(self, newindex): self.index = newindex def nodeCompare(node1, node2): # returns 1 ...
5cd020663a89b49836a0d20fa77dc4d636d4e254
Sebgg/ip-backup
/TDP002/lab6/test/lab1a.py
174
3.765625
4
#!/usr/bin/env python3 sum = 0 for number in range (513): sum += number print(sum) ''' <BEGIN COPYRIGHT> hej this is a cool file hej svej, på dej <END COPYRIGHT> '''
0029873516df28556a279606352daad536780c13
Sebgg/ip-backup
/TDP015/NumeriskUppgift/UppgiftN.py
3,900
4.1875
4
# TDP015 Programmeringsuppgift N # Numeriska metoder # Skelettkod from math import isclose # Er uppgift är att implementera Newtons metod för att approximera # nollställen till en funktion och att sedan tillämpa denna # implementation för att lösa tre numeriska beräkningsproblem. En # beskrivning av metoden hittar du h...
67539b7c31b595be24eb58290719d1b8a78f51e8
Sebgg/ip-backup
/TDP015/uppgift4/uppgift4.py
7,508
3.8125
4
# TDP015 Programming Assignment 4 # Image Classification # Skeleton Code import math import mnist import png import random # ## Introduction # # In this assignment you will implement a probabilistic classifier for # handwritten digit recognition: a system that takes an image of a # digit as its input, and predicts th...
741f461a3c8ce20918fc200ed7602ab1228d38f8
Sebgg/ip-backup
/TDP002/lab5/lab5f.py
225
3.734375
4
#! /usr/bin/env python3 def add(x,y): return x+y def sub(x,y): return x-y def mult(x,y): return x*y def partial(func, value): return lambda x: func(x, value) add_five = partial(add, 5) print(add_five(3))
acc34361669d704aa552c4d534f23505187aeed9
fla07/python
/area_cubo.py
161
3.90625
4
print("Area total do cubo") Ab = float(input("Digite o valor da aresta: \n")) Ab = Ab**2 A = 6*Ab print("A área total do cubo é de ", A," m²")
838775b7700e92d22745528eb8a0d03135d44f55
brandong1/python_textpro
/files.py
1,485
4.28125
4
myfile = open("fruits.txt") content = myfile.read() myfile.close() # Flush and close out the IO object print(content) ########## file = open("fruits.txt") content = file.read() file.close() print(content[:90]) ########## def foo(character, filepath="fruits.txt"): file = open(filepath) content = file.read()...
0dbaaf6e2fe2e5daf521575307c550edbf528dcf
odipojames/password-ip
/run.py
6,025
3.890625
4
#!/usr/bin/env python3.6 from password import User , Credential def create_profile(first_name,last_name,password): ''' function to create a new user ''' new_user = User(first_name,last_name,password) return new_user def save_user(user): ''' function that saves new users ''' User.sa...
2f0db42120abb9b66e4a5f8286aebfc121226914
suavebajaj/Python-3
/InputName.py
257
4.09375
4
print ("Enter your Name") Name = input() #Takes String as an Input print ("\nHowdy " + Name.lower())#Turns the string into lower case X1 = ("How are you? ") + Name.upper()#Turns the string into upper case print(X1) print(X1[8]) #Prints the 8th place string
fff5782580f6fb9f1680abfba49086c184611115
jisun-choi/python_algorithm
/클래스.py
1,159
3.53125
4
# 한 클래스에 두 개의 객체(공격,방어)를 만들어 '캐릭터 싸움'을 구현해주세요. # 나와 상대방(적)의 이름 및 직업을 생성 & 초기 hp 값은 100 & 공격 시, hp에서 -10 / 방어 시, hp에서 -5 # ==========print 내용===================== # 내 이름.공격(적 이름) #메소드 호출 # 상대 (직업) 에게 10 피해를 입혔습니다. # 내 이름.방어() #메소드 호출 # (내 직업) 은 5 피해를 입었습니다. class Fight: def __init__(self, name, role): sel...
31c3f401c7f6962308dcd80d32bba878b738a4ad
jisun-choi/python_algorithm
/카드번호 입력.py
198
3.703125
4
num = input('카드번호를 입력하세요(하이픈 필수)> ') split_list = num.split('-') split_list[0] = '****' split_list[3] = '****' split_list = '-'.join(split_list) print(split_list)
5e06da4c3017b81c4305430ed3de3ef6eb215e16
jisun-choi/python_algorithm
/나이, 점수 리스트.py
433
3.8125
4
Age = {'A':20, 'B': 16, 'C': 30, 'D': 23} Lit = {'A':90, 'B': 47, 'C': 30, 'D': 76} Eng = {'A':86, 'B': 39, 'C': 64, 'D': 84} Math = {'A':47, 'B': 52, 'C': 58, 'D': 73} #C의 총점, 평균 total = Lit['C']+Eng['C']+Math['C'] avg = total / 3 #나이 합계 age = Age.values() print(sum(age)) #가장 적은 점수 min_list = min(Lit.values()), m...
77db9f9a95b9e2fb6181c3795f01060445d6601c
jisun-choi/python_algorithm
/문자열 제거.py
275
3.734375
4
x = input('input str> ') pairs = [] for i in x: if len(pairs) == 0: pairs.append(i) elif pairs[-1] == i: pairs.pop() else: pairs.append(i) if len(pairs) == 0: print(1) else: print(0)
17555294eca71ed6b869cdd2cfd5b8a932d2a9bc
jisun-choi/python_algorithm
/예외처리.py
1,183
3.953125
4
try: print('나누기 전용 계산기') nums = [] nums.append(int(input('첫 번째 숫자 입력: '))) nums.append(int(input('두 번째 숫자 입력: '))) nums.append(int(nums[0] / nums[1])) print(f'{nums[0]} / {nums[1]} = {nums[2]}') except ValueError: print('에러! 잘못된 값 입력') except ZeroDivisionError as err: print(err) except E...
5fe61ff7d146d349842a58fc9da951fd68fb20ba
theepicsnail/cursesgame
/cursesgame/interfaces.py
1,662
3.625
4
""" Base classes for the objects used in this game""" from collections import defaultdict class Cell(object): """ Base class for items shown on the screen """ color = None character = ' ' passable = True def __hash__(self): return hash(type(self)) def __eq__(self, other): retu...
f8ee444a0cf0cbb71e939070d3d130dcb2f9ee41
tannerkoscinski/MySQL-Example
/northwind_mysql_connector.py
18,440
3.71875
4
"""MySQL Examples in Python""" # Import libraries import mysql.connector import pandas # Connect to database CONNECTION = mysql.connector.connect(host='localhost', user='root', passwd='password', auth_plugin='mysql_native_password') MYSQL = CON...
50f5f8f6b42232c74feb16d7b831f6d5d536274a
mglaros/Python-Data-Structures-and-Algorithms-Udemy-Course
/graph_search.py
1,130
3.953125
4
def dfs(graph, start): stack = [start] visited = [] while stack: node = stack.pop() if node not in visited: visited.append(node) neighbors = sorted(graph[node], reverse=True) for item in neighbors: if item not in visited: stack.append(item) return visited def bfs(graph, start): queu...
a94f347d875285726c6d63f4c3ad964f24e2069d
leo-gan/GLD.Skills
/Sorts/selection_sort.py
731
3.53125
4
# def selection_sort(ar): # for i in range(len(ar)): # max_id = 0 # for ii in range(len(ar)-i): # if ar[ii] > ar[max_id]: # max_id = ii # ar[len(ar)-i-1], ar[max_id] = ar[max_id], ar[len(ar)-i-1] # print(ar) def selection_sort(ar): for i in range(len(...
c6d295cee3f2042eade5e625ac5d67163828e2a6
leo-gan/GLD.Skills
/Sorts/merge_sort.py
1,274
3.875
4
def merge_sort(x): if len(x) < 2: return x result, mid = [], int(len(x) / 2) y, z = merge_sort(x[:mid]), merge_sort(x[mid:]) while (len(y) > 0) and (len(z) > 0): t = z if z[0] < y[0] else y #print(t[0]) result.append(t.pop(0)) print(result, y, z) return result + y + z...
22274d2d54df472e134114c99951195a8eef8f44
leo-gan/GLD.Skills
/Sorts/insertion_sort.py
557
3.921875
4
# def insertion_sort(ar): # for i in range(len(ar)): # for ii in range(i, 0, -1): # if ar[ii] < ar[ii-1]: # ar[ii], ar[ii-1] = ar[ii-1], ar[ii] # print(ar) def insertion_sort(ar): for i in range(len(ar)): for ii in range(i, 0, -1): if ar[i...
cf3a400baac6dd50dcd1303a137fca331b1d0ea7
m0mosenpai/dsagrind
/AdventOfCode_2020/6_custom_customs.py
1,424
3.65625
4
#!/usr/bin/env python3 # global GROUP_SIZES = [] # O(n) Time Complexity | O(n) Space Complexity def part_1(data_list): yes_count = 0 total = 0 group_size = 0 questions = [0 for i in range(26)] for data in data_list: if data == "": yes_count = 0 questions = [0 for i ...
9d0f96949376539f83da02873a8e1e619cbd33d5
m0mosenpai/dsagrind
/[Coursera] Algorithmic_Toolbox/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py
603
3.703125
4
# Uses python3 import sys # def pisanoPeriod(m): prev, current = 0, 1 for i in range(0, m*m): prev, current = current, (prev + current) % m if (prev == 0 and current == 1): return i + 1 def get_fibonacci_huge_naive(n, m): pisano = pisanoPeriod(m) n = n % pisano prev, current = 0, 1 if n ==...
9e1cba7ea8c7514882497ac1fe5adb3126fd04f7
m0mosenpai/dsagrind
/LeetCode/binary_search/first_bad_version.py
956
3.734375
4
# The isBadVersion API is already defined for you. # @param version, an integer # @return an integer # def isBadVersion(version): # Example: [1, 2, 3, 4, 5] class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ # If there is only 1 version, return it...
e468eea501a69b3b0461eadfd41bc1563376b88f
m0mosenpai/dsagrind
/LeetCode/binary_search/mountain_array.py
406
4.0625
4
def binary_search(array): left = 0 right = len(array) - 1 while (left < right): mid = left + (right - left) // 2 if array[mid] > array[mid + 1]: right = mid else: left = mid + 1 return left array = [1, 2, 3, 5, 6, 4, 3, 2] print(f"This is the sample ar...
0ee889b872c89631a7e29e52a314417b3b6de0d9
m0mosenpai/dsagrind
/AdventOfCode_2020/13_shuttle_search.py
1,374
3.53125
4
#!/usr/bin/env python3.9 import math # Straightforward Bruteforce def part_1(data_list): min_departure_time = int(data_list[0]) bus_list = list(map(int, list(filter(lambda x: x != "x", data_list[1].split(","))))) rem_dict = {} for i, bus in enumerate(bus_list): time = min_departure_time while (time % bus): ...
f441558275adf898d1cd6100cf9e0099058c4916
sat8ndra/MIT-6.00-Python-Fall-2008-Introduction-to-computer-science---Solution-of-Assignments
/ps1b.py
1,157
3.796875
4
### Problem Set 1 ### Name: Satyendra gupta ### Collaborators: None ### Time: 10:00 ### prime = True number = 3 devisor = 2 for prime_count in range(0,1000): if prime_count == 999 : ##this condition check 1000th prime number count and print print(number - 1 ) break while prime : ...
8e5033488a99f2c785a5d52e13745d4ab0910f61
tanglan2009/Python-exercise
/classCar.py
2,858
4.4375
4
# Imagine we run a car dealership. We sell all types of vehicles, # from motorcycles to trucks.We set ourselves apart from the competition # by our prices. Specifically, how we determine the price of a vehicle on # our lot: $5,000 x number of wheels a vehicle has. We love buying back our vehicles # as well. We offer ...
2ee6f9397ea09b87ad35069b7d94842564c697a3
Jelly815/housepage
/python/k_means.py
2,658
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 16 23:31:02 2019 @author: Jelly """ import random from functools import reduce import matplotlib.pyplot as plt class KMeans: """performs k-means clustering""" def __init__(self, k): self.k = k # number of clusters self.means = None # m...
1eb263cc7cc3812c0c455fd485af6903334b3e0c
Cbhihe/pyDojo
/functional_python/robot_fun.py
1,434
3.6875
4
from collections import namedtuple from functools import reduce from itertools import cycle from operator import add Robot = namedtuple('Robot', ('x', 'y', 'direction')) direction = cycle(('NORTH', 'EAST', 'SOUTH', 'WEST')) def turn_right(robot): if next(direction) != robot.direction: return turn_right(...
b9fdb1c689ce4c3177a52d465fbcd0d97a07fa72
cam-rod/ICS-Encryption
/encryption.py
17,668
4.21875
4
# Cameron Rodriguez # May 23, 2019 # This program encrypts and decrypts files. # These modules generates the GUI for the program import Tkinter as tk import tkFileDialog import math # This module is used to split the password into sets of three """ Data Dictionary main: instance: an instance of Tkinter...
c8e8e6d94c8081be0c1c47c98b955ce70b5e0719
rodolfosgarcia/CodingChallenges
/Twitter-NewStack.py
730
3.9375
4
""" Implement a class for a stack that supports all the regular functions (push, pop) and an additional function of max() which returns the maximum element in the stack (return None if the stack is empty). Each method should run in constant time. """ class MaxStack: def __init__(self): self.s = [] ...
166a571e85c1e698cd8bf0a2814a034c15fed751
marcelomata/bayesian_probabilistic_assembler_genomics_course
/PROGRAMS/CreateTestOutput.py
1,384
3.671875
4
''' Dan Adler, Farhan Damani Computational Genomics Final CreateTestOutput.py COMMAND: python CreateTestOutput.py input.fa output.fa Given a file of data with A's,T's,C's,G's representing a genome, this file creates a continuous sequence of reads by taking away extraneous whitespace. The input file is a sequence of...
e8bab715fb8ff2303ff7d5eb444789393d298844
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex075.py
768
4.3125
4
'''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.''' tupla = (int(input('Digite um número: ')), int(input('Digite outro número: '))...
9acb75fe2acb86b00927c6089411c60441558de6
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex041.py
733
4.03125
4
# A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: #– Até 9 anos: MIRIM #– Até 14 anos: INFANTIL #– Até 19 anos: JÚNIOR #– Até 25 anos: SÊNIOR #– Acima de 25 anos: MASTER from datetime import date from time import sleep...
ca4270f470222f13e66ea1842074eb2cf0ba0806
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex014.py
251
4.34375
4
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. cel = float(input('Informe a temperatura em celsius: ')) print('A temperatura equivalente em Fahrenheit é {}ºF'.format((cel * 1.8)+32))
00cac865ad4fbe8f7194c20341af9603ca5ec756
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex008.py
236
4.09375
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. n = float(input('Digite o valor em metros: ')) print('O valor digitado é {}dm {:0f}cm e {:0f}mm'.format(n * 10, n * 100, n * 1000))
2f951247fe21497e91b69083f9b69c3dfc83a648
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex019.py
497
3.890625
4
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. from random import choice alu1 = str(input('Digite o primeiro aluno: ')) alu2 = str(input('Digite o segundo aluno: ')) alu3 = str(input('Digite ...
c9701a859498f015383c3ad0c809ff1f82d6eb31
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex011.py
428
3.984375
4
# Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. alt = float(input('Digite a altura da parede: ')) lar = float(input('Digite a largura da parede: ')) area ...
3365c7b2b19a07e2325b80eefef64cfff57e2eae
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex074.py
478
4.03125
4
'''Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.''' from random import randint na = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(...
f700029ffc30ad1ea2a06628cea74d2c58b3c45b
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex024.py
282
3.9375
4
# Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome “SANTO” cid = str(input('Digite o nome da cidade: ')).strip().upper() div = cid.split() print(cid) print('A cidade começa com o nome Santo? ', 'SANTO' in div[0]) print(cid[:5] == 'SANTO')
f5a2d37db731ab454c41e19b6922fb0dc050137b
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex082.py
577
3.703125
4
lista = list() pares = list() impar = list() while True: n = int(input('Digite um número: ')) lista.append(n) #if n % 2 == 0: # pares.append(n) #else: # impar.append(n) perg = ' ' while perg not in 'SN': perg = str(input('Deseja continuar: [S/N] ')).strip().upper()[0] i...
79e14ec1780aed4d83f66d809bd629cfac152955
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex007.py
234
3.90625
4
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) print('A media do aluno é {}'.format((n1+n2)/2))
f28857169371fe0e8542b3a41d23a26f63563078
vaibhavc99/GoGreen
/venv/Lib/site-packages/frame/postprocessors.py
2,337
3.53125
4
''' Post processors are applied to the response body just before delivery to the client. This is how simple things like "deflate" are implemented. A post processor is simply a callable that accepts two parameters: the request and response objects. They are exactly what they sound like. To learn how to implement a post ...
b82b852cb601d7852ced288c22b8f03474203055
RajaaBoulassouak/02-simple-python-data
/simple_python_data.py
1,087
3.765625
4
def calculate_rectangle_area(height, width): ## Todo: update `None` to contain the formula for `rectangle_area` rectangle_area = height * width return rectangle_area def calculate_area_of_square(side): ## Todo: update `None` to contain the formula for `squre_area` square_area = side ** 2 re...
55df373faac6e216c3733e94eb04478019370265
saip009/USC-Assignments
/CSCI 567 - Machine Learning - Fall 18/P4/kmeans.py
5,918
3.578125
4
import numpy as np class KMeans(): ''' Class KMeans: Attr: n_cluster - Number of cluster for kmeans clustering (Int) max_iter - maximum updates for kmeans clustering (Int) e - error tolerance (Float) ''' def __init__(self, n_cluster, max_iter=100, e=0...
a89549b60f15df25465bbf8c0280a0eb6e77df1d
Matheusfeq/git
/jogodavelha.py
2,290
3.5625
4
import os, time ############################# #Cores limpar = "\033[0m" vermelho = "\033[38;5;203m" azul = "\033[38;5;27m" ############################ aux = 0; flag = True jogador = 0 # 0 = X, 1 = O jogo = [1,2,3,4,5,6,7,8,9] def clear(): ''' limpar o terminal ''' os.system('cls') clear() def introducao...
2d34449da202708854aea350bad976a82e7e6349
HedgehogCode/keras-transfer-learning
/keras_transfer_learning/backbones/convnet.py
3,462
3.859375
4
"""Simple convolutional neural network backbone. """ import keras.backend as K from keras import layers def convnet(filters: list = None, conv_per_block: int = 2, kernel_size=3, activation='relu', batch_norm: bool = False, end_maxpool: bool = False, end_global_maxpool: bool = True, ndims: int ...
ad4bcad0967ba486e4b20c945f4a5a3bfab83ad1
vitaz-0/naucse-python
/03/zelva.py
869
3.671875
4
from turtle import forward, left, right, shape, exitonclick from turtle import penup, pendown shape('turtle') def obdelnik(): forward(200) left(90) forward(100) left(90) forward(200) left(90) forward(100) left(90) for i in range(4): obdelnik() right(30) exitonclick() # d...
d30f5d0309c01ba64e2cb2170bf3f7914c15d594
ashtonbaker/project-euler
/0049/0049.py
805
3.75
4
import time start_time = time.time() def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=...
0ac9e89fd967b2d954b43a4cc4127a1bf8276aa5
ashtonbaker/project-euler
/0035/0035.py
769
3.734375
4
def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def rotation(n, k): ...
bda9dcdcc4953e320c422efc2b842220a4c3aff5
ashtonbaker/project-euler
/0051/0051.py
912
3.765625
4
def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def anonymize_number...
6ef8d82c888f8225f9c37a4cdfdf12cbc518a4b4
mbocaneg/Leetcode-Submissions
/14_longest_common_prefix/main.py
711
3.671875
4
class Solution: def longestCommonPrefix(self, strs): if len(strs) == 0: return "" if strs[0] == "": return "" prefix = strs[0] str_iterator = iter(strs) next(str_iterator) for str in str_iterator: min_length = min(len(prefix), le...
6380f3d5afda61376b3aceffd9e382c35fa8562e
mbocaneg/Leetcode-Submissions
/88_merge_sorted_array/main.py
665
3.671875
4
class Solution: def merge(self, nums1, m, nums2, n): m -= 1 n -= 1 tail = len(nums1) - 1 while tail >= 0: if m < 0: nums1[tail] = nums2[n] n -= 1 elif n < 0: nums1[tail] = nums1[m] m -= 1 ...
38afe9332ad624a7599d7bf27ea50e5bc6224a82
mbocaneg/Leetcode-Submissions
/344_reverse_string/main.py
450
3.578125
4
class Solution: def reverseString(self, s): """ Do not return anything, modify s in-place instead. """ if s == "": return i = 0 j = len(s) - 1 while j > i: temp = s[j] s[j] = s[i] s[i] = temp ...
b0c07fa5f38f4fd04a17324ab9c790482056dbd2
padma108raj/vasuken-padmaraj
/set/eliminate_dups.py
204
3.875
4
""" Approach1 """ l=eval(input("Enter list of value:")) s=set(l) print(s) """ Approcah 2 """ l=eval(input("Enter list of values:")) l1=[] for x in l: if x not in l1: l1.append(x) print(l1)
489c8f1780e7f36eaa76b69727c298178cbb33a3
padma108raj/vasuken-padmaraj
/set/set_functions.py
262
3.671875
4
# Demo of add() in set s={10,20,30,40} s.add(50) print(s,type(s)) # Demo of update() l=[40,50,60,70,80] s.update(l,range(5)) print(s) # Demo of Copy() # Copy is used clone : Return the copy of set s1=s.copy() print("Elements in s1",s1) s1.clear() print(s1)
ae2bc6d2e8fdab66e99646bc624b538db309e01c
shahrozimtiaz/codingPractice
/python Practice/bus.py
378
3.671875
4
from vehicle import Vehicle class Bus(Vehicle): def __init__(self,vehicleType,doors,wheels,capacity): super().__init__(vehicleType) self.doors = doors self.wheels = wheels self.capacity = capacity def toString(self): print('VehicleType:',self.vehicleType,'Doors:',self.do...
0020a13cb810ccddb45dad9b3243999e6d3e3d2a
shahrozimtiaz/codingPractice
/python Practice/dijkstra's algorithm.py
2,752
3.703125
4
import math class Graph: class Vertex: def __init__(self,value): self.value = value self.adjacent = [] def __init__(self,graph): self.V = len(graph) self.vertices = [] for r in range(self.V): vertex = self.Vertex(r) for c in rang...
ab161863f3642e986fe636fb6000667c404fb779
shahrozimtiaz/codingPractice
/python Practice/wordSearch.py
8,154
3.5
4
import numpy as np import string words = open("words.txt","r").readlines() wordsUsed = {} boardSize = 15 board = np.zeros([boardSize,boardSize],str) alph = list(string.ascii_lowercase) def boardFilled(): for row in range(boardSize): for col in range(boardSize): if board[row][col] == "": ...
3a99a04b406361df0fe73878d283bbbc1366b254
L200180014/algostruk
/MODUL_4/06.py
535
3.515625
4
def binSe(kumpulan, target): low = 0 high = len(kumpulan) - 1 while low <= high: mid = (high + low) // 2 if kumpulan[mid] == target: return "target berada di index " + str(mid) break elif target < kumpulan[mid]: high = mid - 1 ...
c259a0fb4637d7d3c208a8e08657b7584501e424
Karlhsiao/py4kids
/homework/hw_30_pay_calc.py
1,262
4.21875
4
''' Calculate weekly payment by working hours and hourly rate ''' STANDARD_HOURS = 40 OVERTIME_FACTOR = 1.5 def process_user_input(working_hours, hourly_rate): hrs = float(working_hours) r = float(hourly_rate) return hrs, r def input_from_user(): #working hours in the week, ex. 40 working_h...
0a392fa05f555bb51b5731ea101bd65f85ad8b89
KonstantinKlepikov/all-python-ml-learning
/python_learning/overloading_it_gt.py
351
3.796875
4
# example of overloading __lt__, __gt__ class C: """Overloading __lt__ and __gt__ """ data = 'spam' def __gt__(self, other): return self.data > other def __lt__(self, other): return self.data < other if __name__ == "__main__": X = C() print(X > 'ham') # True __gt__ ...
88bf2b286436f65248857cf6409ada4e9cb5023d
KonstantinKlepikov/all-python-ml-learning
/python_learning/metaclass_base.py
5,097
3.890625
4
# example of metaclass - basic terms # redefine __new__ class MetaOne(type): def __new__(meta, classname, supers, classdict): print('In MetaOne.new:', meta, classname, supers, classdict, sep='\n...') return type.__new__(meta, classname, supers, classdict) # both __new__ and __init__ class MetaTw...
20135fbed6d5405f86e8c3b490ca0b8eb0e54d21
KonstantinKlepikov/all-python-ml-learning
/python_learning/overloading_bool.py
811
4.0625
4
# overloading __bool__ class Truth: def __bool__(self): return True class Lie: def __bool__(self): return False class TruthNoBool: """Example with __len__ """ def __len__(self): return 0 class TruthBoolPriority: """If booth __bool__ and __len__ - __booll__ is i...
a094eace179eb7883904a900bb4ec3587c580d2c
KonstantinKlepikov/all-python-ml-learning
/python_learning/class_attention.py
1,427
4.15625
4
# example of traps of class construction """Chenging of class attributes can have side effect """ class X: a = 1 """Chenging of modified attributes can have side effect to """ class C: shared = [] def __init__(self): self.perobj = [] """Area of visibility in methods and classes """ def generate...
a7ccd977a045b256cdaa80893f70eb9356154074
KonstantinKlepikov/all-python-ml-learning
/python_learning/decorators_base.py
2,695
3.796875
4
# basic examples of decorators realisation # call tracking class tracer: def __init__(self, func): self.calls = 0 self.func = func def __call__(self, *args): self.calls += 1 print('call {0} to {1}'.format(self.calls, self.func.__name__)) self.func(*args) @tracer def ...
ed7d9e8b00cfa921c8aa70b09511480a2fbc2a2b
KonstantinKlepikov/all-python-ml-learning
/python_learning/oop_lutz_01_compose.py
3,146
4.375
4
# most realictic class example (with composite architecture) class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): """Extract last name Returns: str: extracted last name """ ...
4d1f40485e149b3a99a3266349f33b59956e9e41
KonstantinKlepikov/all-python-ml-learning
/python_learning/super_example.py
993
4.4375
4
# example of super() usage """Traditional method of superclass calling """ class C: def act(self): print('spam') class D(C): def act(self): C.act(self) # explicit usage of superclass name to give it to self print('eggs') class DSuper(C): def act(self): super().act() ...
2e9536a48eb10ee061b9a5080590339ebd8a0b5b
KonstantinKlepikov/all-python-ml-learning
/python_learning/oop_lutz_02_2.py
701
4
4
# example of definitions of names part 1 #global name or attribute of module (X or oop_lutz_02_2.X) X = 11 # access to global name from function def f(): print(X) # local variable in function (X, hides moduls X) def g(): X = 22 print(X) class C: X = 33 # class attribute (C.X) def m(self): ...
805d28a5aab6a34cc9588ce26de107a142d1f640
KonstantinKlepikov/all-python-ml-learning
/python_learning/factory.py
519
3.53125
4
# simple example of factory principles def factory_(class_, *args, **kwargs): return class_(*args, **kwargs) class Spam: def doit(self, message): print(message) class Person: def __init__(self, name, job=None): self.name = name self.job = job if __name__ == "__main__": o...
1cf4a57b4baa22aff3f0aa808031cfa7cfaffc26
Lucie-G/differential-evaluation
/results.py
15,029
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ # Differential evaluation Compares a set of system results Input = one row per gold standard item, one column per system: in each cell, 1 if system obtained a true positive (TP) for this item, 0 otherwise. For each input data item, computes how many systems obtained a T...
ca80d99e95a718c19ab84c4013d5641e82da0d7d
syl0224/algorithm
/sort/insert_sort.py
544
4.0625
4
class InsertSort(object): @classmethod def insert_sort(cls, arr): if arr == [] or arr is None: return [] for i in range(0, len(arr)): pre_index = i - 1 current = arr[i] while pre_index >= 0 and arr[pre_index] > current: arr[pre_inde...
f041574f6bd8d95433429f3cddd2bf9bd6848743
skaradimitriou/ATM-Project
/main.py
1,873
3.84375
4
from balance.Balance import Balance from billing.BillPayment import BillPayment from deposit.Deposit import Deposit from helper.InstructionsHelper import InstructionsHelper from withdrawal.Withdrawal import Withdrawal # The user has a fixed balance account userBalance = 5000.0 # Calling the Instructions Helper Class ...
bf94d06cdfd120fa395ca1fe3387303e7f9de51b
beijing-fhit/OldManCall_Flask
/App/utils/CommonUtils.py
278
3.71875
4
# 区分两个数组的不同 def compareArrays(a, b): common=[x for x in a if x in b] # 相同元素 _a_diff=[y for y in a if y not in common] _b_diff=[z for z in b if z not in common] print("数组区分",a,b,_a_diff,_b_diff,common) return _a_diff,_b_diff
0704f17a81bb58ccfb55885b3f05ab85da62f5f6
himik-nainwal/PythonCodeFragments
/Search And Sort/BubbleSort Python.py
270
4.15625
4
def bubble_sort(array): for i in range(len(array)): for j in range(i,len(array)): if array[j] < array[i]: array[j], array[i] = array[i], array[j] return array print(bubble_sort([5,54,87,3,9,47,12,65,92,45,78,2]))
7a6964f528a59ff84df3a81be887adde79290644
gjholman/Codecademy
/Data-Science/Honey_Production_LR.py
2,422
4.09375
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model # import csv of honey production using pandas df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv") # Pandas function head will show the fi...
8dfac5602f8b55eb4b850bf8f3b7c15ea7c3363b
merryta/alx-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
550
4.34375
4
#!/usr/bin/python3 """ This is the "0-add_integer" module. add a and b and it can be int or floats """ def add_integer(a, b): ''' add two number Args: a : int or float b : int or float Rueturn an int ''' if not isinstance(a, int) and not isinstance(a, float): raise TypeError("...
3ad8001b48d6a98de48be16b061b2d64efd31315
bagustris/python-intro
/code/dictionary.py
245
4.125
4
#! /usr/bin/env python3 dictionary = {'book' : 'buku', 'table' :'meja', 'chair' : 'kursi' } for k in dictionary.keys(): print(k, "-->", dictionary[k]) for i in dictionary.items(): print(i) print(i[0]) print(i[1])
320dacfaa0cc9d66a041c7048de89c1d20086ae5
bagustris/python-intro
/code/insertion.py
442
3.8125
4
#! /usr/bin/env python3 def insertion_sort(l): """ documentaion goes here""" for i in range(1, len(l)): for j in range (i, 0, -1): if l[j] < l[j-1]: l[j], l[j-1] = l[j-1], l[j] else: break from random import randint for n in 10, 100, 1000, 10000...
1bb899df7ccb19f0b7b29e9038e41e6cde530305
sanmathirai/Python-26Dec18-InternShip
/python/magic_number.py
192
3.59375
4
def magicnum(n): power = 1 ans = 0 while(n): power = power*5 if ( n & 1 ): ans += power n=n//2 print(ans) class mn : magicnum(2)
79a3104079dda69d14564ae6001cead2b4cb10a1
DSmood/Pytorch
/Introduction to PyTorch.py
60,570
4.9375
5
# Introduction to PyTorch #___________________________________________________________________________________ ## Part I Introduction to PyTorch #___________________________________________________________________________________ #1)Creating tensors in PyTorch # Random tensors are very important in neural...