blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
30d0ce50970de8d1ae99b8349eacfe0f99c03677 | sksodhi/bengio-project | /pca.py | 2,461 | 3.640625 | 4 | from __future__ import division
import numpy as np
import numpy.linalg as LA
"""
" This function performs PCA on given matrix X.
" It takes two inputs:
" X : Matrix X on which to perform PCA
" num_of_dim : Number of colums of principal components to return
"
" Sample invocation :
" X,T = read_letter_recognition_data... |
81df48838b82eb29e2bbe943594c94f2d81e7718 | phibzy/InterviewQPractice | /Solutions/MergeIntervals/mergeIntervals.py | 1,745 | 3.890625 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Thursday Nov 19, 2020 11:33:31 AEDT
@file : mergeIntervals
"""
class Solution:
def merge(self, intervals):
# if there's only one interval there's no merging to be done
if len(intervals) < 2: return intervals
#... |
e4ec3a572879a79bcb37850b02904cecbfdc4094 | raflisboa/curso_python | /list.py | 426 | 3.703125 | 4 | #lista
produtos = []
precos = []
quantidades = []
total = 0
while True:
print('Digite um produto:')
produto = input()
print('Digite um preco:')
preco = float(input())
print('Digite um preco:')
quantidade = int(input())
if produto == '':
break
produtos.append(p... |
7226c219fc3d7a7256e96c2c1e4c6164a7202983 | aikem26/test1 | /urok23/hw_22_23.py | 639 | 3.609375 | 4 |
def rev(num):
if num < 10:
return str(num)
else:
str_num = str(num)
digit = str_num[-1]
new_num = str_num[:-1]
return digit + rev(int(new_num), )
print(rev(179))
from random import randint
def generate_list_with_random_numbers(length):
lst = [randint(1, 10) for ... |
0e614d453f679fa0ba9b82102b520481181db7b3 | catherine7st/SoftUni-Python_Fundamentals | /Basic-syntax,-conditional-statements-and-loops/word_reverse.py | 251 | 3.96875 | 4 | # word = input()
#
# for index in range(len(word)-1, -1, -1):
# print(word[index], end="")
#
# word = input()
# result = ""
# for index in range(len(word)-1, -1, -1):
# result += word[index]
# print(result)
word = input()
print(word[::-1])
|
0dc8421daeb74bb740b8768bb64a56548ce91385 | EinarK2/einark2.github.io | /Forritun/Forritun 1/skila6.py | 3,041 | 3.65625 | 4 | #Höfundur Einar Karl
import random
val=" "
while val !="5": #Valmynd
print("--------------------------------------")
print("1. Random Tölur")
print("2. Talnabil")
print("3. Strengjalisti")
print("4. Samanburður")
print("5. Hætta")
val=input("Veldu 1-4 eða 5 til að hætta ")
... |
348dd5d0c5465c282bb5a46cb71c32aa4c6e9b4b | skinnerjake/Portfolio | /Python/ProjectEuler/Problem16.py | 231 | 3.71875 | 4 | #2 to the 15th power = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#What is the sum of the digits of the number 2 to the 1000th power?
x = str(2 ** 1000)
y = []
for i in x:
y.append(i)
z = sum(map(int, y))
print z |
87601cc7c78d35ef6e4f919f51dcf09752f62726 | TrivikramSiddavatam/TriCoding-100DaysOfPythonLearning | /Day10Of100.py | 3,955 | 4.34375 | 4 | #Functions with Outputs
# def format_name(f_name, l_name):
# formated_f_name = f_name.title()
# formated_l_name = l_name.title()
# return f"{formated_f_name} {formated_l_name}"
# print(format_name("TriVIKRAM", "sidDAVAtam"))
#multiple Return values
# def format_name(f_name, l_name):
# if f_name == "" or l_na... |
b3dd2ae318411c29686c0305df3f3c3827b37b3c | achen2289/UCLA-CS-CM122 | /stepik/chapter 9/9-16.py | 1,940 | 3.578125 | 4 | from collections import defaultdict
class tree_node:
def __init__(self, idx, color, children): # 0 = gray, 1 = red, 2 = blue, 3 = purple
self.idx = idx
self.color = color
self.children = children
def form_tree(parent_to_children, node_colors):
color_map = {"red": 1, "blue": 2}
for node, color in node_color... |
2668e779c902ccaeaa371c800595a451a3db94da | YuLiu83/Business-App | /Database_setup.py | 621 | 3.78125 | 4 | import sqlite3
import os
import pandas as pd
if os.path.exists('database.sqlite'):
os.remove('database.sqlite')
conn=sqlite3.connect('database.sqlite')
c = conn.cursor()
#c.execute(''' create table clients ([Label] INTEGER , [Text] text)''')
read_data=pd.read_csv(r'data.csv')
read_data.to_sql('Text_Data', conn, ... |
928c1b2f7bca9100fba6d5947887b44029ebb190 | kjh03160/Algorithm_Basic | /Kakao_2021/1.py | 782 | 3.515625 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/72410?language=python3
def solution(new_id):
new_id = new_id.lower()
REMOVE = '~!@#$%^&*()=+[{]}:?,<>/'
answer = ''
is_ = False
for i in new_id:
if i == "." and is_:
continue
if i not in REMOVE:
answer += i... |
cb25f99bf127848df1a15b7ea700290428e48e36 | kelpasa/Code_Wars_Python | /6 кю/Grouped by commas.py | 325 | 3.53125 | 4 | '''
Finish the solution so that it takes an input n (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.
Assume: 0 <= n < 2147483647'''
from textwrap import wrap
def group_by_commas(n):
return ','.join([i[::-1] for i in (wrap(str(n)[::-1],3))][::... |
b79d60f0ab93e65e22e4cab3f80a45b677114d23 | lymanreed/Dominoes | /Topics/Elif statement/Calculator/main.py | 360 | 4.03125 | 4 | x = float(input())
y = float(input())
op = input()
if op in ('/', 'mod', 'div') and y == 0:
print('Division by 0!')
elif op == '+':
print(x + y)
elif op == '-':
print(x - y)
elif op == '/':
print(x / y)
elif op == '*':
print(x * y)
elif op == 'mod':
print(x % y)
elif op == 'pow':
print(x **... |
072f4c700d1156201d434a7edda83b5fa3c71ebe | swipswaps/pytest-subprocess-example | /program.py | 289 | 3.90625 | 4 | import sys
name = input("What is your name: ")
try:
age = int(input("How old are you: "))
except ValueError:
print("Sorry, I could not understand your age!", file=sys.stderr)
sys.exit(1)
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
|
25c85abcfd50f2238e0e738e07d8813ef2e9b01a | klamb95/list_comprehension_end | /list_conditionals.py | 270 | 3.953125 | 4 | # numbers = range(1, 11)
# evens_squared = []
# for number in numbers:
# if number % 2 == 0:
# evens_squared.append(number * number)
# print(evens_squared)
evens_squared = [number * number for number in range(1, 11) if number % 2 == 0]
print(evens_squared) |
d4af8c6e30b163e695ebd9d27cdb956f04bbc06d | Tech-Tarun/Library-Management-System | /CentraLibrary.py | 1,942 | 3.578125 | 4 | def dump(a):
with open('file.txt', 'w')as f:
f.write(a)
def load():
with open('file.txt','r')as f:
j=convert(f.read())
return j
def convert(string):
li=list(string.split(","))
return li
def convert2(input_seq,seperator):
strr=seperator.join(input_seq)
return strr
... |
5d5803d75a69813ff9ba2ac931410cd956d774f8 | cabama/opencv | /practica1/histograma.py | 930 | 3.515625 | 4 | '''
PRACTICA: Histograma de una imagen en color.
Autor: Carlos Barreiro Mata
'''
# Importamos las librerias necesarias
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Variable que contiene la ruta de la imagen
IMAGEN = "resources/images/prueba.jpg"
# Leemos la imagen y la guardamos en la variabl... |
895bda921fcf5249252cfc831d9f05ce09b9f471 | cesarbhering/30-days-of-code-HackerRank | /13-AbstractClasses.py | 255 | 3.609375 | 4 | class MyBook(Book):
def __init__(self, title, author, price):
Book.__init__(self, title, author)
self.price = price
def display(self):
print(
f'Title: {self.title}\nAuthor: {self.author}\nPrice: {self.price}')
|
0995d1f1b79ba2f70a9a550e914f158f286aee0e | LucasInhaquite/AutomationPython | /ConditionHandlingIfElse.py | 349 | 4.21875 | 4 | i = 10
# Check number is greater then 100 then print "GREATER"
# Else number is Smaller
inputNumber = input("Please digit your number --> ")
# All inputs from users are stored as String so we need to cast the value as int to use numeric operators
if (int (inputNumber) > 100):
print("Number is Greater")
else:
... |
28b607e5c0c840df55d9a20bd0b76878729a9f78 | VictorMinsky/Algorithmic-Tasks | /Codewars/7 kyu/Sum the Repeats.py | 716 | 3.984375 | 4 | """
Write a function that takes a list comprised of other lists of integers and returns the sum of all numbers that appear in two or more lists in the input list. Now that might have sounded confusing, it isn't:
repeat_sum([[1, 2, 3],[2, 8, 9],[7, 123, 8]])
>>> sum of [2, 8]
return 10
repeat_sum([[1], [2], [3, 4, 4, ... |
1b615ef56739daa2c2e3051cdfdd0c1582eb3252 | Kaph-Noir/Python | /bubbleSort.py | 1,600 | 3.84375 | 4 | # by myself
def bubbleSort(lst):
for i in range(1,len(lst)):
# print(i)
j = i-1
while lst[j] > lst[j+1] and j >= 0:
# print(j)
lst[j+1], lst[j] = lst[j], lst[j+1]
# tmp = lst[j+1]
# lst[j+1] = lst[j]
# lst[j] = tmp
j -= ... |
3b708c73e95d3c8ab74aadd9b15f980235483fa3 | arnav-gupta-123/Tic-Tac-Toe-Game | /main.py | 5,639 | 4.375 | 4 | import random
#Global Variables
tictac_list = [["_","_","_"],["_","_","_"],["_","_","_"]]
row_num = ""
col_num = ""
#Prints the instructions for 1 player mode
def instructions_1():
print()
print("1) Your mark will be an X and the Computer's mark will be an O.")
print("2) When prompted, enter the place where you... |
87690f1e9806f0fd6ce46359a59f9042030f18e5 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/0ac5110abcab45718e448540af56b276.py | 201 | 4.125 | 4 | # This function returns a dictionary with a string's unique words and the
# number of times they occur in the string.
def word_count(str):
a = str.split()
return {i : a.count(i) for i in a}
|
fd1f9cc2bf32537583286cf316d2992137276a1c | sfa119f/tugas4-kriptografi | /function.py | 3,086 | 3.515625 | 4 | def isPrime(n):
# Mengetahui apakah n adalah bilangan prima
if n == 2 or n == 3: return True
elif n < 2 or n % 2 == 0: return False
elif n < 9: return True
elif n % 3 == 0: return False
else:
maxVal = int(n**0.5)
temp = 5
while temp <= maxVal:
if n % temp == 0: return False
if n % (tem... |
1d4f284b5f5a66a916ef858f2747384200d86c05 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/hllbra005/question2.py | 208 | 4.0625 | 4 | h = eval(input("Enter the height of the triangle:\n"))
spaces = h-1
stars = 1
for i in range (h):
print (" "*spaces, sep = "", end = "")
print ("*"*stars)
stars += 2
spaces -= 1
|
c895ab6abf83ea812f734853e4a0750e413d5a63 | rafaelperazzo/programacao-web | /moodledata/vpl_data/56/usersdata/138/23587/submittedfiles/av2_p2_m2.py | 555 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
def soma(a,ent,saida,v):
i=0
b=[]
soma=0
while i<=len(a):
soma=soma+a[i]
b.append(soma)
i=i+1
return soma
def maior(b):
for i in range(0,len(b),1):
if b[i]>b[i+1]:
maior = b[i]
if b[i]>m... |
620752531cb336e1bb778b9c313ae5322fdfe321 | nixxby/alien-invasion | /alien_invasion/ship.py | 1,296 | 3.8125 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Creates and Manages the behaviour of our Ship"""
def __init__(self,screen,settings):
"""Initialize ship and it starting position"""
super().__init__()
self.screen = screen
self.image = pygame.image.load('alien_invasion/im... |
a17302d5980b605b712aa044e2f2166fc6215014 | tung491/algorithms | /graph/max_subset_sum_no_adjacent.py | 513 | 3.765625 | 4 | def max_subset_sum_no_adjancent(input_list: list) -> list:
if not input_list:
return
elif len(input_list) == 1:
return input_list[0]
max_subset = input_list[:2]
second = input_list[0]
first = max(input_list[:2])
for n in input_list[2:]:
curr_sum = max(first, second + n)
... |
6f4aaa8ffc7822f165837a787b12e4a96def0bd2 | MatthewTurk247/Programming-II | /Functions and Modules.py | 1,091 | 3.53125 | 4 | from math import *
# is a wildcard, anything...just imports the whole thing, now instead of math.cos, you can just use cos
# however sometimes you may cause issues when the libraries overlap variable names
from random import randrange
from imports import my_import
# Functions
def my_function(name):
'''
Says ... |
33000602dfec84ec46ca81a172b64765028b8441 | kinect59/Python-Programming-for-Machine-Learning | /Python/Deep-Learning-with-Keras/custom_optimizer_losses_metrics.py | 920 | 4.0625 | 4 |
""" Program description: Create three-layer neural network in Keras """
from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(16, activation = 'relu', input_shape = (1000,)))
model.add(layers.Dense(16, activation = 'relu')
model.add(layers.Dense(1, activation... |
c34dec8a62b15117f1f467c9f8954b50a9c4b7ae | Glightman/Entrega_Blue_Modulo1 | /exercíciosEntrega08.py | 922 | 3.984375 | 4 | """ 08 - Crie um programa que leia nome,
ano de nascimento e carteira de trabalho e
cadastre-os (com idade) em um dicionário.
Se por acaso a CTPS for diferente de 0,
o dicionário receberá também o ano de contratação e o salário.
Calcule e acrescente , além da idade, com quantos anos a pessoa vai se aposentar.
Con... |
aab7d2b57de46c3a76311a139933693a6ab4723c | Saalu/trying_Python | /google/regex/Mon.py | 427 | 3.78125 | 4 | import re
def hide_email(email):
regex = re.sub(r"[\w.%+-]+@[\w.-]+", "[REDIRECTED]", email)
if email is None:
return "Incorrect email!"
return regex
def rearrange_name(name):
regex = re.sub(r"([\w .-]*),([\w .-]*)$", r"\2 \1", name)
if name is None:
return "Doesn't match pattern"
... |
287811f075c5d3006f4ae5dfba16aa697f81483f | chowsychoch/Programming-1- | /p18/p18p2.py | 516 | 3.90625 | 4 | #define a Function
#using count function and return the result
def check_string(str):
"""Function that count the number of code in string"""
x = str.count('code')
return x
print(check_string('CodecodecodecodecodeCode'))
def check_string(str):
"""Function that count the number of code in string"""
... |
9fac5ebef82dade07a95a5c40dac3f80ab2c1b47 | SuShweCinAung/CP1404practicals | /CP1404practicals/prac_04/list_exercises.py | 456 | 4.09375 | 4 | def main():
numbers = []
for i in range(5):
number = int(input("Number: "))
numbers.append(number)
minimum = min(numbers)
maximum = max(numbers)
average = sum(numbers)/len(numbers)
print("The first number is ",numbers[0])
print("The last number is ",numbers[-1])
print("Th... |
f5e72d402424bbcf5152b95db3430490d7f424e7 | tim-jackson/euler-python | /Problem4/palindrome.py | 807 | 4.125 | 4 | """palindrome.py: Problem 4 of project Euler.
Calculates the largest product of two 3-digit numbers"""
HIGH_TOTAL = 0
FIRST_DIGIT = 999
def is_palindrome(number):
""" Checks if the number supplied is palindromic. """
# Reverse the strip using ::-1
if str(number) == str(number)[::-1]:
return True
... |
349e8673e30771b939cd49733714346636760b1a | thabied/mypackage | /tmp/sorting.py | 2,662 | 4.5625 | 5 | def bubble_sort(items):
"""
The bubble sort algorithm takes in an unsorted list of numbers
and returns a list in ascending order.
Args:
items(list) : list of unordered numbers
Returns:
an array of a list of items in ascending order
Example:
>>>bubble_sort([5,4,3,2,1])
... |
e1d16991c00f5635282db3caeb938534a519fbbf | relarizky/crush | /crushasher/general/wordlist.py | 711 | 3.828125 | 4 | # Author : Relarizky & Gibran
# Github : @relarizky & @gibran-abdillah
# File : wordlist.py
# Last Modified : 11/23/20, 08:36 AM
# Copyright © 2020 Relarizky x Gibran
import os
def is_file_exist(file_name: str) -> bool:
""" check existence of the wordlist file """
return os.path.isfile(file_name)
def r... |
05714e6d90eb94558cf45acbb38e218b36cd0c69 | medvedodesa/Lesson_Python_Hillel | /Lesson_5/example.py | 261 | 4.125 | 4 | even = 0
odd = 0
min_val = 0
max_val = 0
i = 0
while i < 10:
num = int(input('Please enter a number: '))
if not num % 2:
odd += 1
else:
even += 1
if i == 0:
min_val = max_val = num
i += 1
print(odd)
print(even)
|
648905f5d1d15cccd1a9356204ad69db0f30ce31 | Roooommmmelllll/Python-Codes | /rightTriangleTest.py | 970 | 4.21875 | 4 | def getSides():
print("Please enter the three sides for a triagnle.\n" +
"Program will determine if it is a right triangle.")
sideA = int(input("Side A: "))
sideB = int(input("Side B: "))
sideC = int(input("Side C: "))
return sideA, sideB, sideC
def checkRight(sideA, sideB, sideC):
if sideA ... |
9e45c590d0eae464075a4dd559e73b1c5bca287a | aidanrfraser/CompSci106 | /RectangleArea.py | 282 | 3.640625 | 4 | #Working with Rohan & Jack
from cisc106 import assertEqual
def rectangleArea(l, w):
"""
Finds area of a rectangle with length l and width w
"""
return l * w
assertEqual(rectangleArea(4,0),0)
assertEqual(rectangleArea(5,5),25)
assertEqual(rectangleArea(10,5),50) |
d5b0c9ddedb173402e0f00c3e996811cc3c79528 | xili-h/PG | /ISU3U/Exam/Lots_O_Numbers.py | 1,639 | 4 | 4 | def main():
import time
print('Lots O Number Hard')
print()
go = True
while go:
try:
start = int(input('What number do you want to start at? '))
except:
pass
else:
go = False
go = True
while go:
try:
end = ... |
c8ad5820b15538e2d873eb2420bfcc8e31fca849 | GiulioSF/Python | /Mundo_2/Exercicios/exercicio_70.py | 638 | 3.5625 | 4 | total = contmenor = cont = 0
barato = ' '
while True:
produto = str(input('Nome do Produto: '))
valor = int(input('Preço: R$ '))
contmenor += 1
total += valor
if valor > 1000:
cont += 1
if contmenor == 1 or valor < menor:
menor = valor
barato = produto
opcao = ' '
... |
5df37301cf272d0196aff8dc66e54629523976dc | csitedexperts/DSML_MadeEasy | /Python2.xPractice/ex11_3x.py | 283 | 3.578125 | 4 |
exno = "This is exercise no: %d" %6
print (exno)
print ("How old are you?",)
age = raw_input()
print ("How tall are you?",)
height = raw_input()
print ("How much do you weigh?",)
weight = raw_input()
print ("So, you're %d old, %d tall and %d heavy." % (
age, height, weight))
|
5ab617c30db400b84ed8942fc8aeff432800aea9 | studyml-lab/Python-Basics | /3.tuples.py | 325 | 3.65625 | 4 | #tuple: immutable list
tuple1 = (1, 8, 27, 64, 125, 216, 64)
type(tuple1)
tuple1[0]
tuple1[-1]
tuple1[0:3]
tuple1[2] = 100 # will through an error
len(tuple1)
tuple1.count(64)
for x in tuple1:
print(x ** 2)
list1 = list(tuple1)
type(list1)
shape2 = (10, 20, (40,50), True)
len(shape2)
shape2[2]
shape2[2]... |
ab7a97f63e3c407f8e04124a8dd0f9b684c9a058 | wtfigo/python0801 | /ex05-1.py | 165 | 3.515625 | 4 | import datetime
x = [1984, 1982, 1990, 1985, 1976, 1991]
i = 0
j = len(x)
now = datetime.datetime.now()
while i < j:
k = x[i]
print(now.year - k)
i += 1 |
1e6b1e2a4f428c4c5976ad5cac262ee0ef16ebe6 | ErvinCs/FP | /Lab10-Battleships/src/domain/Board.py | 1,470 | 3.9375 | 4 | class Board:
def __init__(self, size, name):
self.__size = size
self.__board = [[0]*(size+1) for i in range(size+1)]
self.__name = name
#0 - None; X - Hit; M - Miss
def getSize(self):
return self.__size
def setSize(self, size):
self.__size = size
def ge... |
52a0d30a646e7ae3c1f379f54f6a6b63bc1c6e24 | l897284707/index | /第二题.py | 203 | 3.65625 | 4 | tup1=(1,'python',4.5,20,100,90)
tup2=(2,5,6,1,90,100,32,300,0)
print(tup1[3])
print(tup1[5])
tup3=tup1+tup2
for i in tup1:
print(i,end=' ')
print()
print(len(tup2))
print(max(tup2))
print(min(tup2)) |
3254d2a310d9417de399802a1c95c3533334ec24 | AkhilReddykasu/strings | /49.Count and display the vowels of a given text.py | 368 | 4.21875 | 4 | """count and display the vowels of a given text"""
txt = input("Enter a string:")
vowels = "aeiou"
vowels_in_txt = ''
count = 0
for i in txt:
if i in vowels:
count += 1
if i not in vowels_in_txt:
vowels_in_txt += i
print("Numbers of vowels in given text:",count)
print("vowel... |
f9184f9a39d2b3a0a9732b3295eb20d31abaff62 | sofiamalpique/fcup-programacao-01 | /5.1.py | 142 | 3.625 | 4 | def triangular(n):
k=0
s=0
while s<n:
k=k+1
s=s+k
if s==n:
return True
else:
return False
|
a1d5582d91dcbb46f6f4f8747162d795cac882cf | proldapru/stepik | /67-python-begin/task028.py | 660 | 3.71875 | 4 | n, m = int(input()), [[]]
# Формирование почти пустой матрицы
m[0] = [i+1 for i in range(n)] # первая строка заполнена сразу
for i in range(n - 1): # в остальных строках нули
m.append([0] * n)
# Заполнение матрицы
counter, goal, steps, row, col = n, n * n, n, 0, n - 1
while counter < goal:
for move in range(4):
... |
02d6d674415cd888d00254ea192598ff865e19bf | lovehhf/LeetCode | /contest/第 17 场双周赛/5143. 解压缩编码列表.py | 726 | 3.703125 | 4 | # -*- coding:utf-8 -*-
"""
给你一个以行程长度编码压缩的整数列表 nums 。
考虑每相邻两个元素 [a, b] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后有 a 个值为 b 的元素。
请你返回解压后的列表。
示例:
输入:nums = [1,2,3,4]
输出:[2,4,4,4]
提示:
2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100
"""
from typing import List
class Solution:
def decompres... |
9f7ee6ffc8c3dd4392c25ad9d98fb2deee1d40c3 | KishoreMayank/CodingChallenges | /Interview Cake/Combinatorics/AppearsTwice.py | 412 | 3.984375 | 4 | '''
Appears Twice:
Return the number that appears twice in a list of size n + 1 with elements that
range from the values of 1...n
'''
def appears_twice(nums):
if len(nums) < 2:
raise ValueError()
n = len(nums)
sum_nums = (n * (n - 1)) / 2 # take the sum of what it should be
diffe... |
2734bc145bcccfb1a077ea9e35ffde7b48a552be | Hellofafar/Leetcode | /Medium/688.py | 2,660 | 3.671875 | 4 | # ------------------------------
# 688. Knight Probability in Chessboard
#
# Description:
# On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make
# exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and
# the bottom-right square is (N-1, N-1).
... |
ee8809b37810fbebd2757938abe5acd625f7b1f9 | ta326/kg_ta326_2021 | /main.py | 668 | 3.78125 | 4 |
# Module sys for importing arguement
import sys
a = sys.argv[1]
b = sys.argv[2]
# this function prints true, if string a can be mmapped to string b or else it prints false
# Precondition: mapping has two arguements
def mapping(a, b):
# if a has a smaller length, mapping of all character of a is not possible
... |
f553be72d4f6e8825461471f45a0f26b809f0ff8 | chloe-wong/pythonchallenges | /AS13.py | 208 | 3.546875 | 4 | gp = float(input("input gross profit"))
np = float(input("input net profit"))
s = int(input("sales"))
gpm,npm = (gp/s)*100, (np/s)*100
print("Gross Profit Margin:",gpm,"%")
print("Net Profit Margin:",npm,"%") |
9de3e563c89e591212eafb963fd327dea48e3bbc | aurlien/AdventOfCode2020 | /d12/ex2.py | 1,438 | 3.828125 | 4 | import math
FORWARD = 'F'
LEFT = 'L'
RIGHT = 'R'
NORTH = 'N'
SOUTH = 'S'
EAST = 'E'
WEST = 'W'
def parse_instruction(s):
action = s[0]
value = int(s[1:])
return action, value
def left(degrees, dx, dy):
times = degrees // 90
if times == 0:
return (dx, dy)
return left(degrees-90, dx=-d... |
50e3df56a5be3d0ff90150324e1958bcfeb2d1d0 | zhengjiani/pyAlgorithm | /leetcodeDay/April/prac42.py | 3,134 | 4.03125 | 4 | # -*- encoding: utf-8 -*-
"""
@File : prac42.py
@Time : 2020/4/4 8:49 上午
@Author : zhengjiani
@Email : 936089353@qq.com
@Software: PyCharm
单调栈,单调队列
"""
class Solution:
"""按行求解,提交后超出时间限制"""
def trap(self, height):
sum = 0
max_h = max(height)
for i in range(1,max_h+1):
... |
1018b85872930cd72b4956ca8d2e9c166e51303e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2325/60722/249606.py | 232 | 3.5625 | 4 | card=input().split(",")
new_card=list(set(card))
result=True
for i in range(1,len(new_card)):
if card.count(new_card[0])!=card.count(new_card[i]):
result=False
if card.count(new_card[0])<2:
result=False
print(result) |
a25683cdf4bcd1d27017cd3fc264aff73e022017 | muhlik20033/muhlik20033 | /TSIS 6/3.py | 105 | 3.546875 | 4 | def multi(a: tuple):
n = 1
for i in a:
n *= i
print(n)
multi((8, 2, 3, -1, 7)) |
0fc4cc68701cc41a634154f68cb1592ac2c3d40d | adesanyaaa/ThinkPython | /mostFrequent.py | 557 | 3.859375 | 4 | """
Modify the program from the previous exercise to print the 20 most frequently-used
words in the book.
"""
import operator
import re
from collections import Counter
Text = []
with open('book.txt') as text:
next(text)
for lines in text:
Text = Text + re.findall(r"[\w']+", lines)
print(len(Text))
cnt ... |
1269421f0d5fb7ef466fb003d040fffedcd35bcb | jincheol5/2021_python | /4주차/4_1.py | 88 | 3.65625 | 4 | s=input()
n=int(input())
i=0
str=""
while i<n:
str+=s
i+=1
print("String =",str) |
d4b071c2a02763e1841f8d9bb9fe4a93a01cfec8 | andriitugai/python-morsels | /leetcode/three_sum_2.py | 1,157 | 3.78125 | 4 |
def threeSum(A):
'''
:type A: list of int
:rtype: list of list of int
'''
def twoSum(arr, target):
"""
:type arr: list of int
:type target: int
:rtype: list of unique pairs
"""
if not arr or len(arr) < 2:
return []
additions = {}... |
9900382c264e1e97f278d0d949796d44949dc021 | OsProgramadores/op-desafios | /desafio-02/rodineicosta/python/numeros_primos.py | 619 | 3.90625 | 4 | #!/usr/bin/python3
'''
Programa para listar todos os números primos entre 1 e 10000.
'''
from math import sqrt
def main():
'''
Array de números primos
'''
num_primos = []
def np_primo(numero):
'''
Verificação de primalidade
'''
if numero < 2:
return Fa... |
66ba46b693351a8aa9ef65720037580afb341b9e | ashwani8958/Python | /PyQT and SQLite/M5 - Connecting to SQLite Database/program/practice/2_python_conn_sql/5_fatch_one_record.py | 382 | 3.75 | 4 | #fatch one record at a time
import sqlite3
#connect to the database
MySchool = sqlite3.connect('schooltest.db')
#create the handle
curschool = MySchool.cursor()
sql = "SELECT * FROM Student;"
curschool.execute(sql)
#loop to print all the record
while True:
record=curschool.fetchone()# will print one record at... |
be37ef6acd1a4f708cd7ca9b4faee0366ccd2661 | w27/algorithms_courses | /tasks/bubble_sort.py | 190 | 3.59375 | 4 | from typing import List
def bubble_sort(arr: List[int]) -> List[int]:
"""
Bubble sort
:param arr: list of elements to be sorted
:return: sorted list
"""
return arr
|
86560cdf2c060a592039eedb361e0ed2d80d1f6a | Joshua-Enrico/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 494 | 3.625 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
if roman_string is None or isinstance(roman_string, str) is False:
return 0
letter = {'I': 1, 'V': 5, 'X': 10,
'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
maxchar = 'I'
new_list = roman_string[::-1]
for elm2 in new_li... |
4f0dc0fe37834dc5d74f5e1b1e35e6f8531e2179 | jaybenaim/python-intro-pt4 | /exercise10.py | 2,255 | 3.59375 | 4 | line_break = "-----------------------------------------------------------------------------------"
students = {
'cohort1': 34,
'cohort2': 42,
'cohort3': 22
}
# function- display name and number or each student
def display_name_and_num(dict_name):
for student, number in dict_name.items():
print(f'... |
040277d8a2cc89947292bed5a44c9b0bbd0e6056 | swimbikerun96/Brian-P.-Hogan---Exercises-for-Programmers | /#18 Temperature Converter/Temperature Converter v1 - Constraints.py | 2,215 | 4.25 | 4 | #Function for Fahrenheit To Celsius
def ftc(degrees):
f = degrees
c = (f-32) * (5/9)
return f'The temperature in Celsius is {c}'
#Function for Farhenheit to Kelvin
def ftk(degrees):
f = degrees
k = (((f - 32) * 5)/9) + 273.15
return f'The temerature in Kelvin is {k}'
#Function for Cels... |
5f0e74cbf778d5c1a305a10d9348ad24df32a69e | zxycode-2020/python_base | /day07/1-装饰器/装饰器.py | 389 | 3.90625 | 4 | '''
概念:是一个闭包,把一个函数当做参数,返回一个替代版的函数,本质上就是一个返回函数的函数
'''
#简单的装饰器
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("*******************")
func()
return inner
#f是函数func1的加强版本
f = outer(func1)
f()
|
3767d6b037c8cf61ee38cba060f618894867cfbe | driabwb/CSCI3155Paper | /test.py | 911 | 4.1875 | 4 | #!/bin/usr/python
# works in python 3 with the PEP implemented
# but not in python 2 without it
def make_counter_nonlocal():
count = 0
def counter1():
nonlocal count
count += 1
return count
return counter1()
# does not work, count is outside of the scope of counter2
def make_counte... |
2a6c43e1e1e6f0229bdb53a7e9e22cdb1709e5d0 | matheusfelipeog/uri-judge | /categorias/iniciante/uri2510.py | 88 | 3.53125 | 4 | # -*- coding: utf-8 -*-
t = int(input())
for i in range(t):
input()
print('Y')
|
3011e7c15298f090d79af4c919efe72ad1d50ec7 | sivareddykostam/Python_practices | /python/set_method.py | 595 | 3.53125 | 4 | #//--------------------------------------------------------------------------------------------
#// set_methods
#//--------------------------------------------------------------------------------------------
'''
set={"app","telsuko","learning"}
set.add("phone")
print(set)
'''
'''
set={"app","telsuko","learning"}
set1... |
8f8cde5f3e005e79851684836c26992975ba531a | Niveditasankar1901/Best-Enlist-Internship | /day9.py | 3,204 | 4.25 | 4 | #Day 9
# Write a program to loop through a list of numbers and add +2 to every value to elements in list
p=[1,2,3,4,5]
for i in p:
i=i+2
print (i)
#Output:-
#3
#4
#5
#6
#7
# Write a program to get the below pattern
n = 5
for i in range(n, 0, -1):
num = i
for j in range(i,0,-1):
... |
46222466d4aa80d99cc851a69b8d50c25d5f40e5 | junque1r4/treino.py | /Py3Guanabara/des094.py | 1,104 | 3.640625 | 4 | pessoa = dict()
grupo = list()
idades = 0
meninas = list()
while True:
pessoa['nome'] = str(input('Nome: '))
pessoa['sexo'] = str(input('Sexo: [F/M]: ')).lower()[0]
while pessoa['sexo'] not in 'fm':
pessoa['sexo'] = str(input('Valor incorreto! Somente F e M: '))
if pessoa['sexo'] == 'f':
... |
aea97a873aa1bbe20d6634d698e00f336ddc4706 | daviramalho/Learn_python | /2017_SHAW/ex06.py | 1,377 | 4.625 | 5 | types_of_people = 10
x = f"There are {types_of_people} types of people." #This is not a string.
#Previous one defines two variables with a numeric string, "types_of_people",
#inside another string, "x".The "f" before the string alows it to append the
#string inside the other.
binary = "binary"
do_not = "don't"
y... |
b048df5375c8e42b937fc3df8cb9f44bbffec0ce | avijeet-shar/GUI_programs_python | /try3.py | 18,499 | 3.5 | 4 | from tkinter import *
from PIL import ImageTk, Image
import tkinter.ttk as ttk
import tkinter as tk
from tkinter import messagebox, Label, Button, FALSE, Tk, Entry
import csv
global Marquee
class Marquee(tk.Canvas):
def __init__(self, parent, text, margin=2, borderwidth=1, relief='flat', fps=30):
... |
45862bdaf77a46e68061381172068d4759599838 | taymosier/Python-Practice | /string_match.py | 508 | 4.03125 | 4 | '''
Given 2 strings, a and b, return the number of the positions where
they contain the same length 2 substring.
So "xxcaazz" and "xxbaaz" yields 3, since the
"xx", "aa", and "az" substrings appear in the same place in both strings.
'''
def string_matches(a,b):
count = 0
shorter_string = min(len(a),le... |
b6d8c0c294a81b723386862a096a6a976606a4a1 | vitor-rc/Introdu-o-Ci-ncia-da-Computa-o-com-Python | /sem3_exerc5_orderm_cresc.py | 151 | 4 | 4 | x1 = int(input())
x2 = int(input())
x3 = int(input())
if x1<=x2 and x2<=x3:
print("crescente")
else:
print("não está em ordem crescente") |
978eff661558ddf2b6a837ad7c31158d602464b7 | Abis47/HH-PA2609-1 | /24_LR/2LR.py | 6,936 | 3.609375 | 4 | #Topic ---- Dividing Data into Train and Test
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pydataset import data
from sklearn.linear_model import LinearRegression
mtcars = data('mtcars')
data=mtcars
data.head()
data.columns
data.dtypes
data.shape
model = LinearRegression()
ds= ... |
f2fe21803d6630cd701ffde3467df2ba05b18772 | vvenkatesh-vv/infrastructure-assignment | /top10indrive.py | 2,379 | 3.6875 | 4 | import os
count = 0
list = None
#prints attributes of linked list passed
def printf(list):
temp=list
while temp!=None:
print(temp.name,end=' ')
print('& size = ', end='')
print("%.2f" % temp.size, end=' MB')
print(' & path = ', end='')
print(temp.path)
... |
2c9406b4cff87d5c909f9f76c6201d96bd68bcf1 | rafaelperazzo/programacao-web | /moodledata/vpl_data/405/usersdata/277/75605/submittedfiles/exe11.py | 95 | 3.921875 | 4 | # -*- coding: utf-8 -*-
num = int(input('Digite num: '))
if (num%(10**7) != 0)
print('DIF') |
4a52a4d0f027d0bb7e1be01c20c1a91c4f9ec1a9 | Bushidokun/Python | /Main/Week 2/6.Simple Decisions/3 IF...ELIF...ELSE Statement/Activity2.py | 286 | 4 | 4 | print ("What are you?")
entity = input()
if (entity == "Human"):
print("You are a human!")
elif (entity == "Robot"):
print("You are a robot!")
elif (entity == "Animal"):
print("You are an animal!")
else:
print("I do not know what you are!")
print("Analysis complete.") |
497b240a2e8d0eb4954dbb4370ba374d5e00dcd0 | sandeep-singh-79/DynamicProgramming | /canSum/canSum.py | 172 | 3.609375 | 4 | def canSum(sum, arr):
if sum == 0: return True
if sum < 0: return False
for i in arr:
if canSum((sum - i), arr) == True: return True
return False
|
fa2373dc53bf1c8ea7ef6b54d4e6a8c9a0ab17c0 | AhmedAbdelkhalek/HackerRank-Problems | /Algorithms/Warmup/Staircase.py | 269 | 3.90625 | 4 | #!/bin/python3
# Easy
# https://www.hackerrank.com/challenges/staircase/problem
# enter the number of rows required
n = int(input().strip())
# starts with 1 and compensate with n+1
for i in range(1,n+1):
# print the # right aligned.
print(("#" * i).rjust(n))
|
2434b546d60f754938cd8b14b54fe199574c0a19 | johndurde14/Python_Learn | /《Python编程从入门到实践》/08-函数/eg_formatted_name2.py | 1,052 | 3.828125 | 4 | #coding = utf-8
class FormattedName():
def __init__(self):
pass
def get_formatted_name1(self, first, last):
"""没有中间名字,返回整洁的姓名"""
full_name = first + " " + last
return full_name.title()
def get_formatted_name2(self, first, last, middle = ''):
... |
1751a5fa4fdcdaafa2907352a17640e9cfcbba6f | MemoryForSky/Data-Structures-and-Algorithms | /sort/bucketSort.py | 1,919 | 3.703125 | 4 | """
桶排序:
基本思想:
将一个数据表分割成许多buckets,然后每个bucket各自排序,或用不同的排序算法,或者递归的使用bucket sort算法。
也是典型的divide-and-conquer分而治之的策略。它是一个分布式的排序。
时间复杂度:O(N)+O(M*(N/M)*log(N/M)) = O(N+N*(logN-logM)) = O(N+N*logN-N*logM)
"""
class node(object):
def __init__(self, initdata):
self.data = initdata
self.next = None
def get... |
e78788cd4a9801c66766a7c40e7268a36730e979 | bdmcewen/Java | /Course work/McEwen_Assignment_1/Assignment_1/Assignment1Preamble.py | 1,963 | 4.34375 | 4 | # Demo1 -- Mathematical Operations
print()
print("Demo1 -- Mathematical Operations")
a = 10
b = 5
c = 30
sum = a + b + c
avg = sum / 3
print(sum, avg)
# Demo2 -- User input (strings)
print()
print("Demo2 -- User Input (strings)")
name = input("Enter your name => ")
nickname = input("Enter your nickname => ")
print("H... |
048580a45db0af3653c68f7791edfedd8da69445 | VividLiu/LeeCode_Practice | /57_Insert_Intervals/insertInterval.py | 2,008 | 4 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
"""
Time complexity: O(n), n the total number of intervals in intervals list
Space complexity: maximally O(n)
"""
class Solution(object):
def insert(self, intervals, newInter... |
a4f8a5f7e3a204345567c18b9f8b5532d5f74607 | austinwellman3/Project | /Lists, indexing, dictionaries, and other common data structures/main-4.py | 4,155 | 3.953125 | 4 | Created by: Austin Wellman
if __name__ == '__main__':
# printing header
all_work = {}
all_work['sum'] = []
all_work['print'] = []
print('*** Welcome to the Learn Python Because it is Really Cool Tutorial ***\n')
# menu
while (True):
print("What do you want to learn today... |
1568dbfa6840baa365781872bc199bd9bc11baa3 | Oziichukwu/python-Repository | /python_exercises/circle.py | 289 | 4.40625 | 4 | radius = int(input("Enter the radius\n"))
area = 3.14159 * radius * radius
print("The area of the circle is ",area)
diameter = radius * 2
print("The diameter of the circle is ", diameter)
circumference = 2 * 3.14159 * radius
print("The circumference of the circle is", circumference) |
e39e6b70063079b3ecec7864f08136535a0b04c1 | rewonderful/MLC | /src/zhaohang/problem_1.py | 685 | 3.578125 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
def get_least_operations(n,m,nums):
cnt = 0
min_nums = []
for i in range(n-1):
min_nums.append(min(nums[i+1:]))
min_nums.append(nums[-1])
flag = False
for i in range(n):
if min_nums[i] < nums[i]:
cnt += nums[i] - min_nums[i... |
02b55a0b48d131097be0d777be8584bfec4b98fb | chengshq/week9 | /bubble_sort.py | 560 | 4.3125 | 4 | import random
def sort(items):
# 1. TO DO: Implement a "bubble sort" routine here
for position in range(len(items)-1, 0, -1):
for i in range(position):
if items[i] > items[i+1]:
items[i], items[i+1] = items[i+1], items[i]
return items
numbers = list(range(10))
random.shuffle(numbers)
assert list(range(... |
de45f239c2b5d462ccb895ff80ddec4d37370d34 | mason-terry/machine-learning-course | /stats-practice/multiple-linear-regression.py | 2,539 | 3.984375 | 4 | #!/usr/local/bin/python3
# Multiple Linear Regression
class Multiple_Linear_Regression:
''' will create the multiple linear regression formula '''
''' enter three lists and it create b0, b1, and b3 coefficients '''
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
self.b1, self.b2 = se... |
1774c46d20670f98b21d4b06c0cc2c097aa9d286 | ssgsj-carranza/RPSLS | /run_game.py | 3,577 | 3.90625 | 4 | from player import Player
from human import Human
from comphuman import Computer
from gestures import Choices
class RunGame:
def run_gesture(self):
self.welcome_message()
self.display_rules()
# self.choose_gesture()
def welcome_message(self):
input("Welcome to RPSLS! Press ent... |
798175ffddd0b4045c060136398aeefb59f03516 | josephlee3454/game-of-greed-1 | /game_of_greed_1/game_of_greed.py | 6,138 | 3.75 | 4 | import random, itertools
from collections import Counter
class GameLogic:
"""
Gamelogic class
"""
def __str__(self):
return "gamelogic static methods"
@staticmethod
def roll_dice(count):
"""
generates random integer for our dice roll
Returns:
integer
"""
random.randi... |
e8fff27b548e6118ce112ebb7a92cbd542c8c90e | Shuravin/python_practice | /Python for Data Analysis/3.1-list.py | 734 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 10 15:06:35 2020
@author: pauls
"""
import bisect
a_list = [1, 2, 3, None]
tup = ("foo", "bar", "baz")
b_list = list(tup)
b_list[0] = "I hate everything"
r = list(range(0, 10, 2))
b_list.append("kozlina")
b_list.insert(2, "astrology")
#print("goblin" in b_list)
... |
8ba54983e731d17f8315d7bdb43edc52685977f8 | megsmahajan/informationretrieval | /IR/stemming.py | 16,793 | 4.46875 | 4 | """
Description: Stem a word using the porter's stemming algorithm.
Input: a str word, e.g. 'interesting'
Output: a str word after stemming, e.g. 'interest'
"""
# The function vc_num returns the measure of any word or word part.
# Any word, or part of a word, has the following form :
# m
# [C] (VC) [V]
# ... |
e624ba9aab33f7197ae3819470ade4ca95243668 | QianqianShan/Python_for_Everybody | /Using-Python-to-Access-Web-Data/assign13 extracting data from JSON.py | 1,552 | 4.5625 | 5 | # Extracting Data from JSON
# In this assignment you will write a Python program somewhat similar to
# http://www.pythonlearn.com/code/json2.py.
# The program will prompt for a URL, read the JSON data from that URL using urllib and
# then parse and extract the comment counts from the JSON data, compute the sum of the... |
84d7cdb6fa84a379be1da943b21980834869f76a | JakubKazimierski/PythonPortfolio | /AlgoExpert_algorithms/Medium/PhoneNumberMnemonics/test_PhoneNumberMnemonics.py | 1,317 | 3.59375 | 4 | '''
Unittests for PhoneNumberMnemonics.py
February 2021 Jakub Kazimierski
'''
import unittest
from PhoneNumberMnemonics import phoneNumberMnemonics
class test_PhoneNumberMnemonics(unittest.TestCase):
'''
Class with unittests for PhoneNumberMnemonics.py
'''
def SetUp(self):
'... |
50d93ecdcb0fe84019df79adcb3760dc85d66907 | brandonbayliss8/Number-plate-Generator-UK | /Number Plate.py | 769 | 3.9375 | 4 | from random import randint
upperCaseLetter=chr(randint(65,90)) #Generate a random Uppercase letter (based on ASCII code)
upperCaseLetter1=chr(randint(65,90))
upperCaseLetter2=chr(randint(65,90))
upperCaseLetter3=chr(randint(65,90))
upperCaseLetter4=chr(randint(65,90))
Number=chr(randint(49,57))
Number1=chr(rand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.