blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bb2f29c69461f0a17af6c623f0203381cb7886dd | tianluyuan/project_euler | /euler_043.py | 960 | 3.515625 | 4 | """
The number, 1406357289, is a 0 to 9 pandigital number because it is
made up of each of the digits 0 to 9 in some order, but it also has a
rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way,
we note the following:
d2d3d4=406 is divisible by 2 d... |
d25eb8f84d9ba094a41d1ed219d28e7510f73bf8 | priscilamarques/pythonmundo1 | /primeiro_comando.py | 900 | 4.125 | 4 | nome = input('Qual seu nome? ')
idade = input('Qual sua idade? ')
peso = input('Qual seu peso? ')
print(nome, idade, peso)
##Desafio 1
#Crie um script Python que leia o nome da pessoa e mostre uma mensagem de boas-vindas de acordo com o valor digitado.
nome = input('Qual o seu nome? ')
print(f'Olá, {nome}! Prazer em... |
1a80f166a6e3d21ee04986431bbb82e8cbb9130c | LizaPersonal/personal_exercises | /Programiz/convertDecimal.py | 274 | 4.34375 | 4 | # Python program to convert decimal number into binary, octal and hexadecimal number system
dec = int(input("Enter a decimal number: "))
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.") |
65bc40493cf99e44605bed86e83435557717322a | calfzhou/lazy-lab | /TestLca/FindLCA.py | 4,530 | 3.796875 | 4 | '''Find the least common ancestor (LCA) of two nodes in the bin-tree.
'''
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
self.parent = None
if self.left: self.left.parent = self
if self.right: self.right.parent = self
from ... |
23dabe592b858fbb15e2f56fcf792234f753a561 | burdenp/Spruly-AI | /Count.py | 603 | 3.765625 | 4 | import sys
import os
import string
import Stock
import collections
#purpose is to count the given stocks and figure out how many
#there are of each stock and then pass that onto format/weight
#takes in a list of stocks, returns a dictionary
#takes in the list of stocks and then finds the names
#then compares names to ... |
10b19e94dc03410ecc9658ab560a8bfd8cd21aed | Achal08/LeetCode | /Leetcode August Challenge 2020/Leetcode Python/Vector clock.py | 1,547 | 3.921875 | 4 | #This function returns maximum of two vectors
def vector_compare(vector1,vector2):
vector = [max(value) for value in zip(vector1,vector2)]
return vector
P = {1:{}, 2:{}, 3:{}} # Inititalized an empty dictionary having 3 process
inc = 0
e1 = int(input("Enter the no. of events in Process 1:"))
e1 = [i ... |
d669cc9090752387ce27f6f05ca08fb846ad9d6f | theonaunheim/tutorials | /python_sessions/202_intro_for_devs_part_2/static/sample_program/program.py | 514 | 4.1875 | 4 | import sys
def main(args):
'''This program takes arguments, capitalizes them, and writes to stdout.
Alternatively:
import sys
for arg in sys.argv[1:]:
sys.stdout.write(arg.upper() + '\n')
'''
try:
for arg in args:
upper_arg = arg.upper()
... |
4ec0fcd004621bc498e9ab60e8ef33d000d2e45c | wisebaldone/uq-secat | /scraper/course_description.py | 3,860 | 3.640625 | 4 | class CourseDescription(object):
def __init__(self, raw, description, enrolled, responses, rate):
self.course = raw[0]['COURSE_CD']
self.description = description.split(":")[0]
self.year = raw[0]['SEMESTER_DESCR'].split(",")[1].strip()
self.enrolled = int(enrolled)
self.resp... |
0b478ec04d673548e10182876df527015a83ad6e | yuehhan/Interviewprep_and_projects | /singlenumber.py | 1,053 | 3.796875 | 4 | <<<<<<< HEAD
# Given an array of numbers nums, in which exactly two elements
# appear only once and all the other elements appear exactly twice.
# Find the two elements that appear only once.
def singleNumber(nums):
nums.sort()
count = 0
while len(nums) > 2:
if nums[count] == nums[count+1]:
... |
fb50c0a88132b8fa5428119474662e43d0984a10 | adambatchelor2/python | /codewars_spinWords.py | 259 | 3.625 | 4 |
strTest = 'i love horses'
def loop_through(inStr):
word_list = inStr.split()
for x,word in enumerate(word_list):
if len(word) >= 5:
word_list[x] = word[::-1]
return ' '.join(map(str, word_list))
print(loop_through(strTest)) |
1f368f5080bf05577a451fe4491e21740000c535 | Phantom586/My_Codes | /Coding/Python_Prgs/Lists.py | 1,326 | 4.25 | 4 | if __name__ == '__main__':
# Inputting The no. of operations user wants to perform.
N = int(input())
# list to store the Elements after performing operations on it.
mine = []
# for loop for N operations.
for i in range(N):
# List to Store the operation and their required values.
... |
81b9142c87bc6080803d55b7953ee4859c4896e5 | marcelogabrielcn/ExerciciosPython | /exe025.py | 149 | 3.96875 | 4 | nome = input('Digite o nome de uma pessoa: ')
if 'Silva' in nome:
print('Tem Silva nesse nome!')
else:
print('Não tem Silva nesse nome!!!')
|
88058341aff15fa2b61f4d6ef9096d150a2dd25b | shubham-dixit-au7/test | /coding-challenges/Week02/Day 4_30-01-2020/calc_upper_lower.py | 601 | 4.1875 | 4 | #Question- Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.
#Answer-
def countUpperCase(string):
upper= 0
for i in string:
if(i.isupper()):
upper=upper+1
return upper
def countLowerCase(string):
lower= 0
for i in string:
if(i.islower())... |
e87884a14ef14bd227b5750faeba244d110a87e6 | fernandorssa/CeV_Python_Exercises | /m_115.py | 1,298 | 3.8125 | 4 | def menu():
print('-' * 30)
print(f'{"Menu principal":^30}')
print('-' * 30)
print('1 - Ver pessoas cadastradas')
print('2 - Cadastrar nova pessoa')
print('3 - Sair do sistema')
print('4 - Ver o menu principal')
print('5 - Limpar cadastro')
print('-' * 30)
def cadastro():
dici... |
4eb33738e2e5ffecfe818f8d9700d91141232332 | ndonyemark/passlock | /program.py | 5,396 | 4.0625 | 4 | from credentials import Credentials
from users import Users
import time
import secrets
import string
def create_user(username, password):
new_user = Users(username, password)
return new_user
def save_users(user):
user.save_user()
def del_user(user):
user.delete_user()
def find_user(username):
re... |
a0c560608e73da59d2c92846325f64590942d466 | Erick-Paguay/perick885 | /funlist2.py | 228 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 12:14:13 2020
@author: SEDMQ
"""
def listacreada(n):
lista1=[]
for i in range (n):
lista1.append(i)
return lista1
print(listacreada(11)) |
1f21520bd6d2f88a21521c94ac26f4944c51340a | stnorbi/AlienInvasion | /characters/ammo.py | 785 | 3.625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self,ai_settings,screen,ship):
super(Bullet,self).__init__()
self.screen=screen
#set the place of the bullet
self.rect=pygame.Rect(0,0,ai_settings.bullet_w, ai_settings.bullet_h)
self.rect.cen... |
5cf266d879dd16bff182a2575d2c1177236b0599 | Rivarrl/leetcode_python | /leetcode/601-900/884.py | 757 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 884.py
# @Time : 2019/12/30 23:54
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[884. 两句话中的不常见单词](https://leetcode-cn.com/problems/uncommon-words-from-two-sentences... |
8d094ed01c4a79f54671b9eac78eb6be516a26f8 | Maryam-Rafindadi/Python-Basics | /Python _Basics_Exercise1.py | 1,082 | 4.09375 | 4 | #format method
name = 'Maryam Rafindadi'
print('Hello, {0}'.format(name))
#grade of student
print("student scores")
mark = int(input())
score = mark
if score >= 70 and score <=100:
print ("Your Grade is A")
elif score >= 60 and score <= 69:
print("Your Grade is B")
elif score >= 50 and score <= ... |
123686a86e70efcc576cc7092ca24f2d5cfb4bf0 | nickpostma/monopoly2 | /player.py | 776 | 3.734375 | 4 | import unittest
class test(unittest.TestCase):
def test_player_class_callable(self):
self.assertIsNotNone(Player(id = 0))
def test_player_should_have_id(self):
self.assertIsNotNone(Player(id = 0).id)
def test_player_should_have_money(self):
self.assertIsNotNone(Player(id = 0).Mo... |
44b83244efb11dd25665199a5a173ce0d28a1dcb | dan2014/Data-Structures | /linked_lists_practice/stack_list.py | 949 | 4.125 | 4 | class Stack:
def __init__(self):
self.list = []
def __repr__(self):
if(self.len() == 0):
return "The stack is empty"
else:
for i in reversed(self.list):
print(f"{i}")
return ""
def push(self, item):
self.list.append(item... |
de83031c9023cb89bed3112eb4ae4e5f0f44d9c1 | marpe163/Myne-Sweeper | /TileBoard.py | 2,515 | 3.75 | 4 | import sys
from Tile import Tile
from random import randint
class TileBoard:
def __init__(self, width, height):
self.board = [[Tile() for j in range(height)] for i in range(width)]
self.width = width
self.height = height
self.isInitialized = False
def getTile(self, xIdx, yIdx):... |
e5279fa30cd5f4dfc4a5a196f34d48d2e44d85b7 | kolligj70/Agnesi-Fractals | /SupportFiles/genSpiral.py | 1,739 | 3.53125 | 4 | #! /usr/bin/python3
"""
Generate/plot a spiral.
If output of image is desired, include any string as a
command line argument.
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
#### Spiral Parameters ####
xCenter = 2.0
yCenter = 4.0
nPts = 300
# Reverse values for inward spiral
ra... |
3b1e9c51752c5d9a33751a0ca3185b39195f7ba4 | l3r4nd/Machine-Learning-Notes | /Computer-Vision-Tasks/Paint_Brush.py | 1,074 | 3.734375 | 4 | image = np.zeros((512, 512, 3), np.uint8)
drawing = False
ix, iy = -1, -1
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing
#Check to see if the Left mouse button is pressed.
if event == cv2.EVENT_LBUTTONDOWN:
#enable drawing
drawing = True
ix, iy = x, y
... |
86158d0a53373234e8579e78da89c10761ef8136 | vicentegarridoj/Python-Scripts | /FindIPs.py | 322 | 3.515625 | 4 | import re #import Regular Expression Python module
ipAddRegex = re.compile(r'\d+\S\d+\S\d+\S\d+') #This is the pattern that I want to match
ipList = ''' paste your text which contains IP addresses ''' #Paste the values inside triple-quote syntax
ipAddRegex.findall(ipList) #Run this function passing the ipList argumen... |
fbf072dec6015be81d70c32118682e4a1351a8d0 | FisicaComputacionalOtono2018/20180829-tareapythoniintial-jordetm5 | /productovectorial.py | 404 | 3.96875 | 4 | #Jorge Dettle Meza Dominguez
#29/08/2018
#producto cruz
c1=0
c2=0
c3=0
a= []
for i in range (0,3):
a.append(int(input("dame el valor de la componente de A: ")))
b = []
for i in range (0,3):
b.append(int(input("dame el valor de la componente de B: ")))
c1= (a[1]*b[2]-a[2]*b[1])
c2= (a[2]*b[... |
72d11b218f1fbd4bc5de98277a79f7964bba91c5 | matheusribeirog/cognitive | /aula03/01_revisaopython_numpy_pandas.py | 2,023 | 3.8125 | 4 | # pip install pandas, numpy, ipython, scikit-learn, matplotlib
#Sobre Spyder
# ctrl + P
# F5 / F9
import pandas as pd
import numpy as np
from IPython.display import Image, display
# Funcao
# https://www.w3schools.com/python/python_functions.asp
def soma_funcao(x, y):
return x + y
resultado_soma_funcao = soma_fun... |
13a703f47484d8b9d7008b097b599bac058dbd1b | sarthakturkar75/python_practicals | /string.py | 1,744 | 3.828125 | 4 | str = "i aM IrOnmAn"
str0 = "i\taM\tIrOnmAn"
str1 = "ṅśṅḍḥñṭḍ"
str2 = "8696590494"
str3 = "1.5 3.6"
print(str.capitalize())
print(str.casefold())
print(str.center(20, "-"))
print(str.count("n"))
print(str.count("nm"))
print(str1.encode("ascii", "ignore"))
print(str1.encode("ascii", "xmlcharrefreplace"))
pri... |
b21569732e0458a10a883dfb33a4ebefdfb08547 | anvandev/TMS_HW | /HW/task_1_5/task_4_5.py | 1,125 | 3.859375 | 4 | """ Закрепить знания по работе с циклами. Составить список чисел Фибоначчи содержащий 15 элементов.
(Подсказка: Числа Фибоначчи - последовательность, в которой первые два числа равны
либо 1 и 1, а каждое последующее число равно сумме двух предыдущих чисел.
Пример: 1, 1, 2, 3, 5, 8, 13, 21, 34... ) """
# using for loop... |
c78faf447251f861aae637cf1e98c7719e451eff | lil-mars/pythonProblems | /binaryVSsimple/search.py | 519 | 3.859375 | 4 | #Comparing binary search vs fast search
# 9780333
# for number in range(0, 10000000000):
# print(number)
# if 10000000 == number:
# break
searched_number = 10000000
max_bound = 10000000000
minBound = 0
while max_bound:
mid_number = (max_bound + minBound) // 2
print(mid_numbe... |
c8fa461f4e9f904148d9a9669c70fe0a06b93338 | liuxiaoliang/L | /common/util.py | 531 | 3.5625 | 4 | #! /usr/bin/env python
#
# Copyright (c) <2014> <leon.max.liew@gmail.com>
#
"""common utilities
"""
__author__ = "xiaoliang liu"
import sys
import time
class Timing(object):
"""computer used time by a process
unit: milliseconds
"""
def __init__(self):
self.cur_time = 0
def start(s... |
f55640b5845ea7434d5c2a81585eabe0a275af45 | feliperfdev/100daysofcode-1 | /Introdução ao Python/week1/day5/listas_aninhadas.py | 1,207 | 4.28125 | 4 | '''
Listas Aninhadas
-> Linguagens como C/Java possuem uma estrutura de dados chamada array:
- Unidimensionais (arrays/vetores)
- Multidimensionais (matrizes)
-> Em Python temos as listas
'''
print('\n')
# Exemplo:
lista = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(type(lista))
print(lista)
print('\n... |
551a0ed539a451f04c298ac69b34101978a873d0 | rabin-nyaundi/micropilot-entry-challenge | /rabin-nyaundi/count_zeros.py | 376 | 3.828125 | 4 | def count_zero(arr):
result_arr = []
for i in arr:
if i == 0:
result_arr.append(i)
return result_arr
result = count_zero([1,2,3,0,0,0,8])
assert len(result) == 3
print("Test 1 passed")
result = count_zero([0,0,0,0,0,0,])
assert len(result) == 6
print("Test 2 passed")
result = count... |
de4e52cd88e17dd2493d6f9d1b49227b2b1b1aa9 | KodeBlog/Python-3 | /11-while-loop/app.py | 602 | 3.765625 | 4 | i = 0
while i < 5:
print(i)
i += 1
import random
condition = True
while condition:
n = random.randint(1,7)
m = random.randint(1,10)
if (n > m):
print (f'The winning number is {n}, it was blessed by {m}')
condition = False
else:
print(f'The losing number is {n}, it wa... |
79b7ffad85187d12d4819b1c7e54a02916abe49d | jaramosperez/Pythonizando | /Ejercicios Operadores y expresiones/Ejercicio 01.py | 580 | 4.1875 | 4 | # Realiza un programa que lea 2 números por teclado y determine los siguientes aspectos
# (es suficiene con mostrar True o False):
#
# Si los dos números son iguales
# Si los dos números son diferentes
# Si el primero es mayor que el segundo
# Si el segundo es mayor o igual que el primero
a = float(input('Ingrese un n... |
648852ebb2e4442d003e3e796bb3133a71b2ec51 | RyujiOdaJP/python_practice | /ryuji.oda19/week02/c30_int_list.py | 243 | 3.578125 | 4 | def int_list(L):
if len(L) == 0:
return False
else:
try:
X = [isinstance(L[i],int) for i in range(len(L))]
print(X)
return all(X)
except TypeError:
return False
|
a3ca79690bf400fa772db768f0d5976326890ec5 | ledzerck/devf | /operadoresDeAsignacion.py | 334 | 3.984375 | 4 | ## Operadores de asignación
# = asigna un valor
# += suma el valor de la izquierda con el de la derecha
# -= resta
# *= multiplica
x = y = z = 5
print(x)
print(y)
print(z)
print("---------")
a,b,c = 1,2,"Jose"
print(a)
print(b)
print(c)
print("---------")
x = x + 10
print(x)
x += 10
print(x)
x -= 10
print(x)
x *=... |
660f64753d2f14317e04c41cf7e5a115b6e93820 | Giantpizzahead/comp-programming | /Project Euler/p17.py | 1,332 | 3.609375 | 4 | digits = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
tens = ['N/A', 'N/A', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def get_wo... |
35b09e6edb632af056589186afd23ddaf1765e56 | herbetyp/Exercicios_Python | /Mundo 1 - Fundamentos/ex025-procurando uma string dentro de outra.py | 134 | 3.59375 | 4 | nome = str(input("\nDigite seu nome completo: ")).strip()
print('Seu nome tem a palavra "Silva" ? {} '.format('Silva' in nome))
|
b4cc403055f523ec8a7c68d4e9e98bead648aa7c | egar-garcia/AIND_Project3_Adversarial_Search | /opening_book.py | 2,569 | 3.5625 | 4 | import random
import pickle
from collections import defaultdict, Counter
from isolation import Isolation
NUM_ROUNDS = 1000000
#NUM_ROUNDS = 50000 # This is to get within the limits of the review tool
DEPTH = 6
DATA_FILE = 'data.pickle'
def build_table(num_rounds=NUM_ROUNDS):
"""
Creates the table of opening m... |
59230f05474f2261674592377dc887ff89fdbb87 | KunyiLiu/algorithm_problems | /kangli/leetcode/hash_table/find_common_characters.py | 783 | 3.515625 | 4 | class Solution:
def commonChars(self, A):
d, delete = {}, []
res = []
for c in A[0]:
d[c] = 1 if c not in d else d[c]+1
for word in A[1:]:
for k, v in d.items():
if k not in list(word):
delete.append(k)
c... |
55cfcefef97312fa2cd309f8cdc071128ed4f478 | yewei600/Python | /Crack the code interview/Minesweeper.py | 846 | 4.21875 | 4 | '''
algorithm to place the bombs
placing bombs: card shuffling algorithm?
how to count number of boms neighboring a cell?
when click on a blank cell, algorithm to expand other blank cells
'''
import random
class board:
dim=7
numBombs=3
bombList=[None]*numBombs
def __init__(self):
print "let's ... |
ad132f338c5b967896b9ea97ece06501e73e2c7b | hyun98/Project_AlgoStudy | /study/2021.03-2021.04/team1/Week04/BOJ_11057_박시형.py | 393 | 3.609375 | 4 | N = int(input())
if N >= 3:
arr = [i for i in range(10,0,-1)]
for i in range(N-2):
arr_temp = []
temp = []
for idx in range(len(arr)):
arr_temp.append(arr[idx:])
for j in range(len(arr_temp)):
temp.append(sum(arr_temp[j]))
arr = temp[:]
# print... |
eeea939622fa90b7f325f0d48101a90f1f26e639 | anilhoon/penta_python_study | /lotto.py | 696 | 3.90625 | 4 | import random
# Create lotto List
lotto=[]
# 1 ~ 45 number insert
for number in range(1,46):
lotto.append(number)
print(lotto)
# choice 6 numbers
# for 문 보다는 while 문을....len(lotto2) = 6일 때 까지..
# Service number 때문에 7번 실
lotto2=[]
print(len(lotto2))
#for num in range(6): # number
for num in range(7): # servi... |
6d64467772d28087b6c0bb4d89b8b544f2c247f8 | twumm/upcoming-movie-trailers | /entertainment_center.py | 1,838 | 3.734375 | 4 | '''This file makes a request to themoviedb.org's api and fetches the following
movie details:
title, storyline/overview, poster image url, youtube trailer url and the
release date
'''
import media
import fresh_tomatoes
import requests
# access the api and convert it to a json file
MOVIE_LIST = requests.get("https://ap... |
7edec0e891bd01a2d0223d6aaf70bc58b934efb7 | Ting0718/Leetcode | /String/344_reverse_string.py | 682 | 3.9375 | 4 | '''use python in-built function'''
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
'''iteratively swap left and right'''
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
tmp = s[left]
... |
f163b27f07f5a4a4e34804a91b7222e5047a0eb8 | patela29/OOD | /primenumbers.py | 470 | 4.125 | 4 | #Jeffrey Creighton
#Updated by Anand Patel
#Looks through each number within the range and prints it if prime.
def primenumbers(i):
for j in range(2, i+1):
if checkPrime(j): #find out if j is prime
print j
#Checks to see if a number is prime. Returns false if any number less than sqrt+1 divides evenly, true oth... |
c4613f6ad8a571db354d428c78a9f5441cdc62a0 | tyriem/PY | /Intro To Python/41 - GUI - Radio Button SelectGet - TMRM.py | 1,047 | 4.25 | 4 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - GUI: Radio Buttons Select & Get
### VER: 1.0
### DATE: 06-06-2020
#####################
### GUIs ###
#####################
### OBJECTIVE ###
#Code a basic GUI for user
#
### OBJECTIVE ###
##Declare CALLs & DEFs
from tkinter import*
#First, we import the t... |
164fd89684bec7fd144308b525eeec393a6dd404 | awedz/uni | /python/dp/singleton/sngtn.py | 313 | 3.703125 | 4 | class Singleton:
__myList = []
def GetInstance(self):
return self.__myList
def Insert(self,data):
if self.__myList is None:
self.__myList = []
self.__myList.append(data)
a1 = Singleton()
a1.Insert( 1 )
a2 = Singleton()
a2.Insert( 2 )
print( a1.GetInstance() )
|
478d287b8a64a188fec68fb70106fd8ecdc324f6 | Auclown/algo-challenge-py | /010_alternating-sums/attempt.py | 304 | 3.765625 | 4 | def alternating_sums(people):
team_one = 0
team_two = 0
for i in range(len(people)):
if i % 2 == 0:
team_one += people[i]
else:
team_two += people[i]
return [team_one, team_two]
# Test
print(alternating_sums([50, 60, 60, 45, 70])) # [180, 105]
|
decf6342b0fc75bcf2fa73486341e8c0e8b7be5b | jasmin-guven/labile_HD_exchange | /pdb2DF.py | 2,736 | 3.515625 | 4 | import numpy as np
import pandas as pd
import csv
import os.path
def is_path(filepath):
is_path = os.path.isdir(filepath)
while is_path == False:
filepath = input('Invalid directory %s. Please enter again: ' %(filepath))
is_path = os.path.isdir(filepath)
return filepath
def is_file(filep... |
b7d6e97569e0b2e85b8c741e62ed0daee1651e27 | Jojtek/allPythonLabsAndProject | /Zad4.py | 559 | 4.125 | 4 |
def insertsort(arr):
for i in range(1, len(arr)):
temp = arr[i]
j = i - 1
while j >= 0 and temp < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = temp
import random
arr=[]
for i in range (20):
arr.append(random.randrange(1, 101, 1))
sor =... |
b0dc54bc68d6b374c419e3edacbf5b7ebde7378d | luosch/leetcode | /python/Kth Smallest Element in a BST.py | 896 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def dfs(self, root, answer):
if root:
self.dfs(root.left, answer)
answer.append(root.val)... |
6275d78014687aa63aa75e5b323f98cc9f98395b | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mrnkud004/question4.py | 488 | 4.0625 | 4 | """finding palindromic primes
kennedy muranda
9/5/2014"""
import sys
sys.setrecursionlimit (30000)
#define function to check if number is palindrome
def palind(c):
if len(c)<2:
return True
else:
if c[0]==c[-1]:
return palind(c[1:-1])
else:
r... |
41ef03cadff0fab488de1475d1b4b1a22012b30b | neequole/my-python-programming-exercises | /unsorted_solutions/question68.py | 663 | 3.9375 | 4 | """ Question 68:
Please write a program using generator to print the numbers which can be
divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
Hints:
Use yield... |
01984a3f1be19145930da2615763d9859168f41e | ppak9/intern | /5주차/3.py | 227 | 3.90625 | 4 | # 2,3 은 하나에
# 2.py는 조건문에 대한 기본문을 작성하는 것
# 논리연산자 and or
numbers =[1,2,3,4,5,6,7,8,9,10]
for n in numbers:
if n%2==0 or n%3==0:
print(n)
else:
continue |
09eafe3a8b6f5079f9495da3c819d55bcdb7234e | zhangda7/leetcode | /solution/_101_symmitric_tree.py | 2,133 | 4.3125 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015/8/24
@author: dazhang
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:... |
12f9519b6d6304712969380b708455915ff171f1 | nikhil-nakhate/search-engine-udacity | /test.py | 576 | 3.875 | 4 | '''
Created on 21 Apr 2013
@author: Nikhil
'''
def find_element(p, t):
i = 0
for e in p:
if (e == t):
print i
return i
i = i+1
return -1
find_element([1,2,3], 3)
def find_element_in(p, t):
if (t in p):
print p.index(t)
return ... |
737e967a5037124beae855b3f6ddcc44e39bfaa5 | andreaumac/Python | /Classe.py | 3,174 | 4 | 4 | print(type(1))
print(type([]))
print(type(()))
print(type({}))
#instancia da class list(objeto)
l = [1,2,3]
print('----------------------------')
class Dog(object):
#construtor
def __init__(self, raca):
self.raca = raca #public
#self.__raca = raca #privado
rex = Dog('vira-lata')
print(rex.rac... |
43784a9c4b2a701899a93f251919b608b53c6972 | yhxddd/python | /lian.py | 614 | 4.0625 | 4 | '''
print("--------------文字小游戏----------------")
temp = input("猜猜我想的是数字几(3次机会哦!):")
guss = int(temp)
if guss == 8:
print("对咯!")
else:
for content in range(0,3):
content = 3
temp = input("猜错了 重新输入吧!")
guss = int(temp)
if guss == 8:
print("对咯!")
... |
97730b7e22c7eb4b8dfd256d7a67325d225fe05e | Aasthaengg/IBMdataset | /Python_codes/p03815/s962131495.py | 106 | 3.71875 | 4 | x=int(input())
ans=(x//11)*2
if x%11==0:
pass
elif 0<x%11<=6:
ans+=1
else:
ans+=2
print(ans)
|
1d3753de01b4f7e96b64ee6faf91c4ace26ba78f | paik11012/Algorithm | /lecture/day02/day02_3.py | 1,194 | 3.640625 | 4 | # def bin(n,key):
# l = 1
# r = n
# cnt = 0
# while 1:
# mid = int((l+r)/2)
# cnt +=1
# if mid == key:
# return cnt
# break
# elif
import sys
sys.stdin = open('sample_3.txt','r')
def binary_search(a, key): # 400개가 든 리스트 a
start, end = 0, len(a) # len(... |
d79ce832b1d924d57248270e04890e5a3137d56a | rafsie/scripts | /articles_counter.py | 297 | 3.828125 | 4 | from string import punctuation
s = input('Wprowadź jakiś tekst: \n')
for c in punctuation:
s = s.replace(c, '')
s = s.lower()
L = s.split()
words = ['a', 'an', 'the']
print()
for item in words:
article = L.count(item)
print("Słowo '{}' występuje {} razy.".format(item, article))
|
b4ad7b1f331b92371c30be5b028b0c45dbcb9bf8 | Devinlomax/Ch3-Programming-Assignment | /#6.py | 1,032 | 4.09375 | 4 | #6. A software company sells a package that retails for $99. Quantity discounts are given according to the following: 10 – 19 (10%), 20 - 49 (20%), 50 – 99 (30%), and 100 or more (40%). Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the disco... |
2ff7c89b6ca6e95208850dfa77fe7630ad31610c | avldokuchaev/testProject | /body_square.py | 2,211 | 4.0625 | 4 | # Рассчет площади поверхности тела
def square_body_chemotherapy(weight_float, height_float):
square_body = 0.0167 * weight_float ** 0.5 * height_float ** 0.5
square_body_result = round(square_body, 2)
return square_body_result
height = float(input("Введите рост в сантиметрах: "))
weight = float(input("Вв... |
3b15767988f1d958fc456f7966f425f93deb9017 | juliehub/python-practice | /string/anagrams.py | 591 | 4.0625 | 4 | """
Given two strings, a and b, that may or may not be of the same length,
determine the minimum number of character deletions required to make
a and b anagrams. Any characters can be deleted from either of the strings.
"""
from collections import Counter
import math
import os
import random
import re
import sys
# Com... |
75fdae0a570ddea8c84fad8f6f52d0bccd77729b | subodhss23/python_small_problems | /hard_problems/oddly_or_evenly_positioned.py | 1,096 | 3.96875 | 4 | '''Create a function that returns the characters from a list or string r on odd or even positions, depending on the specifier
s. The specifier will be "odd" for items on odd positions(1,3,5,....) and "even" for items on even positions(2,4,6,...)'''
def char_at_pos(r, s):
if type(r) == list:
new_lst = ... |
96ed932274c368a1bd7ba93afed1e8546575a38a | ekdeguzm/space_invaders | /space_invaders.py | 10,280 | 4.0625 | 4 | # Space Invaders
# Python 3.9.5 on Mac
import turtle
import os
import math
import random
import platform
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Space Invaders")
screen.setup(width = 700, height = 700)
screen.tracer(0) # shuts off all the screen updates
# Register the sh... |
580be650f840ef13d4fd478d75f8dba4c5273f95 | maiya-tracy/helloFlask | /hello.py | 996 | 3.578125 | 4 | from flask import Flask # Import Flask to allow us to create our app
app = Flask(__name__) # Create a new instance of the Flask class called "app"
@app.route('/') # The "@" decorator associates this route with the function immediately following
def hello_world():
return 'Hello World!' # Return the strin... |
9459cbf14133847e1e0558bab3b42d701f961ddf | VLD62/PythonFundamentals | /01.PYTHON_INTRO_FUNCTIONS_DEBUGGING/06.Math_Power.py | 182 | 3.78125 | 4 | def power_calculator(n,pow):
return n ** abs(pow)
if __name__ == '__main__':
number = float(input())
power = int(input())
print(power_calculator(number,power)) |
d6198d84c1a376eb709049ab982db14e418698c9 | kjnh10/pcw | /work/atcoder/abc/abc079/B/answers/782387_amukichi.py | 306 | 3.59375 | 4 | #!/usr/bin/env python3
import functools
@functools.lru_cache(maxsize=None)
def lucas(n):
if n == 0:
return 2
elif n == 1:
return 1
else:
return lucas(n - 1) + lucas(n - 2)
def main():
n = int(input())
print(lucas(n))
if __name__ == '__main__':
main()
|
d8da81942f3a41175ffeff7d65f2f7de4950328c | ekjellman/interview_practice | /ctci/17_3.py | 825 | 3.953125 | 4 | ###
# Problem
###
# Write a method to randomly generate a set of m integers from a list of size
# n. Each element must have an equal probability of being chosen.
###
# Work
###
# Questions:
# Sizes of m and n? (assume fits in memory)
# Invalid inputs? (Assume input is valid)
# -- negative m, m > n, etc.
import ran... |
602c4f96aebb51ffa0ee20f861f45e1340e79f4b | FelipeLauton/Python | /Exercicios/ex007.py | 171 | 3.796875 | 4 | medida = float(input('Uma distância em metros: '))
cm = medida * 100
mm = medida * 1000
print('A distância de {}m em cm vale {}cm e em mm {}mm.'.format(medida, cm, mm))
|
7f4503b51c5c06b2c97242a6058450ac5ca17978 | KumarSanskar/Python-Programs | /Getting_items_of _list.py | 669 | 4.75 | 5 | # Programs to access items/elements of the list:
# (1) Using index:- This can be used to get a specific item:
lst = ["Ram","Ali","Hardy","Joe"]
print("List is: ",lst)
print("Item at second is:",lst[2])
# (2) Using negative index:- this can be used to acces item from backwards, (-1) represents last element:
... |
c59789e7ccc1f32b917c659347e9d00a4b497df6 | mgermaine93/python-playground | /python-coding-bat/warmup-1/monkey_trouble/test_module.py | 1,163 | 3.5625 | 4 | import unittest
from monkey_trouble import monkey_trouble
class UnitTests(unittest.TestCase):
def test_true_and_true_returns_true(self):
actual = monkey_trouble(True, True)
expected = True
self.assertEqual(
actual, expected, 'Expected calling "monkey_trouble() with "True" and ... |
4ac47b9c33a339eff8496612c2d841f492122157 | Tiyasa41998/py_program | /temp.py | 97 | 3.796875 | 4 | c= float(input("enter the temparature"))
f=(c*9/5)+32
print("the temparature is" ,float(f))
|
a3bb5d8bd60c5c5e6a23aa0dfd33eb7b038ad0c9 | nat-g/algorithms | /BasicDataStructures/linked_lists/singly_linked_list.py | 629 | 3.578125 | 4 | #!/usr/bin/env python
"""
Pros:
1) Linked lists have constant insertion and deletion time at any position
n comparison arrays will always require linear (meaning O(n)) to do the
same thing
2) Linked lists can also expand without specifying their size ahead of
time (amortization reference)
Cons:
1) Lookup time is ... |
29841f1c1c7fb2bb63b10d84df3cc73a349d7191 | younes38/Daily-Coding-Problem | /uber_problems/problem_4.py | 544 | 4.1875 | 4 | """This problem was asked by Uber.
Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods:
next(): returns the next element in the array of arrays. If there are no more elements, raise an exception.
has_next(): returns whether or not the iterator stil... |
0fd8b7c6d2cf62cb26e520db90fd717231fb2dcc | icarogoggin/Exercitando_python | /Exercicios11_PintandoParede.py | 302 | 3.9375 | 4 | largura = float(input('Digite a largura da parede: '))
altura = float(input('Digite a Altura da parede: '))
area = largura*altura
print(f'Sua parede tem a dimensão de {largura}x{altura} e sua área é de {area}m')
tinta = area/2
print(f'Para pintar essa parede, você precisará de {tinta}l de tinta') |
79691788a8cd9dca4857937a16a18af632a30be7 | dingkillerwhale/Python | /My_Python/Manhattan_Distance.py | 169 | 3.640625 | 4 | # Manhattan Distance
from numpy import * # import numpy libraries
v1 = array([1,2,3])
v2 = array([4,5,6])
print(sum(abs(v1 - v2))) # print Manhattan Distance
|
799fccf6325d7f38069b9dd7b42ec459d77643af | qiang-yu-scd/Python_cursus | /pe5_1.py | 251 | 3.703125 | 4 | score = input ( 'Geef je score: ' )
if int(score) >= 15:
print ( 'Gefeliciteerd!' )
print ( 'Met een score van' + ' ' + str(score) +' ' + 'ben je geslaagd!' )
else:
print ( 'Met een score van' + ' ' + str(score) +' ' + 'ben je Gezakt!')
|
99f862a58831afe3072727be21fea0163f6c5b35 | omdeshmukh20/Python-3-Programming | /string1.py | 243 | 3.828125 | 4 | #Discription: str input
#Date: 10/07/21
#Author : Om Deshmukh
print("Enter the element:")
element=str(input())
for i in range(element):
if element=str.upper():
print(element.lower())
else element=str.lower():
print(element.upper())
|
6b1deb02f50a897037c402e8f8736c30c772233b | mrfabroa/ICS3U | /Archives/2_ControlFlow/2_5_1_Practice/question_3_for_loop.py | 899 | 4.28125 | 4 | """
Write a trip calculator that allows the user to enter how many trips they’ve travelled (in km) and
then the distance travelled for each trip. It should then output the total distance travelled.
"""
number_of_trips = input("How many trips did you travel?")
total_distance = 0
for i in range(1, number_of_trips + ... |
0c30c0a6c467442df9f6136d7bb6841fc59bc36f | TanyaFox/3_bars | /bars.py | 1,537 | 3.75 | 4 | import json
import math
def load_data(filepath):
with open(filepath, 'r') as json_file:
data = json.load(json_file)
return data
def get_biggest_bar(data):
biggest_bar = max(data, key = lambda i: i['SeatsCount'])
return (biggest_bar['Name'], biggest_bar['SeatsCount'])
def get_smallest_bar(dat... |
fcd05d370cf43d9fddefdeea050748ecef709ca4 | jmruzafa/cd50-problem-set | /pset6/credit/credit.py | 2,203 | 3.921875 | 4 | #!/bin/python3
import cs50
import math
def main():
# message
result = "INVALID"
while True:
# ask for the change owed
creditcard = cs50.get_int("Number: ")
if creditcard >= 0:
break
# get the lenght of the CC number (easier in pyhton than C)
# it could be do... |
e006ef63dad027281a421c972f761913c5fdb4d2 | Lusarom/progAvanzada | /ejercicio93.py | 790 | 3.984375 | 4 |
def nextPrime(n):
while True:
if n < 0:
print("www")
print("El número no es un entero positivo")
n = float(input("Ingrese un número entero positivo: "))
elif n != int(n):
print("El número no es un entero positivo")
n = float(in... |
d6c644c054f05051263f7ba3a98050450910f495 | hellohaoyu/codeEveryDay | /constructStringFromBinaryTree.py | 1,492 | 3.78125 | 4 | # Leetcode: https://leetcode.com/problems/construct-string-from-binary-tree/description/
# Input: Binary tree: [1,2,3,4]
# 1
# / \
# 2 3
# /
# 4
# Output: "1(2(4))(3)"
# Explanation: Originallay it needs to be "1(2(4)())(3()())",
# but you need to omit all the unnecessary empty p... |
92b2b4abee66646bdbf171da3081a6a08a9ff0c6 | snlab/utilities | /mininet/ysn_linuxrouter.py | 3,830 | 3.671875 | 4 | #!/usr/bin/python
"""
linuxrouter.py: Example network with Linux IP router
This example converts a Node into a router using IP forwarding
already built into Linux.
The topology contains
MX-router (r1) with two IP subnets:
- 130.132.11.0/24 (interface r1-eth1 IP: 130.132.11.1)
- 192.31.2.0/24 (interface r1-eth2 IP... |
ff849e53eee5fe198eb33eaaa4aa9f4a3e1c7096 | sdfgx123/Python_lecture | /section_8_Dynamic_programming/4.py | 595 | 3.59375 | 4 | # 도전과제 돌다리 건너기 bottom up
# 쉽게 생각해서, top down은 DFS, bottom up은 dynamic programming 생각
import sys
sys.stdin=open("C:\Python-lecture\Python_lecture\section_8_Dynamic_programming\input.txt", "rt")
# def DFS(x):
# if dy[x]>0:
# return dy[x]
# if x==1 or x==2:
# return x
# else:
# dy[x]=D... |
3c3100353ea38b11bffd0b6558e40c4060266e93 | research-fork/SMTsolver | /smt_solver/solver/solver.py | 826 | 3.921875 | 4 | from abc import ABC, abstractmethod
class Solver(ABC):
@abstractmethod
def __init__(self):
"""
Initializes the solver.
"""
pass
def create_new_decision_level(self):
"""
Creates a new decision level.
"""
pass
def backtrack(self, level: ... |
20eebbe85ae1b1f2d50297cd9a036c77d63aeb00 | lixiang2017/leetcode | /leetcode-cn/1436.0_Destination_City.py | 877 | 3.703125 | 4 | '''
Hash Table
执行用时:36 ms, 在所有 Python3 提交中击败了50.15% 的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了69.66% 的用户
通过测试用例:103 / 103
'''
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
a2b = {}
for a, b in paths:
a2b[a] = b
city = paths[0][1]
while city in a2b:
... |
7f61e27afa407ba726e261040cae124cf05e8828 | juliendurand/geoapi | /src/trigram.py | 1,526 | 3.765625 | 4 | """
Copyright (C) 2016 Julien Durand
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... |
f71c00f69d927ea007db0d44ffbe832a598b0ca4 | jxlxt/leetcode | /Python/92.reverse_linked_listII.py | 756 | 3.6875 | 4 | class Solution:
def reverseBetween(self, head, start, end):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy_head = sublist_head = ListNode(0)
sublist_head.next = head
for _ in range(1, start):
sublist_h... |
2d46b5ee5c79dc997df806e1df1dc37ef0cd5f94 | bakunobu/exercise | /python_programming /Chapter_1.1_and_1.2/order_check.py | 773 | 4.21875 | 4 | """
Составьте программу, получающую в аргументах командной строки три значения,
х, у и z типа float, а выводящую True, если значения расположены в порядке
возрастания или убывания (х < у < z или х >у> z), и False в противном случае.
"""
def in_a_raw(x:float, y:float, z:float) -> bool:
"""
An order checker
... |
414054aed84fa777b5c21b3409b6c5e1a628f791 | flora-pura/pog | /listAppV1DeBerry.py | 4,614 | 4.21875 | 4 | """
Program Goals:
1. Get input from the user (at multiple points)
2. We need to convert some of this input to INTs from StRs
3. We need to provide choices to the user
a. Add more values to the list
b. Return a value a speciftic index
"""
import random
myList = []
uniqueList = []
def mainProgram():... |
b4e90b4be5e93f441ff131ba49dd04c36428ea9e | AHowardC/python101 | /excerise.py | 1,781 | 4.0625 | 4 | name = raw_input("What is your name")
#day 4 algorithim 1
# if we list all natural numbers below 10 that are mulitiples of 3 or 5, we get 3,5,6, and 9.
# the sum of these nultiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
empty_list = []
for i in range (0, 1000, 3):
empty_list.... |
9142898d5d79f70e9cd31c6704d07da464fbb38b | Sandraopone1/python_fundamentals | /findCharacters.py | 548 | 3.796875 | 4 |
# def findCharacters(listed,singlechar):
# newArr = []
# for x in range(0,len(listed)):
# if listed[x].find(singlechar) != -1:
# newArr.append(listed[x])
# return newArr
# print findCharacters(['hello', 'the'], 'l')
word_list = []
def FindCharacters(list, character ):
for word in list:
for char i... |
dafc642f39bbc5dbdebdb91ef85c83e064727063 | sifo/hackerrank | /python/built_ins/athlete_sort.py | 307 | 3.671875 | 4 | # https://www.hackerrank.com/challenges/python-sort-sort/problem
if __name__ == '__main__':
N, _ = map(int, input().split())
l = []
for i in range(N):
l.append(list(map(int, input().split())))
K = int(input())
l = sorted(l, key=lambda x: x[K])
for i in l:
print(*i)
|
8f0afa4f5a2f06d884db53e6b99096e74c03cb0b | maurus56/exercism | /python/word-count/word_count.py | 192 | 3.6875 | 4 | def word_count(phrase):
import re
phrase = re.compile(r"[a-z]+'?[a-z]|[0-9]").findall(phrase.lower())
d = {}
for key in phrase:
d[key] = d.get(key, 0) + 1
return d |
136918e0c0b7c1d655fabeab683cc091da981f65 | Jean-Martins22/Exercicios-Python | /Projeto_03.py | 4,428 | 3.828125 | 4 | # Importanto a biblioteca randint para escolher aleatóriamente
from random import randint
# Importanto a biblioteca sleep para fazer pausas durante um print e outro
from time import sleep
# Mostrando a apresentação do campeonato e as Regras
print('-=-' * 32)
print(' Sejam bem vindos ao... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.