blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5acca960951c7c40be5d2545e058623af45cb86f | Yutreess/lc101-initials | /initials.py | 568 | 4.1875 | 4 | def get_initials(fullname):
""" Given a person's name, returns the person's initials (uppercase) """
# TODO your code here
# Make name uppercase
names = fullname.upper()
# Separate into different words
names = names.split()
initials = ""
for name in names:
initials += na... |
8ee9229f1fff3dae7f211348086f7d8945bec6e9 | peguin40/cpy5p4 | /q3_find_gcd.py | 397 | 4.03125 | 4 | #q3_find_gcd.py
# Finds greatest common divisor of 2 numbers
# Define function
def gcd(m,n):
if (m%n) == 0:
return n
else:
return gcd(n,m%n)
# get inputs
while True:
try:
m=int(input("Please enter the 1st integer: "))
n=int(input("Please enter the 2nd integer: "))
... |
ea44ec681af1cae61e8b85301bc6d573c9005892 | mdash/helper-functions | /visualization/distributions.py | 5,673 | 3.5625 | 4 | """Perform useful descriptive visualizations of variable distributions
Classes:
-----------------
VarDistributions -- Plot distributions of various variables given a dataframe
"""
import pandas as pd
import numpy as np
import ipywidgets as widgets
from ipywidgets import HBox, Layout, Output, VBox
from IPython.displa... |
b271e9bfcd8c9b4be1be0a3faff80f45c59bc165 | GeliaNiz/pythonPractice3 | /Mathplot/main.py | 2,530 | 3.53125 | 4 | from random import randint
from time import sleep
import matplotlib.pyplot as plt
# Initialization
population = int(input())
height = int(input())
width = int(input())
field = [[0 for x in range(height)] for y in range(width)]
percent = float(input())
tolerant = float(input())
steps = int(input())
colors = ['red', 'gr... |
19bf5a6812ce4d4d9f476f1edebf42665986fb61 | yenext1/python-bootcamp-september-2020 | /lab5/exercise_3.py | 225 | 4.15625 | 4 | # if can be divided by 7 return boom
num = input("Pick a number!")
while (int(num) % 7 != 0):
num = input("Pick another number!")
print("BOOM!")
"""
Uri's comments:
==============
* Very good! This code works.
"""
|
b1f6fcbae950b8334960ecabc7b97d3efeef9370 | yenext1/python-bootcamp-september-2020 | /lab19/exercise_1.py | 723 | 3.96875 | 4 | # if user and pw exist return "Welcome Master" otherwise return "INTRUDER ALERT"
users = {
"apple": "red",
"lettuce": "green",
"lemon": "yellow",
"orange": "orange"
}
username = input("Please write your username ")
print("Thank you")
pw = input("Now, please write your password ")
try:
if users[use... |
7d5584a8000113accf6e0985034e6582206b9e54 | JaromPD/Robot-Finds-Kitten-Project | /rfk/game/casting/actor.py | 3,301 | 4.0625 | 4 | from game.shared.color import Color
from game.shared.point import Point
class Actor:
"""A visible, moveable thing that participates in the game.
The responsibility of Actor is to keep track of its appearance, position and velocity in 2d
space.
Attributes:
_text (string): The text to di... |
208d47c3b0ebe5820d764e05438308c572b2f870 | patvdc/python | /02-datastructures/03_collection_tuple.py | 3,115 | 4.21875 | 4 | # tuple () : collection data type
# ordered, immutable (read-only list), duplicate elements allowed
# create empty tuple
empty_tuple1 = ()
print("empty tuple\t\t",empty_tuple1)
# create empty tuple using constructor
empty_tuple2 = tuple()
print("empty tuple\t\t",empty_tuple2)
color_tuple = tuple(("green","yellow","w... |
f8086dade87e33863de113aca91a53258dd295d2 | patvdc/python | /01-basics/06-functions/06_function.py | 158 | 3.828125 | 4 | # return value
def square(x):
return x * x
print(square(3))
print(square(5))
print(square(9))
for i in range(11):
print(f"Square of {i} = {square(i)}") |
98fe57e16908edc6ff30152269a8533e0b37570f | patvdc/python | /02-datastructures/02_collection_array.py | 581 | 4.03125 | 4 | # array [] : collection data type
# use list (no array datatype) or numpy -> faster
# ordered, mutable, duplicate elements allowed
computer = ["dell","apple","samsung","lenovo"]
print(computer)
print(computer[3])
print("modify")
computer[2]="hp"
print(computer)
print("len")
x = len(computer)
print(x)
print("loop")
... |
24142981e8c35702493e6460da62c5f90c0fe687 | patvdc/python | /20-packages/os/01_os.py | 130 | 3.515625 | 4 | import os
print("delete file")
if os.path.exists("text2.txt"):
os.remove("text2.txt")
else:
print("file does not exist")
|
690fe007438c10d638c8e8c0520dd879878c22c0 | sreesudha1/-PYTHON-task | /ass6.py | 168 | 3.890625 | 4 | print("please enter your name")
name=input()
print("please enter your age")
age=input()
print("\n")
print(f"the name you had entered is {name} and age is {age}")
|
a642d3f8dd24ec6f42c2ddb258c802ee98bab579 | liugongfeng/CS61A | /exam_prep05.py | 1,961 | 3.796875 | 4 | def live(lon):
def prosper(spock, live):
nonlocal lon
if len(lon) == 1:
return spock + 1
lon[1] = live(lon[0])
lon = lon[1:]
prosper(lon[0], abs)
return spock[0] + 1
prosper(lon, lambda trek: trek - 3)
class Worker:
greeting = 'Sir'
def __init__(self):
self.elf = Worker
def... |
b71f85b2200c7bb4d4370284c10f2405e36570e6 | liugongfeng/CS61A | /ex/compo.py | 3,080 | 3.8125 | 4 | class Link:
empty = ()
def __init__(self, first, rest = empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __len__(self):
return 1 + len(self.rest... |
beaef033e9cf972715eabba7040af52aecc8cb4d | lcc19941214/python-playground | /src/features/slice.py | 824 | 3.828125 | 4 | # coding=utf-8
# slice
L = ['Loki', 'Steve', 'Natasha', 'Stark', 'Hulk', 'Eagle Eye', 'Thor']
print(L[0:3])
print(L[:4])
print(L[5:])
print(L[:-1])
print(L[-3:])
# slice with steps
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd = num[::2]
even = num[1::2]
print('odd number includes %s' % odd)
print('even number includes ... |
28db9c5e406f4a270660f63a52312df2ba4b020e | lcc19941214/python-playground | /src/basic/loop.py | 284 | 3.953125 | 4 | # coding=utf-8
# iterate a array
arr = ['Amy', 'Bob', 'Cindy']
for item in arr:
print(item)
# note that this variable is already declared
print(item)
sum = 0
for item in range(101):
sum += item
print(sum)
count = 0
while count < 1000:
count += 1
else:
print(count) |
f1501b9cdad41bab24ff9b15fbe9f90c789cad09 | lcc19941214/python-playground | /src/object-oriented-programming/private_property.py | 636 | 3.8125 | 4 | # coding=utf-8
import datetime
class Human(object):
def __init__(self, name, birth_year):
self.__name = name
self.birth_year = birth_year
def get_age(self):
year = datetime.date.today().year
age = year - self.birth_year
return age
def say_name(self):
prin... |
94096b5fa0b9c17ef2bf3b068829b1c6ecce6d04 | lcc19941214/python-playground | /src/functional-programming/anonymous-functions.py | 221 | 3.609375 | 4 | # coding=utf-8
'''
匿名函数只能有一个表达式,不用写return,返回值就是该表达式的结果
'''
L = range(1, 11)
L2 = map(lambda x: x*2, L)
print(L2)
func = lambda x: x**2
print(func)
print(func(5)) |
69772c379f519e1886eb516737b011e2ac19e93f | lcc19941214/python-playground | /src/functional-programming/partial-function.py | 464 | 4.3125 | 4 | # coding=utf-8
import functools
# partial function
print('\n# partial function')
'''
difference between partial function and curry function
@see https://segmentfault.com/q/1010000008626058
'''
'''
偏函数用于固定函数中的指定参数的值
'''
print(int('250'))
print(int('1234', 8))
print(int('10101010110', base=2))
def int_2(x, base=2)... |
186c5c853e58cfa4d884862502d3df043336ffb4 | sydatascience/Galvanize-1 | /Application/q1/q1.py | 2,620 | 4.5625 | 5 | #!/bin/python
"""Question 1:
Create a text content analyzer. This is a tool used by writers to find statistics
such as word and sentence count on essays or articles they are writing.
Write a Python program that analyzes input from a file and compiles statistics on it.
The program should output:
1. The total word c... |
a60bca8f84d0f6472a4f0f04004080565ccad129 | sydatascience/Galvanize-1 | /Learn/Unit 1/Development Workflow/hello.py | 539 | 4.15625 | 4 | """
The ideal workflow is to write a little bit of code,
then ensure that the code is doing what you expect by inspecting some output,
or playing with it in an interactive environment.
Plus, having a tight feedback loop is more fun.
"""
# Step 1: Writing the script. Use the Terminal to open hello.py
def hello_world()... |
b4093db7f68034234843ba35e68daacc29804c73 | TristanMoers/IA_Assignment1 | /pathologic.py | 5,925 | 3.53125 | 4 | # -*-coding: utf-8 -*
'''NAMES OF THE AUTHOR(S): Gaël Aglin <gael.aglin@uclouvain.be>, Francois Aubry <francois.aubry@uclouvain.be>'''
from search import *
import time
#################
# Problem class #
#################
class Pathologic(Problem):
def successor(self, state):
# We list all a... |
4c21435af63cd76326da5d63882a7fbc815d2b27 | devmohit-live/Prep | /Level1/Arrays/reverse_array.py | 461 | 3.921875 | 4 | ''' Reversing the array O(N) => runtime= O(n/2) half of the siz
using two pointers approach one starting from left and one from right
'''
def reverse_array(l):
low, high = 0, len(l)-1
while low < high:
l[low], l[high] = l[high], l[low]
low += 1
high -= 1
t = int(input())
for _ in ran... |
f25645365c1514d10f83688a02f1a3416ad50093 | devmohit-live/Prep | /Level1/recursion/Python/Palindrome.py | 361 | 3.984375 | 4 | def isPalindrome(s, start, end) -> bool:
if(start == end or start > end): # start=end ex: abba(even) start>end aba(odd)
return True
if s[start] == s[end]:
return isPalindrome(s, start+1, end-1)
if s[start] != s[end]:
return False
t = int(input())
for _ in range(t):
s = input()... |
62e866fa649d59c9eaadff517216b7f8d163d9fc | andrewlee977/SQL-modules | /module1/sqlite_example.py | 631 | 3.703125 | 4 | """An example of a sqlite3 workflow"""
import sqlite3
from query import SELECT_CHARACTERS
# STEP 1: Connect to the database
def connect_to_db(db_name="../data/rpg_db.sqlite3"):
return sqlite3.connect(db_name)
# STEP 2: Make a cursor from our connection
# STEP 4: Execute Query
# STEP 5: Fetch results
def execute... |
106f76ee11d42e74207e8f5c957a016b4ec14099 | itscamlong/201-recursion-ex | /factorial.py | 369 | 4.0625 | 4 | def factorial(n):
# Prevent negative numbers... because duh
if n < 0:
print("Can't do negative numbers!")
return 0
# It's the base case!
elif n == 1:
return 1
# Ladies and gentleman... recursion
else:
answer = n * factorial(n-1)
return answer
if... |
128af6e6946bee1baaea579821058f5a7a537d9e | namiranianp/ECIES | /ECIES.py | 7,227 | 3.671875 | 4 | #!/usr/bin/env python
"""
IMPORTANT NOTE:
This code is written using Python 2.7.5 and will not correctly run on Python 3.
If you are running into issues check the Python version of your machine. This
code can be converted to Python 3 by changing the raw_inputs to input.
"""
import os
import pickle
import hmac
import... |
e570757ce2cce03d9d0c1a48d5539ffb23534389 | waterlp/python_grammer | /practice/丑数.py | 1,328 | 3.734375 | 4 | def nthUglyNumber_t(m):
# write your code here.
# 找出m的下一个丑数
while True:
m += 1
n = m
while True:
if n == 1:
break
elif n % 2 == 0 :
n = int(n/2)
continue
... |
38f37d34e116c4245534fa770436a24bac2d021f | DanielPagetti/advanced_bootcamp | /madlibs.py | 1,065 | 3.96875 | 4 | my_textfile = open('textfile.txt', 'w')
my_textfile.write('The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.')
my_textfile.close()
ADJECTIVE = input("Enter an adjective: ")
NOUN = input("Enter a noun: ")
ADVERB = input("Enter an adverb: ")
VERB = input("Enter a verb: ... |
81b8e8d57047ab3cf0ebcdb0edbdad63e45f2f11 | Anamika79/Python_Projects | /Table.py | 637 | 3.5625 | 4 | from tkinter import *
class Table:
def __init__(self, root):
for i in range(rowno):
for j in range(columnno):
self.e = Entry(root, width=20, fg="black", bg="white", font=('Arial', 16, 'bold'))
self.e.grid(row=i, column=j)
self.e.insert(END, l... |
a8bcb75ce5847905c8d825aaef5b97c74524cce1 | BellaShah/DataStructureProjects | /TestBinaryTree.py | 5,314 | 4.03125 | 4 | # File: TestBinaryTree.py
# Description: Creates an Binary Search Tree and tests several function. Also, created test cases.
# Student's Name: Bella Shah
# Student's UT EID: BHS533
# Course Name: CS 313E
# Unique Number: 50945
# Date Created: April 26, 2016
# Date Last Modified: April 26... |
fd486f5c2625cc1b0219dada81f93343f5230ce3 | BellaShah/DataStructureProjects | /Graph.py | 13,780 | 3.546875 | 4 | # File: Graph.py
# Description: Creates a graph from an input
# Student's Name: Bella Shah
# Student's UT EID: BHS533
# Course Name: CS 313E
# Unique Number: 50945
# Date Created: May 5, 2016
# Date Last Modified: May 7, 2016
import copy
class Stack (object):
def __init__ (self):
... |
3fbc289b3063d64dfbf4d14ef4da9858d80d6eef | BellaShah/DataStructureProjects | /Eights.py | 6,602 | 3.765625 | 4 | # File: Eights.py
# Description: This program will simulate a game of Crazy Eights
# Student's Name: Bella Shah
# Student's UT EID: BHS533
# Course Name: CS 313E
# Unique Number: 50945
# Date Created: March 10, 2016
# Date Last Modified: March 11, 2016
import random
# Creates Class Car... |
6d093c59d9ded591b39f5432567762cec568c588 | physicsphoenix/SRproject | /SRbuildnumbers.py | 8,861 | 4.0625 | 4 | import math as m
import matplotlib.pyplot as plt
def not_a_num(number):
'''Will check to see if the value passed to the functions is a float or and int'''
if type(number)!=int and type(number)!=float:
return True
else:
return False
def check_given(R,c,v,n):
'''Will check to ... |
1d8c7579d5cbe63dfd5bd569f71cf0c7239a093e | sonalgupta06cs/Python_Projects | /PythonProjectBasics2/app.py | 855 | 4.375 | 4 | first = 'Sonal'
last = 'Gupta'
message = first + ' [' + last +'] is a coder'
# Formatted String, define your Formatted Strings, prefix with f'' then use curly braces to dynamically
# insert values into your strings.
msg = f"{first} [{last}] is a coder."
print(msg)
# len(), print() are a general purpose function in py... |
4013a80f5547d43bbe0e44ce1aa87f07128fd867 | millenagena/Python-Scripts | /aula010 - desafio028 sorteio de numeros.py | 456 | 3.984375 | 4 | from random import randint
print('----------------------------------------------------')
print('Vou pensar em um número de 0 a 5. Tente adivinhar...')
print('----------------------------------------------------')
num = randint(0, 5)
n = int(input('\nEm qual número eu pensei? '))
print('PROCESSANDO...')
if n == num:
... |
3ae4d4520c0178124924b5433a5b82de85ef4890 | millenagena/Python-Scripts | /expressoes regulares.py | 1,159 | 3.546875 | 4 | import re
import requests
stringteste = 'O gato é bonito'
padrao = re.search(r'gat\w', stringteste) # o search encontra somente uma vez o padrao desejado, nao percorrendo a string inteira
if padrao:
print(padrao.group()) # pra apresentar o padrao e nao o objeto
else:
print('Padrao nao encontrado')
# Regular express... |
a5061e303e7a55a85d945d84a850d58064145875 | millenagena/Python-Scripts | /aula018 - des088 palpites para a mega sena.py | 554 | 3.5625 | 4 | from random import randint
nsorteados = []
lista = []
num = qntd = cont = 0
j = 0
print('-='*30)
print(f'{"JOGO DA MEGA SENA":^60}')
print('-='*30)
qntd = int(input('Quantos jogos você deseja fazer? '))
print()
while j != qntd:
while cont < 6:
num = randint(0, 60)
if num not in nsorteados:
... |
22ae0326a6a021e9b8b4016b1c61b7e856c562cf | millenagena/Python-Scripts | /aula07 - desafio010 dolares.py | 213 | 3.828125 | 4 | r = float(input('Informe a quantidade, em reais, de dinheiro que possui: '))
d = float(input('Informe o atual valor do dólar: '))
qntd = float(r/d)
print(f'O valor de R${r} é equivalente a {qntd:.2f} dólares') |
5f1a97314267491e993cfa56178d1eda965d3015 | millenagena/Python-Scripts | /###COMANDOS AULA17.py | 1,575 | 4.15625 | 4 | num = [2, 5, 9, 1]
print(num)
num[2] = 3
print(f'Substituindo o terceiro elemento por 3 \n{num}')
num.append(7)
print(f'Adicionando o elemento 7 \n{num}')
num.sort()
print(f'Colocando em ordem crescente \n{num}')
num.sort(reverse=True)
print(f'Colocando em ordem decrescrente \n{num}')
print(f'Essa lista tem {len(n... |
c93827956a4e20965d26af798e95784d7ff0e672 | millenagena/Python-Scripts | /aula08 - desafio016 porção inteira.py | 287 | 4.125 | 4 | '''from math import trunc
num = float(input('Digite um valor: '))
numint = trunc(num)
print(f'O valor digitado foi {num} e sua porção inteira é {numint}')'''
num = float(input('Digite um valor:'))
numint = int(num)
print('A porção inteira do valor digitado é: {}'.format(numint)) |
3aaf90dcf903b99d7fded87d0ec76d87217195c8 | millenagena/Python-Scripts | /aula09 - desafio026 analisando string.py | 348 | 3.9375 | 4 | frase = str(input('Digite uma frase que contenha letras "a": ')).strip()
frasemi = frase.lower()
print('Quantas vezes aparece a letra "a"? {}'.format(frasemi.count('a')))
print('Em que posição a letra "a" aparece primeiro? {}'.format(frasemi.find('a')+1))
print('Em que posição a letra "a" aparece por último? {}'.format... |
4f99e544a4b30595a5b92df06f752f4059fa38ea | millenagena/Python-Scripts | /aula09 - desafio023 dezena, centena, milhar.py | 234 | 4.03125 | 4 | num = int(input('Informe um número: '))
u = num//1 % 10
d = num//10 % 10
c = num//100 % 10
m = num//1000 % 10
print('Analisando seu número: ')
print(f'Unidade: {u}')
print(f'Dezena: {d}')
print(f'Centena: {c}')
print(f'Milhar:{m}')
|
dcf0c8306e081425428538089a3bea9421fac6f5 | millenagena/Python-Scripts | /aula010 - desafio029 multa.py | 283 | 3.859375 | 4 | vel = int(input('Informe a velocidade do carro em km/h: '))
if vel>80:
multa = (vel-80)*7
print('\nESTÁ MULTADO POR EXCESSO DE VELOCIDADE!!\n')
print(f'Sua multa é correpondente ao valor de R${multa}')
print('\nDirija com segurança e consciência!\nTenha um bom dia.') |
486f9dad804e0ade0ade299d0ece1f6567da0de7 | millenagena/Python-Scripts | /aula012 - desafio038 numero de 2 digitos.py | 246 | 4.0625 | 4 | num = str(input('Informe um número inteiro de dois dígitos: '))
if num[0]>num[1]:
print('O primeiro dígito é maior!')
elif num[0]==num[1]:
print('O primeiro dígito é igual ao segundo!')
else:
print('O segundo dígito é maior!') |
b316af9657983fef24ca38c65e102e142a8bc7ea | millenagena/Python-Scripts | /aula015 - desafio069 analise dados do grupo.py | 815 | 3.6875 | 4 | idade = m18 = mm20 = h = m = 0
sexo = rsp = ' '
while True:
print('-='*15)
print('Cadastre uma pessoa')
print('-='*15)
idade = int(input('Idade: '))
if idade > 18:
m18 += 1
while sexo not in 'MF':
sexo = str(input('Sexo[M/F]: ')).strip().upper()
... |
83db30a8974555ec9cd7be415d3c39cedf1a3e4b | sararuiz97/DataBaseProject | /graph.py | 805 | 3.578125 | 4 | from collections import deque
class Node(object):
"""docstring for Node."""
def __init__(self, name):
self.name = name
self.adj = {}
self.incAdj = {}
self.numC = 0
self.rank = 0.0
def insertAdj(self, node, weight):
self.adj[node.name] = [weight, node]
... |
626d013cb58ef41849714ce774edaccd627bc0c8 | mwxxt/labs_python | /Lab #8/4.py | 406 | 3.796875 | 4 | import datetime
b=int(input("\nВведите год: "))
t=int(input("Введите месяц: "))
a=int(input("Введите день: "))
d = datetime.date(b, t, a)
print("\nВведённая дата:")
print("Год",b,"Месяц",t,"День",a)
print("\nОтвет после определённых вычислений:")
print("Год",d.year+1,"Месяц",d.month-1,"День",d.day,"\n") |
8a17f3fd9975a40a98b242229c2a9afd2a34e0b4 | mwxxt/labs_python | /Lab #3/2.py | 1,477 | 4.09375 | 4 | def func(x):
if x<1 or x>9:
print("\nНеверный ввод!\n")
return x
x = int(input("\nВведите число от 1 до 9: "))
print("\nВведено число:",x)
func(x)
if x<=3 and x>=1:
s=input("\nВведите строку: ")
n=int(input("\nВведите число повторов строки: "))
print("\nЧисло повторов для строки:",n,"\n... |
7ec7941bc02a9c5025d58e9a3398b181cef4428c | mwxxt/labs_python | /Lab #3/3.py | 409 | 3.734375 | 4 | words = input("\nВведите строку: ")
words = words.replace(',', '').replace('.', '').replace('...', '').replace(':', '').replace('!', '').replace('?', '').replace(';', '').replace('-', '').replace(')', '').replace('(', '').replace('"', '')
words = words.split()
letter_counts = list(map(lambda x: len(x), words))
prin... |
d60731af78135f76b482cfeb0ed7045a0f1baddc | leandroaa7/selenium | /sdet-selenium-with-python/condicionalcommands.py | 1,461 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# Vídeo 5/45 Selenium with Python Tutorial 5-WebDriver Conditional Commands
'''
Agenda
Condicional Commands
-is_displayed()
-is_enabled()
-is_selected()
caso não apareça os atributos das classes no VSCode basta clicar ctrl + shift + p
e digigar python interpreter para selecionar o interpretad... |
4b017347aa313cd38c727593fcc6aba6754aabd5 | nguyenkimthanh1410/EnhancedKMeans | /kdd_kmean_enhanced/app/validate_input.py | 947 | 4.15625 | 4 | # Purpose: Validate user input in console window
# Validate input as integer within [start, end] inclusive
def validate_int_in_range_inc(start,end,message):
input_str = input(message) # check input validation later
input_int = validate_int(input_str,message)
# Check value in range (1, num_records) inclus... |
e523bce7547d9ba7223e6ca3f3db3120dafa15ca | EliGluch/sample | /firstfew.py | 874 | 3.703125 | 4 | def half_range(n):
return map(lambda x: x / 2.0, range(2 * n + 1))
# print(half_range(5))
def intersection(listA, listB):
return list(set([item for item in listA if item in listB]))
# a = [1,2,3,3]
# b = [1,3,2,2,5]
# print(intersection(a,b))
def char_set(my_string):
return set([char for char in my_st... |
e728a2650d3078a7f5ecedde2962391884f56f02 | BlackstarDamien/My-Scripts | /next_bigger_num.py | 514 | 3.875 | 4 | """
function that takes a positive integer number and returns the next bigger number formed by the same digits
"""
def next_bigger(n):
s = list(str(n))
for i in reversed(range(1, len(s))):
if s[i] > s[i - 1]:
pos = i - 1
for j in reversed(range(pos + 1, len(s))):
... |
2133890102e79a9d79f855903902e8015a3e90ee | BlackstarDamien/My-Scripts | /detect_pangram.py | 228 | 3.828125 | 4 | """
Function, which detecting pangrams
"""
import string
def is_pangram(s):
alphabet = "abcdefghijklmnopqrstuvwxyz"
return not (set(alphabet) - set(''.join(s.translate(str.maketrans("!?,.:", 5*' ')).split()).lower()))
|
9dbdf2d4a047be165449cee86aca915513feca13 | cheyra90/CodeKatas | /recreational_ints.py | 891 | 4.09375 | 4 | import math
from unittest import TestCase
"""
given a range of numbers, calculate any instances where the squares of the divisors of any numbers within the list sums to a square number
eg => 42: Divsors: 1,2,3,6,7,14,21,42
Divosors Squared: 1,4,9,36,49,196,441,1764
sum(): 2500 => (sqrt(50))
"""
def ... |
8677be45e08dae5cc34797f5f3334c0e3b75c0df | cheyra90/CodeKatas | /replace_with_alphabet_position.py | 319 | 4.1875 | 4 | '''
given a string, replace every letter with its position in the alphabet eg
The => '20 8 5'
'''
test_string = "The sunset sets at twelve o' clock."
def alphabet_position(text):
l = [ord(l.lower())-96 for l in text if l.isalpha()]
return ' '.join(map(str, l))
l = alphabet_position(test_string)
print(l) |
9e9f98cfc2900a718c46ab521e826a7c55a2574c | ElenaBarvinskaya/Python_Lessons | /lesson2/b.py | 2,564 | 4.21875 | 4 | # Часть 1
print("Пожалуйста, введите ваше имя")
firstName = input()
print("Пожалуйста, введите вашу фамилию")
secondName = input()
print("Пожалуйста, введите ваш возраст")
age = int(input())
print("Пожалуйста, введите ваш адрес")
adress = input()
print("Пожалуйста, введите ваш телефон!")
phone = input()
print("Ваши дан... |
67e95967c31f17ef2749f7d92fa026d4c8462b3f | gkl1107/Python-algorithm | /is_palindrome.py | 1,128 | 4.21875 | 4 | '''
Write a function that takes a string as a parameter and returns True if the string is a palindrome, False otherwise.
Remember that a string is a palindrome if it is spelled the same both forward and backward.
for example: radar is a palindrome.
for bonus points palindromes can also be phrases, but you need to re... |
ed9ed9f80796fa62a91a6f5d38793b8766dca9c2 | gkl1107/Python-algorithm | /plot_regression.py | 2,038 | 4.09375 | 4 | '''
Write a function called plotRegression that reads the data from this file and
uses a turtle to plot those points and a best fit line according to the following formulas:
y=y¯+m(x−x¯)
m=∑xiyi−nx¯y¯∑x2i−nx¯2
where x¯
is the mean of the x-values, y¯
is the mean of the y- values and n
is the number of points. If yo... |
a54e2411e8811c8ad8ee4c5a2a116c3e0d80e50f | gkl1107/Python-algorithm | /count_alpha.py | 819 | 4.09375 | 4 | #!/usr/bin/python
'''
Write a program that allows the user to enter a string.
It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs.
Case should be ignored.
'''
sent = raw_input("Please enter a sentence:")
#sent = s... |
759ebb5ee1fa73ff450ea3a2eb40610d34e331d3 | gkl1107/Python-algorithm | /fill_water.py | 1,347 | 4.125 | 4 |
def get_water(jug1size,jug2size,targetIn1):
# set initial state for the big jug and the small jug,
# in default considering jug1size as the bigger and jug2size as the smaller
jugBig = 0
jugSmall = jug2size
print("Start: big jug: {}, small jug: {}".format(jugBig,jugSmall))
# keep pouring small-jug size o... |
37223f6250fa24c775aec10dc75c79f0efe83173 | 1000scores/ML_GAME | /KEK/interface.py | 10,633 | 3.5 | 4 | """
Sprite with Moving Platforms
Load a map stored in csv format, as exported by the program 'Tiled.'
Artwork from http://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_moving_platforms
"""
import arcade
import os
import random
impor... |
ace0fa6f1d050009f2160b406e7d7b9aaa6de8c0 | EtienneJanel/scramble-solver | /define_tile.py | 1,054 | 3.890625 | 4 | class Tile:
def __init__(self, name, north, east, south, west):
"""defines the image with cardinal points 🧭
north = up, clockwise
name: STR
north, south...: INT (from -4 to +4)
positive numbers for 'heads'
negative for 'tails' of the image
... |
43a39bd0b6df5af96be077dd43ec088f4e5ee37f | kxkangxi/kpath | /kpath.py | 3,102 | 3.578125 | 4 | # Algorithm to calculate K-shortest paths
import networkx as nx
def find_next_hops_to_remove(existing_paths, root_path):
"""
compare each existing path with the root path, if overlapped, the next hop node is returned
:param existing_paths: [path1, path2, ...]
:param root_path: a root path
:return:... |
c641bf180ee249151cc3d6f7560fb9e402c3defe | bagusdharma/testing | /for.py | 857 | 4.34375 | 4 | # A simple dictionary
d = {"foo" : "bar"}
for key in d:
print d[key] # prints "bar"
once = {'a': 1, 'b': 2}
twice = {'a': 2, 'b': 4}
for key in once:
print "Once: %s" % once[key]
print "Twice: %s" % twice[key]
# Ex:
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana... |
40381ed0ae150f60456fae335d76ea92017a86ef | thommms/Spark-Programming | /counting_in_Spark.py | 1,429 | 4.15625 | 4 | from pyspark.sql import SparkSession
#after importing the spark session, lets create our spark program
spark = SparkSession.builder.appName("Spark Assignment question3").getOrCreate()
#import the data set and set header to be true to properly format the column names
df = spark.read.csv('/user/common_data/Spark_Assi... |
ea43c9d7429fd698590c953cc8531c5e1006a3bc | yarosmar/beetroot-test-repo | /lesson_11/custom_exception.py | 640 | 3.625 | 4 | import time
import logging
logging.basicConfig(filename='log.log',
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s % (message)s')
logger=logging.getLogger(__name__)
class NumberNotInRangeError(Exception):
def __init__(self, number):
self.message = "... |
3744894dcb1e0b1d3a607bba28d8bb1b3013d0f1 | yarosmar/beetroot-test-repo | /lesson_16/task_1.py | 601 | 3.6875 | 4 | def my_enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
def my_enumerate1(sequence, start=0):
for i in range(len(sequence)):
yield start + i, sequence[i]
def my_enumerate2(sequence, start=0):
return [(start + i, sequence[i]) for i in range(le... |
6392f57d9ea7cbcf4eb7ee6d5b48c34b558186f7 | yarosmar/beetroot-test-repo | /lesson_8.py | 786 | 3.84375 | 4 | def ooops():
'''IndexError_exception'''
a = ['o', 'o', 'o', 'p', 's']
s = 0
for i in a: # ітерація по списку a
s = s + 1
print(a)
print('Sum =', s)
n = input('Enter index: ')
n = int(n)
try:
print(a[n])
except IndexError:
print('o-o-o-p-s')
print('Try again.')
def division():
'''atemp... |
e4a405eebe15f1eb5ee9c4e0924114f7144d0600 | hyoretsu/uri-online-judge | /python/beginner/1002.py | 99 | 3.859375 | 4 | pi = 3.14159
radius = float(input())
circleArea = pi * (radius ** 2)
print(f"A={circleArea:.4f}")
|
723ed4f53c472462d96137458293304b87f6d668 | hyoretsu/uri-online-judge | /python/beginner/1017.py | 120 | 3.65625 | 4 | timeSpent = int(input())
averageSpeed = int(input())
distance = averageSpeed * timeSpent
print(f"{distance / 12:.3f}")
|
4da349a0b5b501943c2908f90f9066942faac664 | hyoretsu/uri-online-judge | /python/beginner/1043.py | 176 | 3.546875 | 4 | [a, b, c] = map(float, input().split())
if a < b + c and b < a + c and c < a + b:
print(f"Perimetro = {a + b + c:.1f}")
else:
print(f"Area = {((a + b) / 2) * c:.1f}")
|
fee8af01236774f4a416e62820ad19b3fa7425f7 | developer579/Practice | /Python/Python Lesson/First/Lesson7/Lesson7.py | 613 | 4 | 4 | def rpast(num):
print("*" * num)
n = int(input("個数を入力してください。"))
rpast(n)
def rpstr(num,str="*"):
print(num*str)
n = input("文字列を入力してください。")
s = int(input("個数を入力してください。"))
print("文字列あり---")
rpstr(n,s)
print("文字列なし---")
rpstr(s)
def makex(x):
while True:
yield x
x = x+1
start = int(inpu... |
b78c99e561f241dc1db7b4718981093bd0c43067 | developer579/Practice | /Python/Python Lesson/First/All/Sample1.py | 616 | 3.90625 | 4 | #画面に出力する
print("ようこそpythonへ!")
print("Pythonをはじめましょう!")
sale=10
print("売上は",sale,"万円です。")
sale = int(input("売上を入力してください。"))
if sale >= 100 :
print("売上は好調です。")
if sale <= 100 :
print("売上は不調です。")
print("処理を終了します。")
sale=[80,60,22,50,75]
print(sale)
sale = {"東京":80,"名古屋":60,"京都":22,"大阪":50,"福岡":75}
print("現在のデータは",s... |
5a6415e47baed035154faed9cf0c52a9979a8c88 | developer579/Practice | /Python/Python Lesson/First/Lesson11/Sample4.py | 171 | 3.5625 | 4 | import sqlite3
conn = sqlite3.connect("pdb.db")
c = conn.cursor()
itr = c.execute("SELECT*FROM product WHERE name LIKE '%ン%'")
for row in itr:
print(row)
c.close() |
95596f557912c48d4979c564dbee3a0215b335fb | developer579/Practice | /Python/Python Lesson/First/All/Sample16.py | 356 | 3.75 | 4 | data=[
["東京",32,25],
["名古屋",28,21],
["大阪",27,20],
["京都",26,19],
["福岡",27,22]
]
print("現在のデータは",data,"です。")
for dat in data:
print("都市別データは",dat,"です。")
for d in dat:
print(d,end="\t")
print()
print(data[0][0],"の最高気温は",data[0][1],"最低気温は",data[0][2],"です。") |
b087997783a4b542adbdb0d5eebcbcc3a860f102 | developer579/Practice | /Python/Python Lesson/First/Lesson5/Lesson5.py | 782 | 3.546875 | 4 | test = [74,85,69,77,81]
ave = sum(test)/len(test)
print("テストの点は",test,"です。")
print("最高点は",max(test),"です。")
print("最低点は",min(test),"です。")
print("平均点は",ave,"です。")
print("テストの点は",test,"です。")
print("テストの点は",sorted(test),"です。")
print("テストの点は",sorted(test,reverse=True),"です。")
print("テストの点は",test,"です。")
high = [n for n in t... |
8f8a8a22c79aee3c81b2d9fd171eaff5a31c0b0b | developer579/Practice | /Python/Python Lesson/First/Lesson4/Lesson4.py | 470 | 3.78125 | 4 | print("1から10までの偶数を表示します。")
for i in range(1,11):
if i%2 == 0:
print(i)
print("1から10までの偶数を表示します。")
for i in range(2,11,2):
print(i)
print("九九の表を表示します。")
for i in range(1,10):
for n in range(1,10):
print(i*n,"\t",end="")
print()
print("*のコードを出力します。")
for i in range(1,6):
for j ... |
f95e72087ae62f10236aa339655340deb3b4250b | developer579/Practice | /Python/Python Lesson/First/Lesson11/Sample1.py | 555 | 3.796875 | 4 | import sqlite3
conn = sqlite3.connect("pdb.db")
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS product")
c.execute("CREATE TABLE product(name CHAR(20),price INT)")
c.execute("INSERT INTO product VALUES('鉛筆',80)")
c.execute("INSERT INTO product VALUES('消しゴム',50)")
c.execute("INSERT INTO product VALUES('定規',200)")
c... |
60ca2b8990bbded0493071560ad9d60a5a5f5807 | developer579/Practice | /Python/Python Lesson/First/All/Sample4.py | 1,342 | 3.671875 | 4 | print("水平タブを表示します。:\t")
print("垂直タブを表示します。:\v")
print("改行を表示します。:\n")
print("復帰を表示します。:\r")
print("警告音を表示します。:\a")
print("バックスペースを表示します。:\b")
print("改ページを表示します。:\f")
print("\'を表示します。:\'")
print("\"を表示します。:\"")
print("\345を表示します。:\345")
print("\xFFを表示します。:\xFF")
print("1+2は",1+2,"です。")
for i in range(1,13,1):
print(... |
833358c6bb8c1c7ff5dcd1a4024ca602a5b95006 | developer579/Practice | /Python/Python Lesson/First/Lesson5/Sample15.py | 561 | 3.875 | 4 | sale = [80,60,22,50,75]
print("現在のデータは",sale,"です。")
print("最大のデータは",max(sale),"です。")
print("最小のデータは",min(sale),"です。")
print("データの合計は",sum(sale),"です。")
print("昇順でソートされたデータは",sorted(sale),"です。")
print("降順でソートされたデータは",sorted(sale,reverse=True))
sale.sort(reverse=False)
print("sale.sort(reverse=False)で表示します。")
print(sale)
... |
bd8751885b142f26fbe04ca0db09895336c15bf8 | developer579/Practice | /Python/Python Lesson/Second/Lesson9/Lesson9.py | 406 | 3.875 | 4 | list = ["Sample.csv","Sample.exe","Sample1.py","Sample2.py","Sample.txt","index.html"]
file = []
print("ファイルのリストは以下です。")
for i in list:
print(i)
key = input("拡張子を入力してください。")
for i in list:
res = i.endswith(key)
if res is True:
file.append(i)
print("該当するファイルのリストは以下です。")
for i in file:
print(i) |
53bf044549f39fe732cfe9069930191a89a02c14 | developer579/Practice | /Python/Python Lesson/First/All/Lesson4.py | 497 | 3.8125 | 4 | print("1から10までの偶数を表示します。")
for i in range(10):
if (i+1) % 2 == 0:
print(i+1)
print()
print("1から10までの偶数を表示します。")
for i in range(2,11,2):
print(i)
print()
print("九九の表を表示します。")
for i in range(1,10):
for j in range(1,10):
print(i*j,"\t",end = " ")
print()
print("画面にコードを出力します。")
for i in ran... |
776300fbfbacb913799d918f12bde047e1adda37 | djs21905/Web-Scraping | /Chime_script.py | 964 | 3.578125 | 4 | import requests
from bs4 import BeautifulSoup
# User input for artist name/ song name
search_query = input("Enter search query: ")
# Creates an http req and retrieves the url based on the artist/ song name
r = requests.get("https://www.youtube.com/results?search_query=" + search_query)
# Converts the html request ob... |
138c6528c370f6d8f84b68b48388711b05556c5a | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex058.py | 640 | 3.8125 | 4 | from time import sleep
from random import randint
computador = randint(0, 10)
soma = 0
print('''Sou seu computador ....
Acabei de pensar em um número entre 0 e 10.
Será que você consegue adivinhar qual foi ?''')
sleep(2)
palpite = int(input('Qual é o seu palpite ? '))
while palpite != computador:
soma = soma + 1
... |
4772304ba7290855be34b26b9803f13b4cddad3d | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex079.py | 912 | 4.09375 | 4 | numeros = list()
while True:
n = int(input('Digite um valor: '))
if n not in numeros:
numeros.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado, não vou adicionar...')
resposta = input('Quer continuar ? [S/N] ')
if resposta in 'Nn':
break... |
b61734dc9f6ce3e7275db29b80e7924f46670d95 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex078.py | 1,302 | 3.78125 | 4 | lista = []
maior = menor = 0
for c in range(0, 5):
lista.append(int(input(f'Digite um valor para a posição {c}: ')))
if c == 0:
maior = menor = lista[c]
else:
if lista[c] > maior:
maior = lista[c]
if lista[c] < menor:
menor = lista[c]
print('Você digitou os va... |
d5e321117c5fb68255620a63e602f7e00baf082d | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex008.py | 282 | 4.0625 | 4 | x = int(input('Digite uma distância em metros: '))
km = x * 0.001
hm = x * 0.01
dam = x * 0.1
dm = x * 10
cm = x * 100
mm = x * 1000
print('A medida de {} metros corresponde a '.format(x))
print(km,'km')
print(hm,'hm')
print(dam,'dam')
print(dm,'dm')
print(cm,'cm')
print(mm,'mm')
|
51e2ec4d99b635aabfed305ec64c00b4c719ef13 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex090.py | 371 | 3.828125 | 4 | aluno = {}
aluno['Nome'] = input('Nome: ')
aluno['Media'] = float(input('Média de {}: '.format(aluno['Nome'])))
if aluno['Media'] < 6:
situacao = 'Reprovado'
elif aluno['Media'] >= 7:
situacao = 'Aprovado'
else:
situacao = 'Recuperação'
aluno['Situacao'] = situacao
print('-=' * 30)
for k, v in aluno.items()... |
1ed35c749c457e17ce997314f69c044eba1abf5d | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex052.py | 595 | 3.859375 | 4 | n = int(input('Digite um número: '))
if n == 1 or n == 0:
print('Não é primo')
elif n == 2:
print('É primo')
else:
for i in range(2, n + 1):
if n % i == 0:
print('Não é primo')
break
else:
print('É primo')
break
... |
291d720a86d205f7531210a0cd6f2e5c0d1da413 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex075.py | 465 | 3.984375 | 4 | num = (int(input('Digite um valor: ')),
int(input('Digite outro valor: ')),
int(input('Digite outro valor: ')),
int(input('Digite outro valor: ')))
print('O número 9 apareceu {} vezes'.format(num.count(9)))
if 3 in num:
print('O valor 3 apareceu na posição {}'.format(num.index(3) + 1))
else:
... |
56877948b90afe71780e616b6b42faa809bb3de3 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex054.py | 421 | 3.78125 | 4 | from datetime import date
hoje = date.today().year
count1 = 0
count2 = 0
for i in range(1, 8):
ano = int(input('Em que ano a {} pessoa nasceu ? '.format(i)))
idade = hoje - ano
if idade < 18:
count1 = count1 + 1
else:
count2 = count2 + 1
print('')
print('Ao todos tivemos {} pessoas maior... |
f466e1192a59e74e38ba3879b13f2f7b88891ba6 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex005.py | 149 | 3.96875 | 4 | x = int(input('Digite um número :'))
y = x - 1
z = x + 1
print('Analisando o valor {}, seu antecessor é {} e seu sucessor é {}'.format(x, y, z ))
|
af8233161080a361bf443aae0560c821b7b66259 | ClaudioSiqueira/Exercicios-Python | /Exercicios Python/ex064.py | 214 | 3.828125 | 4 | n = 0
cont = 0
soma = 0
while n!= 999:
n = int(input('Digite um número (999 para parar): '))
cont = cont + 1
soma = soma + n
print(f'Você digitou {cont-1} números e a soma entre eles é {soma-999}')
|
8b252a0a235157a98e7b18ac690527cd74824cc9 | ceharrin/legendary-octo-giggle | /src/main.py | 2,790 | 4 | 4 | import random
import src.BinManager as BinManager
# Some constants and default values
min_int = 20001
max_int = 380000
bin_size = 36000
range_size = 1000
num_bins = 10
# Main entry point. Prompt for user input and then create the bins based on the provided input.
# Generate the random numbers and bin them.
# Output... |
da4dcba8b06288a0fccbbe620ec1f831946a588d | marciobbj/data-structures-and-algos | /stacks_and_queues/queue.py | 1,016 | 3.921875 | 4 | """
Queues sao consideradas estruturas lineares FIFO (First In First Out). E.g. [1, 2, 3].remove() -> [2, 3]
"""
from stacks_and_queues import LinearDataStructure, Node
class Queue(LinearDataStructure):
def peek(self):
return self.head.data
def add(self, data):
node = Node(data)
if ... |
3a0c332ef4eb62cfc2a6a529cae9f28acdcb1711 | espinosakev24/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/3-print_alphabt.py | 158 | 3.5 | 4 | #!/usr/bin/python3
for n in range(0x61, 123):
if n == 0x71:
continue
elif n == 101:
continue
print('{:s}'.format(chr(n)), end="")
|
03559196ca51e00a06618489f34d111e55d0b6b3 | espinosakev24/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 184 | 3.6875 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
def sq(num):
return num * num
new = []
for a in matrix:
new.append(list(map(sq, a)))
return new
|
53d9404a2a43affc38ae07c24edbc62b66507989 | espinosakev24/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 521 | 4.03125 | 4 | #!/usr/bin/python3
"""
Module with add_integer function
Function that adds two numbers
This module only has one function
"""
def add_integer(a, b=98):
"""
add_integer
"""
if type(a) is not int and type(a) is not float:
raise TypeError('a must be an integer')
if type(b) is not i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.