blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f657cc4b54189daca055c55cf0ab26fa6ab2ba46 | compvision/archive | /18-19/labs/2.1.2-python/Bafna.Mihir/printpyramid.py | 569 | 4.03125 | 4 | def printSpaces(spaces):
for i in range(spaces):
print(' ', end='')
def printPoints(points):
for x in range(points):
print("#", end="")
printSpaces(2)
for x in range(points):
print('#', end='')
def printPyramid(height):
rowcounter = 0
pointnumber = 1
spaces = height... |
56c2acf1db2a93b5cc5a00908638505c8eade41b | compvision/archive | /18-19/labs/2.3.1-class-implementation/Bafna.Mihir/TargetProcessor.py | 578 | 3.640625 | 4 | import math
class TargetProcessor:
degrees = u'\N{DEGREE SIGN}'
centimeters = " cm"
def __init__(self):
pass
def findDistanceAzimuth(self,f,w,iw,x,h):
d = (f*w)/iw
az = math.atan(x/f)*180/math.pi
al = math.atan(h/f)*180/math.pi
return round(d,2),round(az,4),roun... |
5bf2ce2ddd8d5163772ac57369d6bfe2feb4bf05 | alexey-zakharenkov/gb-python-algo | /les_1/les_1_task_1.py | 560 | 4.21875 | 4 | """
Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
https://app.diagrams.net/#G1FHgjTe-_tNOLtWPGYvXT0sW377_hb3tz
"""
num = int(input("Введите целое трёхзначное число:"))
summ = 0
prod = 1
digit = num % 10
summ += digit
prod *= digit
num //= 10
digit = num % 10
summ += digit
prod *=... |
714878802ebc153c601ad72ffd74c0ad7209d956 | alexey-zakharenkov/gb-python-algo | /les_7/les_7_task_2.py | 1,733 | 4.1875 | 4 | """
Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и
отсортированный массивы.
"""
import random
def merge_sort(a):
if len(a) <= 1:
return
middle = len(a) // 2
x = a[:middle]
y = a[middl... |
f3c6635d58bf4f725ea9e0141f870955d91cd991 | alexey-zakharenkov/gb-python-algo | /les_3/les_3_task_9.py | 1,071 | 4.28125 | 4 | """
Найти максимальный элемент среди минимальных элементов столбцов матрицы.
"""
import random
def print_matrix(m):
for r in m:
for el in r:
print(f"{el:5}", ' ', sep='', end='')
print()
LOWER_BOUND = -10
UPPER_BOUND = 10
ROWS = 5
COLS = 5
matrix = [
[
random.randint(LOWE... |
1e7e3483698840af10de31aec0e7054978d7582d | nirajw11/ud120-projects | /outliers/outlier_cleaner.py | 852 | 3.5 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the ... |
4359ceb01516076cca7d66a321d42c0c9ba39443 | ankitanwar/DataStructure | /arrays/threeWayPartion.py | 699 | 3.75 | 4 | """
Given an array we need to partion that such that
all elements smaller than low value comes first
all elements smaller than low value and larger then high value should come in the mid
all elements larger then high value should come in the last
"""
def partionAroundRange(array,a,b):
first=-1
last=len(array)... |
dbb1c457b8ce313cf36a8592f952814d8ce6d983 | sppenna/cs415a1 | /CommonElements.py | 484 | 3.875 | 4 | '''
input: two lists of any size and one empty list
Return: two lists are checked and common elements from the list are appended to output list
'''
def comElems(list1, list2, output, count):
i = 0
j = 0
while (i < len(list1) and j < len(list2)):
count+=1
if (list1[i] > list2[j]):
... |
17ca084b7e51eb07e8f753dd4a573cec5c94b5bc | Alexander-Sidorenko/lesson2.0 | /2-3.py | 378 | 4.375 | 4 | month = int(input("Введите номер месяца "))
if month == 1 or month == 12 or month == 2:
print('Зима')
elif month >= 3 and month <= 5:
print('Весна')
elif month >= 6 and month <= 8:
print('Лето')
elif month >= 9 and month <= 11:
print('Осень')
else:
print('Нет такого месяца! Введите от 1 до 12')
|
ac0c355fe6c0aed87af604ee1801ec7b8ea7029d | loganmurphy/questions | /q1.py | 1,699 | 3.640625 | 4 | dates = [
'Oct 7, 2009', 'Nov 10, 2009', 'Jan 10, 2009',
'Oct 22, 2009', 'Oct 3, 2004', 'Dec 10, 1984',
'May 10, 1984', 'Jun 11, 1989', 'May 10, 2002'
]
months = {
"Jan": "01",
"Feb": "02",
"Mar": "03",
"Apr": "04",
"May": "05",
"Jun": "06",
"Jul": "07",
"Au... |
7a37b27dee191fd186e9bf521eb77501a9b08272 | yoshiyoshiharu/leetcode | /a-106.py | 187 | 3.53125 | 4 | import math
import sys
N = int(input())
for a in range(1 , 100):
for b in range(1 , 100):
if 3**a + 5**b == N :
print(a , b)
sys.exit()
print("-1")
|
b064f3575cea0f2054f07bb819cb57f38437e742 | yoshiyoshiharu/leetcode | /palindrome-number.py | 548 | 3.78125 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 :
return False
else:
x = str(x)
half_len = len(x) // 2
if half_len == 0 :
return True
print(half_len)
left = x[:half_len]
right = x[-ha... |
2a9a792ff6c088f02739e6f5191972d58871d26c | NycoleRibeiro/PPTLS | /animvencedor.py | 2,381 | 3.828125 | 4 | import pygame
SIZE = WIDTH, HEIGHT = 700, 500 # the width and height of our screen
BACKGROUND_COLOR = pygame.Color('white') # The background colod of our window
FPS = 10 # Frames per second
class MySprite(pygame.sprite.Sprite):
def __init__(self):
super(MySprite, self).__init__()
# adding all ... |
2a1ecb02572dc41529457dc3530e70d2e9b03a57 | sima-rai/Python-Excercise-Solution-I | /DataTypes.py | 18,214 | 4.53125 | 5 | #1. Write a Python program to count the number of characters (character frequency) in a string.
# Sample String : google.com'
#Ans:
# def count_string(str):
# dict = {}
# for value in str:
# c=str.count(value)
# dict[value]=c
# print(dict)
#
# count_string('google.com')
#---------------... |
7e42af787175bf5bcad907c0b6ddf65b2cc9445c | xid-er/CS1P | /Books/recommendations.py | 6,377 | 3.640625 | 4 | # Book recommendation program by Kārlis Siders, 2467273S, CS1S, LB01
import random
# Reading books.txt
books = []
try:
with open('books.txt', 'r') as b:
for i in b.readlines():
data = i.strip().split(',')
books.append([data[0],data[1]])
except:
with open('output.txt','w') a... |
4af1e7ea049a6c76fd8bc2e54f091c4f82a583b1 | avanishkd/Python_FLask_MyBooks_Project | /Exceptions/exceptions.py | 4,053 | 3.6875 | 4 | '''
Custom Exceptions
'''
class Aadhar_Invalid(Exception):
'''
Exception occurs when password and confirm password are not matching
'''
def return_message(self):
return "Aadhar number should be of 11 digits"
class Age_Invalid(Exception):
'''
Exception occurs when entered... |
1cd124dbaca28ead86c6a8c66c1bdc55fbd22c63 | feng197907/python100 | /判断语句.py | 245 | 3.53125 | 4 | #!/usr/bin/python3
username = input('请输入用户名: ')
password = input('请输入密码: ')
if username == 'admin' and password == '123456':
print('登录成功')
else:
print('用户名密码输入错误,请重新输入') |
5085f7f5c02a34eb983588784d75f7c4278332af | yugaltale5/IP-LP3-SUBMISSION-PYTHON | /IP_LP3_Python_Yugal_Tale_1348/four.py | 223 | 3.65625 | 4 | def find(x,y):
temp=0
for i in range(1,max(x,y)+1):
if (x % i == y % i == 0):
temp+=1
print(temp)
return None
if __name__=="__main__":
x=int(input())
y=int(input())
find(x,y)
|
e1ada3b63db548bd2ae8afc13cb803fb4fb0ac00 | pihu480/list | /lala2.py | 291 | 3.609375 | 4 |
# a=[2,4,6,8,5]
# pa=[]
# i=0
# n=int(input("enter the number"))
# while i<len(a):
# if i <=n:
# pa.append(a[i])
# print(a[i])
# else:
# print(a[i])
# pa.append[a[-1]]
# i=i+1
# a="priyanka"
# print(a,end=" ")
# a="dangwal"
# print
print(a) |
13f8a80e3213b4d352d708933ce14f335fb9acba | Darfunfun/Revisions | /2.8.1 - Ping v2.py | 6,065 | 3.796875 | 4 |
# Fonction OK
def return_valeur():
n = m = -1
while n < 0 or m < 0:
if n < 0 or m < 0:
print("Les nombres ne sont pas positifs !")
n = int(input("Veuillez entrer le nombre de colonne du plateau : "))
m = int(input("Veuillez entrer le nombre de lignes du plateau : "... |
b42d4e66ed9889cc54072346d6f9fff8230a78e4 | SvetlanaMoldavskaya/python_app_seconds_converter | /Seconds_Converter_2.py | 469 | 4.125 | 4 | # 2. The user inputs time in seconds. Trabnslate the given time into hours, minutes and seconds in the hh:mm:ss format. Use string formating.
def translate():
user_seconds = int(input("Input the seconds: "))
hrs = user_seconds / 3600 #how many times the input can be divided by 1hr
mins = (user_seco... |
3d7fe7017dd492aa8246de3a6dfaa7ce4d8e1c8f | aroseca15/Python_MarketApp | /Tutorial_Notes/arithmeticOperations.py | 535 | 4.71875 | 5 | # ARITHMETIC OPERATIONS:
# print(10 + 3)
# print(10 - 3)
# print(10 / 3)
# Below is a division that will only return the int value, not the float.
# print(10 // 3)
# Below is the operator modulis and it will return the remainder of the division as an int.
# print(10 % 3)
# Below is the operator power or exponent and it... |
1d0608fe277096872b259147861d6833ab26d6a6 | aroseca15/Python_MarketApp | /Tutorial_Notes/2D_lists.py | 1,013 | 4.59375 | 5 | # 2D LISTS: used for data that are and have to be stored in rectangular data table. 2D arrays are known as matrices which we will use.
# [
# 1 2 3
# 4 5 6
# 7 8 9
# ]
# In math this is a 3x3 matrix. This can be modeled using 2D lists. Basically, the computer will understand that each item of the top list w... |
5ca47cc7f49cbdd6f75ef5204c219507b8a3522e | Peiffap/lingi2261-assignments | /assignment1/knight.py | 8,104 | 3.75 | 4 | # -*-coding: utf-8 -*
'''NAMES OF THE AUTHOR(S): Gael Aglin <gael.aglin@uclouvain.be>
Martin Braquet <martin.braquet@student.uclouvain.be>
Gilles Peiffer <gilles.peiffer@student.uclouvain.be>
'''
import time
import sys
from search import *
#################
# P... |
1076f6367e1f60f56286fffe56239de4b7e92776 | matheusgomes28/Pygame-Bouncy-Ball-Python | /main.py | 3,273 | 3.796875 | 4 | import pygame, classes, sys
from pygame.locals import *
from functions import *
pygame.init() #Initialising pygame functions and variables
#Colors R G B
BLACK = ( 0, 0, 0)
WHITE = (255,255,255)
BLUE = ( 0, 0,255)
FPS = 200 #Frames per second / display update time
#########################
### Movement ... |
9b7a61010356c5e646f31fdb29be48d654813f9e | afrazhu/algorithm | /leetcode/array/495.py | 2,209 | 3.703125 | 4 | #!/usr/bin/env python3
# https://leetcode-cn.com/problems/teemo-attacking/
# In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need ... |
f34813dc338805b05b1edf706b792028d551c6d2 | Hessah95/python | /lists_dicts_task.py | 1,547 | 4.03125 | 4 |
skills = [ "Python", "Java", "HTML", "Graphic Design", "Origami", "Crochet", "Tennis", "Bowling"]
cv = {} # an empty dictionary to be filled later
print ("Welcome to the special recruitment program, please answer the following questions:")
cv["name"] = input ("name: ")
cv["age"] = int (input ("age: "))
cv["experien... |
ddfd6cdcb340b17ec5bf851fc6226bbc5ce66763 | rahul-x-verma/Polaris | /polaris/static/algorithm/stop.py | 885 | 3.703125 | 4 | class Stop():
"""
Represents a bus stopping at a certain time and place.
"""
def __init__(self, uid, location, time, line, days):
self.uid = uid
self.location = location
self.neighbors = []
self.time = time
self.line = line
self.days = days
def add_n... |
3a54141f7f79b490a819e8607c8a15eaef19a7cf | rahul-x-verma/Polaris | /polaris/static/algorithm/create_db.py | 20,362 | 3.703125 | 4 | """
SCRIPT TO GENERATE BUS INFORMATION DATABASE
Database Plan: Maintain one table of each stop along with associated
information. Note that the time field represents the number of minutes
after 6 AM the bus stops at a given point, so Night Safety Shuttle stops during
the early hours of the day will be treated as belo... |
1aa2f602d0372187aa0f52803d2608e9c1f93b74 | luiz158/talks_and_articles | /codes/python_moderno/example_annotations.py | 409 | 3.8125 | 4 | #!/usr/bin/python3
from typing import List, IO, Sized
# annotate a variable
spam: str = "eggs spam bacon spam"
def square(list_of_numbers: List[int]) -> List[int]:
return [number ** 2 for number in list_of_numbers]
def printlines(file: IO) -> None:
for line in file:
print(f'{line}\n')
def printsi... |
3c6e8a950f1ce4ea71afa5dfa02eeefca10e4903 | chbuxing1011/pythonstudy | /Python/GUI/GUIInput.py | 620 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
import tkMessageBox
class Application2(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.nameInput = Entry(self)
self.nameInput.pack()
self.alertButton = Bu... |
3125f3bc4ad5f519be309494a8b81d3388dd116b | JasonNyentapCU/SYSC3010_Jason_Nyentap | /Lab-3/lab3-database-JSON.py | 1,291 | 3.78125 | 4 | import urllib
import requests
import datetime
import sqlite3
# The URL that is formatted:
#http://api.openweathermap.org/data/2.5/weather?APPID=a808bbf30202728efca23e099a4eecc7&units=imperial&q=ottawa
# As of October 2015, you need an API key.
# I have registered under my Carleton email.
apiKey = "a808bbf30202728efca... |
90564e9db42f2586a76ef802f46301837daf4916 | ding-co/codeup-python | /basic100/6082.py | 261 | 3.703125 | 4 | # [기초-종합] 3 6 9 게임의 왕이 되자(설명)(py)
# Constraint
# 0. input: 1 <= n <= 29
n = int(input())
for i in range(1, n + 1):
if i % 10 == 3 or i % 10 == 6 or i % 10 == 9:
print("X", end = " ")
else:
print(i, end = " ") |
d6ef6801d24fb6496f0d8f31183c80cef9102104 | brandonfcohen1/garden_app | /program.py | 4,466 | 3.515625 | 4 | import time
import requests
import RPi.GPIO as GPIO
import sensors.barometric_sensor as barometric_sensor
import sensors.cpu_temp as cpu_temp
import sensors.rpio_sensors as rpio_sensors
import sensors.humidity_sensor as humidity_sensor
import sensors.mcp3008 as mcp3008
from signal import pause
# Sensor Configs
HUMIDI... |
54a4125c2811dcacb9a97042e0a2c249af50ed6f | lyubolp/XML-Project-Uni | /src/content/content.py | 1,793 | 3.640625 | 4 | """
:version: 1.0
:author Lyuboslav Karev
Contains two classes - ContentType and Content
Content - The class used to wrap different types of content to be put in the XML
ContentType - The class used to express the type of content inside the main class
"""
from typing import Tuple, List
from enum import En... |
1ba963657dc02871a5dd014c1a3385459a766500 | lindawsol/dailyprogrammer | /wordwar.py | 1,705 | 3.75 | 4 | import re
def word_war (input):
#make everything lowercase.
input = input.lower()
#parse input into 2 words.
wordList = re.sub("[^\w]", " ", input).split()
#check to see if we only have 2 words.
if len(wordList) != 2:
return 'Only 2 word are allowed in this battle!'
left = wordLi... |
141e310e7a7dcabce1c1951e058a7fadea34dec0 | lancerdancer/leetcode_practice | /templates/dfs_backtracking.py | 794 | 3.515625 | 4 | class Solution(object):
def permute(self,nums):
rtlist = []
templist = []
self.backtrack(rtlist,templist,nums)
return rtlist
#rtlist用来存储所有的返回所有排列,templist用来生成每个排列
def backtrack(self,rtlist,templist,nums):
if(len(templist) == len(nums)):
rtlist.append(te... |
81fc280daaf7f4765a882d4e9965857e88404011 | lancerdancer/leetcode_practice | /code/stack/895_maximum_frequency_stack.py | 2,014 | 3.921875 | 4 | """
https://leetcode.com/problems/maximum-frequency-stack/
Implement FreqStack, a class which simulates the operation of a stack-like data structure.
FreqStack has two functions:
push(int x), which pushes an integer x onto the stack.
pop(), which removes and returns the most frequent element in the stack.
If there i... |
a5989430bd5c7a252a49d131562e14da4113f9ee | lancerdancer/leetcode_practice | /code/combination_based_dfs/140_word_break_ii.py | 1,580 | 4 | 4 | """
https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multi... |
21f3c0fd9232ee8aef48709cd64d318e18d8a431 | lancerdancer/leetcode_practice | /code/binary_tree_and_tree-based_dfs/270_closest_binary_search_tree_value.py | 1,004 | 4.0625 | 4 | """
https://leetcode.com/problems/closest-binary-search-tree-value/
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the targe... |
357bdcb45a45e00a432b265dd71015e234ee50df | lancerdancer/leetcode_practice | /code/bit_manipulation/190_reverse_bits.py | 946 | 3.921875 | 4 | """
https://leetcode.com/problems/reverse-bits/
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so
return 964... |
66eb7fcb075b37dfb147fb9eeaba9049cccd40b9 | lancerdancer/leetcode_practice | /code/list/616_add_bold_tag_in_string.py | 1,339 | 4.03125 | 4 | """
https://leetcode.com/problems/add-bold-tag-in-string/
Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two ... |
f0c90874402a36e9c59527fd756244d0a4b90924 | daamparan/Past-Current-Labs | /CS 2302 - Data Structures/Lab4-1.py | 9,169 | 3.90625 | 4 | """
Author: David Amparan
Last Modified: 3/17/2019
TA: Anindita Nath, Malileh Zaragan
Professor: Fuentes, Olac
Functionality: Implement the functionalities of a B-Tree as well
as learn the implementation and different modes of traversal
"""
class BTree(object):
# Constructor
def __init__(self,ite... |
276479e7bc9891424bdf9fb9c61634e8d07cd016 | priscillatiemi/jogos | /jogo_adivinhacao_for.py | 1,077 | 4.0625 | 4 | print("**********************************")
print("Bem vindo ao jogo de adivinhação!")
print("**********************************")
numero_secreto = 42
total_de_tentativas = 3
for rodada in range(1, total_de_tentativas + 1):
print("*********************************")
print("Tentativa {} de {}".format(rodada,t... |
7919c28c44a720d18f400a8a65ef59602dc08088 | Thireb/LearningGit | /Python in VS code/Pymanger/passwordManger.py | 9,315 | 4.15625 | 4 | # python
'''
Documentation of password manager
Check if there's a master password
if not then create a new user and master password
if exists then show all of the passwords
Ask to save a new password
Ask to generate a random password
'''
import csv
import os
import random
import string
import sys
def startup():
#... |
9eb1e73b242e8869914045f50c899208abbca484 | Jarantym/portfolio | /magicSquare.py | 923 | 3.71875 | 4 | ## magic square
# headers and inputs
print()
print('MAGIC SQUARE')
print()
print('enter an odd number:')
n=int(input(''))
print()
# creating matrix
square=[]
for i in range(n):
datas=[0]*n
square.append(datas)
# first position
row=n-1
col=int(n/2)
#first cycle
for k in range(1,int((n-n//2)*n)+1):
square[row][... |
dae5af192755899c5263e761915960339a9eb63e | PhilippvH1/udemy_automate_boring_stuff_python | /04_error_handling/try_except.py | 263 | 3.84375 | 4 | print('How many bikes do you have?')
numBikes = input()
try:
if int(numBikes) >= 4:
print('That is a lot of bikes...')
elif int(numBikes) < 0:
print('That seems unlikely.')
else:
print('That seems ok.')
except:
print('That was not a number!')
|
7e3edf79ff6c8956bc0ad785a0ad0e86ac54d1b4 | PavithSudhirAP/SQLite | /query_by_actor_names.py | 466 | 3.96875 | 4 | import sqlite3
#connecting database
mov = sqlite3.connect('favmovies.db')
#creating cursor
c = mov.cursor()
#query the database by lead actor name
c.execute("SELECT * FROM movies WHERE lead_actor = 'TOM CRUISE' ")
# # prints all TOM CRUISE's movies
# print(c.fetchall())
#prints all TOM CRUISE's movie... |
c3ab3c11d4a93dd3797d8e33e35758ce9609f6c3 | jose145/t08.Carrasco.Castillo | /CARRASCO/longitud.py | 1,478 | 3.734375 | 4 | #ejercicio 01
cad="ELLA NO TE AMA"
print("la longitud de la cadena es:",len(cad))
#ejercicio 02
cad="UNIVERSIDAD NACIONAL PEDRO RUIZ GALLO"
print("la longitud de la cadena es:",len(cad))
#ejercicio 03
cad="FACULTAD DE CIENCIAS FISICAS Y MATEMATICAS"
print("la longitud de la cadena es:",len(cad))
#ejercicio 04
cad="L... |
c5dadd00794c760db747a18dad6ad17aa01b1971 | marianac99/Mision-04 | /triangulos.py | 1,101 | 4.09375 | 4 | #Mariana Caballero Cabrera A01376544
# Recibe los lados de un triángulo y calcula que tipo de triángulo es
# Determina el tipo de triángulo según sus lados
def determinarTriangulo (lado1,lado2,lado3):
if lado1 == lado2 and lado2 == lado3:
triangulo = "isosceles"
elif lado1 == lado2 != lad... |
362ee3a5c552b84eef3fe14c5bd33ccf1d4deeba | samyak360/python | /tkinter_and_threading.py | 1,355 | 3.703125 | 4 | # This is the implementation of the tkinter and the threading
from tkinter import *
import time
import tkinter.messagebox
root=Tk()
import threading
def f():
i=70
for i in range(550):
l.place(x=i ,y=70)
time.sleep(0.04)
def counter_label():
l2.config(text=time.ctime())... |
c7d9e8a7b71c853ed178b004e4795f7c5fb06adb | MooseyAnon/linear-algebra-and-algos | /src/algorithms/python/quicksort.py | 2,572 | 4.375 | 4 | """Various implementations of the quicksort algorithm."""
def quicksort(array):
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksor... |
dd13d496691eb974b3892aba29bd45ce7c36429b | Wekesa-Wafula/python_exercises | /task5.py | 197 | 3.59375 | 4 | a = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )
string1 = ''
for values in a[0:5]:
string1 += str(values)
print(string1)
string2 = ''
for values in a[5:10]:
string2 += str(values)
print(string2)
|
fa3a6dee46551c50b8b418f519f81f58b06cdf42 | jorgesmunoz/CESE | /DASO/Clase_3/Ejemplos/ejMutex.py | 908 | 4.0625 | 4 | #!/usr/bin/python3
import threading
import time
class MyThread (threading.Thread):
varCompartida=0
threadLock = threading.Lock()
def __init__(self, name, counter):
threading.Thread.__init__(self)
self.name = name
self.counter = counter
def run(self):
print ("Comienza... |
fa5eb956595433440fef62bc554bc64303db77a0 | akshatmittal1/python | /basic python/akshat.py | 153 | 3.625 | 4 | l=list()
i=0
while(i<5):
n=int(input("enter a no"))
if(n in l ):
print("duplicate")
else:
l.insert(i,n)
i=i+1 |
d31ee161f01593e825db864af72ed406e1e08414 | akshatmittal1/python | /basic python/17.py | 47 | 3.578125 | 4 | s="abc"
a=20
print("name",s,"age",a)
print() |
01e8be39cfb1879e7fb589b29d25ba5217ff17c8 | akshatmittal1/python | /basic python/2.py | 241 | 3.78125 | 4 | l=list()
i=0
while(i<5):
n=int(input("enter a no"))
if(i%2==0):
l.insert(i,n)
i=i+1
elif(n%2==0):
print("even no on odd place not allowed")
else:
l.insert(i,n)
i=i+1
print(l) |
c3749452f058f8591fe2a391dda3b17792a8c34b | makzylinski/SI | /animation.py | 13,595 | 3.703125 | 4 | from __future__ import print_function
import decission_tree as dt
import time
from tkinter import *
import os
import tkinter as tk
import rozpoznawanie as rp
try:
import matplotlib.pyplot as plt
except:
raise
class AStarGraph(object):
# Define a class board like grid with two barriers
def __init__(s... |
d401edc19de276a8952db91d9e9a9cf43c324857 | lalimite123/Groupe4L2IN2019-2020- | /systeme_banque.py | 10,064 | 3.59375 | 4 | #coding:utf-8
from time import sleep
class Client():
def __init__(self, nom, prenom, numero_id, mdp):
self.nom = nom
self.prenom = prenom
self.numero_id = numero_id
self.mdp = mdp
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### +++++++++++++... |
42213dcdc9c90c2806804cfd61515c3ee95b5196 | noel-maldonado/Data-Programming | /HW Assignments/Chapter_8/Exercise_1.py | 471 | 4.46875 | 4 | # (Check SSN) Write a program that prompts the user to enter a Social Security
# number in the format ddd-dd-dddd, where d is a digit. The program displays
# Valid SSN for a correct Social Security number or Invalid SSN otherwise.
ssn = input("Enter a valid social security number (ddd-dd-dddd): ")
if len(ssn) == 11 a... |
457f55c6a383fb19d6f9098be242b13e62af4613 | noel-maldonado/Data-Programming | /HW Assignments/Chapter_11/Exercise_2.py | 788 | 4.46875 | 4 | # (Sum the major diagonal in a matrix) Write a function that sums all the numbers
# of the major diagonal in an matrix of integers using the following header:
# def sumMajorDiagonal(m):
# The major diagonal is the diagonal that runs from the top left corner to the bottom
# right corner in the square matrix. Write a tes... |
6a9c54e372fb912e536b58dffa6ab6ee9fe36e8c | noel-maldonado/Data-Programming | /HW Assignments/Chapter_6/Exercise_18.py | 524 | 4.46875 | 4 | # (Display matrix of 0s and 1s) Write a function that displays an n-by-n matrix using
# the following header:
# def printMatrix(n):
# Each element is 0 or 1, which is generated randomly. Write a test program that
# prompts the user to enter n and displays an n-by-n matrix. Here is a sample run:
import random
def prin... |
3272a194e104dddea57db038e713cc99b3fb5db4 | noel-maldonado/Data-Programming | /HW Assignments/Chapter_10/Exercise_4.py | 655 | 4.25 | 4 | # (Analyze scores) Write a program that reads an unspecified number of scores and
# determines how many scores are above or equal to the average and how many
# scores are below the average. Assume the input numbers are separated by one
# space in one line.
scores = input("Enter scores: ")
scores_list = [int(x) for x i... |
8a00042bb4830c5e4fd8fbdf1ea4bf26eb2b24e1 | alishalopes87/hb-coding-challenges | /whiteboard.py | 155 | 3.8125 | 4 | def is_unique(str):
for i, char in enumerate(str):
if char in str[i+1:]:
return False
return True
print(is_unique("abc!"))
print(is_unique("abca")) |
861762394525058fe7367281a94e195932d07c17 | alishalopes87/hb-coding-challenges | /longest_substring.py | 1,634 | 4.3125 | 4 | a# Given a string, find the length of the longest substring without repeating characters.
# Example 1:
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example 3:
# Input: "... |
de899e5c9cf3095dcfc03e6e9cdb288dadb14ab4 | alishalopes87/hb-coding-challenges | /current.py | 2,321 | 3.671875 | 4 | #create variable current first item in list
#create variable max start at first item
#create variable count
#create empty list
#iterate over list starting at index 1
#compare current to list[i] if same increment count
#else current = list[i]
#result.append(current)
#result.append(count)
#current = lst[i]
#count = 1
# ... |
905e83feea864fc343b5e8fba84af87f8afc2052 | alishalopes87/hb-coding-challenges | /long_prefix.py | 672 | 3.90625 | 4 | #subtring =""
#if i = j subtring += i
def common_prefix(word1,word2):
subtring = ""
i = 0
j = 0
while i < len(word1) and j < len(word2):
if word1[i] == word2[j]:
subtring += word1[i]
i += 1
j += 1
else:
break
return subtring
def longest_prefix(array):
subtring = ""
if not array:
return s... |
a5551d00cce939385d40556e2c729d45e7528e98 | alishalopes87/hb-coding-challenges | /is_anagram_of_palindrome.py | 882 | 4.21875 | 4 | #Is the word an anagram of a palindrome?
# A palindrome is a word that reads the same forward and backwards (eg, “racecar”, “tacocat”). An anagram is a rescrambling of a word (eg for “racecar”, you could rescramble this as “arceace”).
# Determine if the given word is a re-scrambling of a palindrome.
# The word will ... |
c2cc671684ae0a09c57b38c2bce486673c67f026 | sweet23/oreillyPython1 | /Chap13-MoreFunctions/13Quiz1.py | 1,065 | 4.65625 | 5 | '''
Question 1:
What is the dict-parameter?
What type of object is provided by the dict-parameter?
'''
question1 = 'What is the dict-parameter? What type of object is provided by the dict-parameter?'
answer1 = 'We know that when an unknown number of positional arguments will be provided, \
we can capture the extra ... |
154976921e054ff2ad25a8d8b7a4ed4fd26c7ebd | sweet23/oreillyPython1 | /Chap11-DefineFunctions/11Quiz2.py | 736 | 3.875 | 4 |
question1 = 'What is the prefix used for a sequence-parameter?'
question2 = 'What type of object does the sequence-parameter provide to the function body?'
answer1 = 'The prefix used is the "*" character. For example:\
def multiplier(*args):'
answer2 = 'A tuple. The interpreter collects any unmatched positional argum... |
a1cab4def8b67e98762ce31d3f27dd3fd874bffb | sweet23/oreillyPython1 | /16/16Quiz1.py | 2,187 | 3.5 | 4 | __author__ = 'outofboundscommunications'
#To change this template use Tools | Templates.
#
'''
Question 1:
What is "agile" programming?
Question 2:
Why is testing so important?
Question 3:
How can Python help you test your code?
'''
print('Question #1: What is "agile" programming?')
print('"Agile Programming" is ba... |
cce0fbc6f1a5ebe76bddd6360bd69b8885b4d6a3 | sweet23/oreillyPython1 | /Chap11-DefineFunctions/test.py | 264 | 3.609375 | 4 | __author__ = 'outofboundscommunications'
#To change this template use Tools | Templates.
#
def returnAnswer(myString):
text = "This is now lowercase:"
LString = myString.lower()
text+=LString
return text
v = returnAnswer('hello There How Are You Today?')
print(v) |
19c5bc514e7e5ffe3b14d370599e2fab0c4f4ca9 | sweet23/oreillyPython1 | /Chap12-StdLibrary/12Quiz1.py | 1,071 | 3.671875 | 4 | '''
Question 1:
Write code that:
imports the time module from the Python standard library.
imports the sys library, giving it the name "system."
imports your own module called actions.py.
'''
'''
Question 2:
If actions.py contains a function named "jump," how would you import just that function?
How would you import... |
9e3a85ffd16b8d7d78d5c0cfcad70254d9ccbb9c | camelCasedAdi/Python-Programming-Tutorials | /tutorial5.py | 257 | 4.21875 | 4 | num1 = int(input("First Number: "))
num2 = int(input("Second Number: "))
op = input("Operater: ")
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2) |
91fac84c73464c1f34e6746f7d4fc3a471d5a370 | camelCasedAdi/Python-Programming-Tutorials | /tutorial13.py | 107 | 3.84375 | 4 | # .strip(), len(), .lower(), .upper(), .split()
text = input("Input: ")
print(text)
print(text.split(' ')) |
a2fb8877bad4e0347bfc8348e79f1b6389273e4f | shanjianqing0207/learn_python | /map+reduce.py | 440 | 3.578125 | 4 | from functools import reduce
def str2float(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
lis=map(lambda x:DIGITS[x] ,[i for i in s if i!='.'])
return reduce(lambda x,y:x*10+y,lis)/10**(len(s)-s.find(".")-1)
print('str2float(\'123.456\') =', str2float('1... |
9306b234d9f4e6f4950d59c414b5cdf9ee1e329d | shanjianqing0207/learn_python | /余数除法.py | 127 | 4.1875 | 4 | num1 = int(input('plz enter num1 '))
num2 = int(input('plz enter num2 '))
print(str(num1//num2) + '......' + str(num1%num2)) |
a5405f37c0a8c43edc66bd0041f878d4d378b79f | mcxu/code-sandbox | /PythonSandbox/src/misc/diamond_pattern.py | 788 | 3.9375 | 4 | '''
Given number of rows, print a diamond pattern.
n = 3
*
* * *
*
n = 4
*
* * *
* * *
*
'''
class Prob:
@staticmethod
def printDiamond(n):
aux = [" "] * (n+1)
medInd = int(n/2) # median index
aux[medInd] = "*"
lim = int(n/2)
if n % 2 != 0:
... |
8324d6963cdf77f5e878b6b0bebf5012bd925883 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc1451_rearrange_words_in_sentence.py | 1,161 | 4.03125 | 4 | '''
https://leetcode.com/problems/rearrange-words-in-a-sentence/
Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case. Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearran... |
058251cfccccdc17d613a09d02d7e959aced4472 | mcxu/code-sandbox | /PythonSandbox/src/misc/three_largest_nums.py | 2,264 | 4.15625 | 4 | """
Write a function that takes in an array of integers and returns a sorted array
of the three largest integers in the input array. Note that the function should return duplicate integers
if necessary; for example, it should return [10, 10, 12] for an input array of [10, 5, 9, 10, 12].
"""
class ThreeLargestNums:
... |
868760343e5aa09fcbbe6ceef75de6840f210e95 | mcxu/code-sandbox | /PythonSandbox/src/misc/kth_largest_element.py | 5,378 | 4.125 | 4 | '''
Find kth smallest/largest element in unsorted array
Sample input: [7, 10, 4, 3, 20, 15], k=3, find kth smallest
Sample output: 7
Sample input: [7, 10, 4, 3, 20, 15], k=4, find kth smallest
Sample output: 10
https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/
'''
class Prob:
'''
sma... |
9aafae9b6c6d09dcf9296a59c27f88aa0d178c6f | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc383_ransom_note.py | 1,211 | 3.890625 | 4 | '''
383. Ransom Note (https://leetcode.com/problems/ransom-note/)
Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed from the magazines ;
otherwise, it will return false. Each letter in the m... |
3a24aff22f722bd90b7db5ea70a7cacbf27b94ed | mcxu/code-sandbox | /PythonSandbox/src/misc/string_sum.py | 2,234 | 3.5 | 4 | """
ab9q???qY1ery???y9ay?t?y?udf1
Match format <num><could be alpha chars>???<could be alpha chars><num>
Rules:
numbers on each side of ??? (3 question marks) should add up to 10
return True if so, False otherwise.
"""
# using a stack
def isValid_v2(s):
queue = []
qMarkCount = 0
i = 0
while i < len(s)... |
af82e6f369283ab7c16438f59d1be42ccef0c69b | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc23_merge_k_sorted_lists.py | 6,358 | 4.03125 | 4 | '''
https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
import heapq
class ListNode:
def __init__(self, val, next=None):
se... |
c762d2234ba19e5a972d5f6f6df8005896f34f47 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc92_reverse_linked_list_mn.py | 3,395 | 4 | 4 | '''
92. Reverse Linked List II
https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add(self, x):
self.next... |
dbd4feb8fd9d293a933a1d7c9905f2432226c45f | mcxu/code-sandbox | /PythonSandbox/src/misc/balanced_brackets.py | 2,681 | 4.1875 | 4 | '''
Balanced brackets
Function that returns True with brackets are balanced, return False otherwise.
Sample input: "([])(){}(())()()"
Sample output: True
'''
class Prob:
"""
Time complexity: O(n), n=len(string). Since for loop iterates through all chars.
Space complexity: O(n), since at the worst cas... |
ea51ce257b94eed5a12501f910a668b8115355df | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc227_basic_calculator_ii.py | 1,732 | 3.5 | 4 | # https://leetcode.com/problems/basic-calculator-ii/
class Solution:
def calculate(self, s: str) -> int:
slist = list(s.strip())
#remove empty str
i = 0
while i < len(slist):
if slist[i]=='' or slist[i]==' ':
slist.pop(i)
i -= 1
... |
07a1514fb36cbb87732682f92cda3e10ae1a2b76 | mcxu/code-sandbox | /PythonSandbox/src/misc/invert_binary_tree.py | 1,533 | 4.21875 | 4 | """
Invert binary tree: for each node, swap left and right child nodes
"""
from utils.binary_tree_utils import BinaryTreeUtils as Utils
class BTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Prob:
""" Complexity
Time: O(n): n=num nodes,... |
838f0a16418c7e59bbcbf29ecbd028ccf4b45c12 | mcxu/code-sandbox | /PythonSandbox/src/daily_coding_problem/dcp1276_same_sum_subset_partition.py | 2,180 | 4.03125 | 4 | """
This problem was asked by Facebook.
Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same.
For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true,
since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 5... |
59d0ebc7cfe1875e0ff44ba0bf45fea3f9a02e02 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc1457_pseudopal_paths_in_bt.py | 4,548 | 4 | 4 | '''
https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic
if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths... |
6504777c3c60cebb48a38bcf06ca9f2e7c1c4e9e | mcxu/code-sandbox | /PythonSandbox/src/misc/subarray_sort_indices.py | 1,425 | 3.96875 | 4 | '''
Subarray Sort Indices
Given array of integers, return [start,end] indices of
the smallest subarray that must be sorted in order for the
entire array to be sorted. Input array length >= 2. If array
is already sorted return [-1,-1].
Sample input: [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]
Sample output: [3, 9]... |
8f2c433619b219811ccb89951cd520fb837212ea | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc1215_stepping_numbers.py | 2,447 | 3.609375 | 4 | class P1215_SteppingNumbers:
"""
5081. Stepping Numbers
"""
def countSteppingNumbersBruteForce(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
sns = []
for i in range(low, high+1):
intstr = str(i)
... |
cb4037d5fe5088d24d41d54689345640cfc32e0c | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc775_global_and_local_inversions.py | 1,797 | 3.5 | 4 | """
https://leetcode.com/problems/global-and-local-inversions/description/
"""
from typing import List
class Solution:
""" Notes: This solution results in TLE
Time complexity: O(n*logn) from the merge sort
Space complexity: O(1), no auxiliary data structures other than nums which doesn't count
"""
... |
f20fe0bb32bdb171b610c350e5bbd5c6abb6439a | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc101_symmetric_tree.py | 1,014 | 3.828125 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root.left and root.right and (root.left.val != root.right.val):
return False
return self.dfs... |
aad567da44c96188654a33756c12400bf9e00e88 | mcxu/code-sandbox | /PythonSandbox/src/misc/water_area.py | 4,671 | 3.96875 | 4 | '''
Water Area
Given array ints, each non-zero int represents the height of a pillar of width 1.
What is the total surface area (viewed from from) of the water that the space
between the pillars can hold?
Sample input: [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3]
Sample output: 48
'''
class Prob:
'''
Recursiv... |
d2fa0c94a09e16530342d00711d63c665d33da8f | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc2696_min_str_len_after_rem_substrings.py | 648 | 3.6875 | 4 | """
https://leetcode.com/problems/minimum-string-length-after-removing-substrings/
"""
class Solution:
def minLength(self, s: str) -> int:
while "AB" in s or "CD" in s:
# print("s: ", s)
sList = list(s)
if "AB" in s:
idx = s.index("AB")
... |
edc8d6cef53a17c32727664b5f4522eb73043077 | mcxu/code-sandbox | /PythonSandbox/src/misc/array_contains_close_nums.py | 1,537 | 3.765625 | 4 | '''
Given an array of integers nums and an integer k,
determine whether there are 2 distinct indices i and j
in the array where nums[i]=nums[j] and the absolute difference
between i and j is less than or equal to k.
Example 1:
nums = [0,1,2,3,5,2] and k = 3
output should be: true
Example 2:
nums = [0,1,2,3,5,2] and k... |
8b5e0c5209cae97a4219be75d2f5da0b5cabfbbb | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc79_word_search_v2.py | 2,120 | 3.59375 | 4 | '''
https://leetcode.com/problems/word-search/description/
'''
class Solution:
def exist(self, board: [[str]], word: str) -> bool:
wordExists = False
for row in range(len(board)):
for col in range(len(board[0])):
# do dfs
wordExists = self.dfs(board, row,... |
e6f5ccae7fbab19aada79baf343f0294c5a5bf8e | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc243_shortest_word_distance.py | 1,496 | 4.125 | 4 | '''
https://www.programcreek.com/2014/08/leetcode-shortest-word-distance-java/
Given a list of words and two words word1 and word2,
return the shortest distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "p... |
0178fc8e9577a4adfa7b655270c7cc4f48a7b070 | mcxu/code-sandbox | /PythonSandbox/src/misc/median_of_2_sorted_lists.py | 821 | 3.90625 | 4 | def med_2_sorted_lists(l1, l2):
i,j = 0,0
mergedList = []
while i < len(l1) and j < len(l2):
v1, v2 = l1[i], l2[j]
if v1 <= v2:
mergedList.append(v1)
i += 1
elif v1 >= v2:
mergedList.append(v2)
j += 1
if i == len(l1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.