blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
74aa9d80f83e0e05353bdf4270f33daac1ac883d | lorenanicole/interviewprep | /data_structures.py | 2,548 | 4.21875 | 4 | '''
Trees:
- Have a node ('key'), may have additional info ('payload')
- Edge - connects two nodes to show there's a relationship
- All nodes (minus root) connected by one incoming edge from another node
- Nodes have have 1+ outgoing edges
- Root has no incoming edges; root of the tree
- Path is the ordered list of n... |
23e0065c2cf78db0542bd8e1d5f879b6b942d647 | Tr3v1n4t0r/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,812 | 3.96875 | 4 | #!/usr/bin/python3
"""
Define a Square class
"""
from models.base import Base
from models.rectangle import Rectangle
class Square(Rectangle):
"""Defines class Square"""
def __init__(self, size, x=0, y=0, id=None):
"""Initializes Square instance"""
super().__init__(size, size, x, y, id)
d... |
a42bfe4fecd90232b9c4584d32348e17f3470af6 | gustavohsr/python | /sem3/sem3-exe4.py | 117 | 4.03125 | 4 | num = input("Informe o numero: ")
if int(num)%3 == 0 and int(num)%5 == 0:
print("FizzBuzz")
else:
print(num)
|
fb0ebe4c261f80fc64af7f651eac662f89a33047 | gustavohsr/python | /sem3/sem3-exe2.py | 93 | 4.03125 | 4 | num = input("Informe o numero: ")
if int(num)%3 == 0:
print("Fizz")
else:
print(num)
|
0131cab8dc79656f0d3f0ec383755c26e4143306 | nuga99/daily-coding-problem | /Problem 15/solve.py | 1,259 | 4.125 | 4 | #!/usr/bin/python
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a stream of elements too large to store in memory,
pick a random element from the stream with uniform probability.
Upgrade to premium and get in-depth solutions to every problem.
Since you... |
36fa31cd30693b2b450b8910601a58d0e7f4fcb0 | nuga99/daily-coding-problem | /Problem 13/solve.py | 780 | 3.9375 | 4 | #!/usr/bin/python
'''
Problems #13
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring ... |
381d1e7ba28e582af8957e13145ff3d2405f953c | Sowjanya-0/DataStructuresUsingPython | /Experiment13/Stack.py | 955 | 4.03125 | 4 | #Initial Stack
stack = ['x','y','z']
# Stack Insertion
def push(item):
stack.append(item)
# Stack Display
def display():
print(stack)
#Stack Deletion
def pop():
print(stack.pop())
#Stack Searching Operation
def search(key):
flag =0
for i in range (0,len(stack)) :
... |
727a0e8e653e3f158cc065a400a54cfbcf17d38c | gafajardogr/CursoLeonEoiPythonDjango | /python/10_funciones.py | 371 | 4.03125 | 4 | """
Ejemplos de funciones simples
"""
def hi():
print('hola')
hi()
def hi_to(name):
print('Hi', name)
hi_to('Ramón')
def add_name(name_list, name):
name_list.append(name)
print(name_list)
l = ['Patricia', 'Maria']
add_name(l, 'Carlota')
# modificar argumento dentro de la función
def talk(word):
... |
a7cac4e50b02e6cebdf951c6a3d620c49862347d | Annihilation7/Ds-and-Al | /src/leetcode/1-99/05.py | 1,282 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2019-12-08 11:28am
'''
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
'''
class Solution:
def longestPalindrome(self, s: str) -> str:
'''
采用中心扩展算法来解决本题
注... |
3dff92c807bcea914a74b567fbfe3e1a03220d11 | Annihilation7/Ds-and-Al | /src/leetcode/1-99/37.py | 751 | 3.75 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2019-12-18 10:46pm
'''
编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 '.' 表示。
Note:
给定的数独序列只包含数字 1-9 和字符 '.' 。
你可以假设给定的数独只有唯一解。
给定数独永远是 9x9 形式的。
'''
from typing import List
class Solu... |
5e3c8dd0ac72e227f6ac0c383f2d5854b68be4ea | Annihilation7/Ds-and-Al | /src/leetcode/1-99/26.py | 2,303 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2019-12-15 09:36pm
'''
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新... |
62b7dbaddd923d73fe7f139a4b5189da6c7e1dd7 | Annihilation7/Ds-and-Al | /src/ds/bst.py | 7,284 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2019-12-07 01:51pm
from src.ds.loop_queue import LoopQueue
from src.ds.array_stack import ArrayStack
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(s... |
bbc69c43fa1593075e297dda4d525e8b3a090597 | Annihilation7/Ds-and-Al | /src/leetcode/1-99/07.py | 957 | 3.75 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2019-12-08 12:11pm
'''
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。
请根据这个假设,如果反转后整数溢出那么就返回 0。
'''
class Solution:
def reverse(self, x... |
4210e456917369e9fc3e932f983f5f761ef43f1b | Annihilation7/Ds-and-Al | /src/al/sorts.py | 5,834 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# Email: 763366463@qq.com
# Created: 2020-01-26 12:03am
import random
class SortsFactory:
@classmethod
def bubble_sort(cls, alist):
"""
冒泡排序 —— O(N ^ 2)
"""
# 不用到0,因为倒数第二次换完最后一个一定是最小的了
for i in range(len(alist) - 1, 0, -1):
for... |
a89cbf2aa71bf821028bf411b13e61b449b8ab76 | PininQ/pythonCode | /producer_consumer/prodcons_thead.py | 1,367 | 3.953125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'QB'
from queue import Queue
import random, threading, time
'''
多对多的生产者消费者 Demo
'''
# 生产者类
class Producer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self, name=name)
self.data = queue
def run(self):
for i in range... |
d05d2c767852aaa4fd623672ebbc8443d3f93fe2 | ddh/rosalind | /ini4.py | 194 | 3.546875 | 4 | # Conditions and Loops
# Given: Two positive integers a and b (a<b<10000).
# Return: The sum of all odd integers from a through b, inclusively.
# 4543 9334
print(sum(list(range(4543,9335,2)))) |
e8e2c69b9746a22f57e9995d337e095ad6adb07b | Lilsnot/cti110 | /P2HW2_MealTip_AaronDeason.py | 875 | 3.953125 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # a program that calculates the total amount of a meal purchased at a restaurant.The program will ask the user to enter the charge for food and calc... |
c3693e2ad2df8eaa381bb3ead5305d26e9156d3b | LeKhan9/WebDev | /PythonGeneratedHTML/generateHtml.py | 5,660 | 3.546875 | 4 |
#----------------------------------------------------------------------------------
# Mohammad Khan contribution | Isaiah Snelling contribution
# Khan rate: 93% | 93%
# Snelling rate: 93% | 93%
#
# -- Web Technologies and Mobile ... |
aebf6546ab4d2d9bd1b83cbe781d427c4a7be396 | flavianmissi/random-stuff | /algebra/cryptography/caesar_cipher/caesar_cipher.py | 818 | 3.734375 | 4 | import string
from code_helper import CodeHelper
class CaesarCipher(object):
def __init__(self, key=3):
self.key = key
self.letters = list(string.ascii_lowercase) # a to z
self.helper = CodeHelper()
def encrypt(self, msg):
code = self.helper.to_code(msg)
encrypted = []
... |
b9b901b6fafb8366674cfb65c6052719a31f1b88 | KistVictor/exercicios | /exercicios de python/Mundo Python/060.py | 244 | 3.890625 | 4 | calculo = 1
fatorial = int(input('Digite um número para calcular o fatorial: '))
fat = fatorial
while True:
print (f'{fat} x ', end='')
calculo = calculo * fat
fat -= 1
if fat == 1:
print(f'1 = {calculo}')
break |
488f5033cd4ffd325c59667fef5350594dbe0c71 | KistVictor/exercicios | /exercicios de python/Mundo Python/052.py | 254 | 3.984375 | 4 | n = int(input('Digite um número: '))
tot = 0
for i in range(1, n+1):
print(i, end=' ')
if n % i == 0:
tot += 1
print('\nO número {} foi dividido {} vezes'.format(n, tot), end='')
if tot == 2:
print(', portanto é um número PRIMO')
|
3543c0d0b1be371f9ab0fbf5c19f62e04c7e258c | KistVictor/exercicios | /exercicios de python/Att Estrutura de Dados.py | 5,913 | 4.09375 | 4 | # Define tamanho da lista
tamanhoLista = 4
# Define class Pessoa com nome e matricula
class Pessoa:
nome = ''
matricula = 0
# Define class Lista com uma lista da class pessoas e o número de elementos dentro dela
class Lista:
alunos = [Pessoa()] * tamanhoLista
numeroElementos = 0
# Função para cria... |
95ef0875b056890656869d66231f7b229947fc68 | KistVictor/exercicios | /exercicios de python/Mundo Python/040.py | 256 | 3.734375 | 4 | n1 = float(input('Digite a sua primeira nota: '))
n2 = float(input('Digite a sua segunda nota: '))
m = (n1+n2)/2
if m >= 7:
print('\033[1;32m-APROVADO-')
elif 5 <= m < 7:
print('\033[1;33m-RECUPERAÇÃO-')
else:
print(('\033[1;31m-REPROVADO-')) |
acb31696373c750ff08124a28d22d82c86a5fde1 | KistVictor/exercicios | /exercicios de python/Mundo Python/020.py | 309 | 3.6875 | 4 | from random import shuffle
a1 = input('digite o nome do primeiro aluno: ')
a2 = input('digite o nome do segundo aluno: ')
a3 = input('Digite o nome do terceiro aluno: ')
a4 = input('digite o nome do quarto aluno: ')
list = [a1, a2, a3, a4]
shuffle(list)
print('a ordem de apresentação é: {}'.format(list))
|
30ebf5592ee35a0b5f9fe1fd6893096399d98ee8 | KistVictor/exercicios | /exercicios de python/Mundo Python/035.py | 309 | 3.96875 | 4 | r1 = int(input('Digite o valor da primeira reta: '))
r2 = int(input('Digite o valor da segunda reta: '))
r3 = int(input('Digite o valor da terceira reta: '))
if r1 + r2 > r3 and r2 + r3 > r1 and r1 + r3 > r2:
print('Um triângulo pode ser formado!')
else:
print('Um triângulo não pode ser formado')
|
5ed80a9c3ca0f89fdd2515ba6f0faf7a825a33e6 | vitaliytsoy/problem_solving | /python/medium/count_primes.py | 1,245 | 4.09375 | 4 | """
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
"""
import math
class Solution:
# def is_... |
cb1b4688de0db70a3e64e8a144c80f5ad3522558 | vitaliytsoy/problem_solving | /python/medium/map_sum_pairs.py | 2,596 | 4.09375 | 4 | """
Design a map that allows you to do the following:
Maps a string key to a given value.
Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the MapSum class:
MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into the map. If ... |
c207569b97b4a49b45d291a58abca91c0f67699a | vitaliytsoy/problem_solving | /python/medium/two_keys_keyboard.py | 960 | 4.28125 | 4 | """
There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given an integer n, retur... |
a22ee89a6995f91f768bb5116b635ba90c061510 | vitaliytsoy/problem_solving | /python/medium/range_sum_query_2d.py | 2,799 | 3.9375 | 4 | from typing import List
class NumMatrix:
"""
Given a 2D matrix matrix, handle multiple queries of the following type:
Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Implement the NumMatrix class:
... |
696046526ff807925438451c02caf94cf921fa2c | vitaliytsoy/problem_solving | /python/easy/is_palindrome.py | 357 | 3.6875 | 4 | import re
import re
def main(s: str):
filtered = re.sub(r"[\W_]+", '', s).lower()
i = 0
j = len(filtered) - 1
result = True
while (i <= j):
if (filtered[i] != filtered[j]):
result = False
break
i += 1
j -= 1
return result
print(mai... |
9262bfb759cd177be20503c93a3cea52adff8c44 | vitaliytsoy/problem_solving | /python/easy/palindrome_number.py | 1,226 | 4.3125 | 4 | """
Given an integer x, return true if x is a
palindrome
, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes ... |
7d279d2dafbfa2d7726fd7f1544340f3d94a748b | vitaliytsoy/problem_solving | /python/medium/delete_node_bst.py | 3,287 | 4.09375 | 4 | """
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Example 1:
Input: root = [5,3... |
7d9af69f24bafc9fc683cc2a4c57a0787f448c7f | intdxdt/robustpy | /rb_segs_inters/brut.py | 970 | 3.5 | 4 | # It is silly, but this is faster than doing the right thing for up to a
# few thousand segments, which hardly occurs in practice.
class BruteForceList(object):
def __init__(self, capacity):
self.intervals = [None] * (2 * capacity)
self.index = [None] * capacity # pool.mallocInt32(capacity)
... |
6ad87aa59c2a18ad7eeb449a0bcffb73a95260b9 | NathanSmithOPHS/Y11Python | /codechallenge2.py | 645 | 3.921875 | 4 | print("Welcome to the game")
age=int(input("Enter your age"))
print("Your age is", age)
gender=str(input("Enter your gender"))
print("You are a", gender)
email=str(input("Enter your email address"))
print("Your email is", email)
player_name=str(input("Enter your players name"))
print("Your players name is", player_name... |
5d20817477007dd61543dc8ec4004ceb76ebece6 | dcarlin/Advent-of-Code-Challenge | /Advent of Code/Day 5/Day5Part1.py | 2,146 | 4.1875 | 4 | '''
--- Day 5: A Maze of Twisty Trampolines, All Alike ---
An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions, and it would like assistance from any programs with spare cycles to help find the exit.
The message includes a list of the offsets for each jump. Jumps are relative: -... |
aa35b6b8e04544827510d26fb7210feb6e0f8af9 | avspit/prt | /ex2/PlotFunction.py | 2,016 | 3.75 | 4 | import numpy as np
import matplotlib.pyplot as plt
class PlotFunctions():
"""
Построение функций
"""
def sigmoid(self, x):
return (1 / (1 + np.exp(-x)))
def plot1(self):
"""
Построение sin(x) на интервале [0,1]
"""
x = np.linspace(0, np.pi, 100)
y =... |
231772db66b130c8992c32c124985940dd9039c8 | johanndiedrick/algos | /ctci/string_compression.py | 2,136 | 3.671875 | 4 | # Runtime O(n)
# Hints #92, #110
import unittest
from collections import OrderedDict
def compress_all(original_string):
character_count = OrderedDict()
compressed_string = ""
for s in original_string:
if s in character_count:
character_count[s] += 1
else:
character... |
11f47ca1b8cd59bd568272e38ce9585a0b0678dc | Shaon2710/Python-Code | /NikahReg/main.py | 268 | 3.84375 | 4 | from tkinter import *
root = Tk()
mylabe = Label(root, text='Hello world')
mylabe1 = Label(root, text='Hello world 2')
mylabe2 = Label(root, text='Hello world 3')
mylabe.grid(row=0,column=0)
mylabe1.grid(row=1,column=1)
mylabe2.grid(row=2,column=2)
root.mainloop() |
fd7b36774c4529396052585e429ce941102f15ed | arfio/PolyAlgo | /google_codejam_2010/StandingOvation.py | 959 | 3.765625 | 4 | def standing_ovation(path):
with open(path, mode='r') as file:
lines = file.readlines()
test_case_number = 0
line_number = 1
while test_case_number < int(lines[0]):
test_case_number += 1
# variables for this problem
sum_persons_clapping = 0
... |
f8683dd8cbadb7a3788094b32daef945c25e0ede | hawkerfun/python-algorithms | /SortingAlgorithms/SortingWithInsertion.py | 316 | 3.71875 | 4 | def sortWithInsertion(arr, len):
new_list = arr.copy()
for i in range(1, len):
temp = new_list[i]
curr_pos = i - 1
while temp < new_list[curr_pos] and curr_pos > -1:
new_list[curr_pos + 1] = new_list[curr_pos]
curr_pos -= 1
new_list[curr_pos + 1] = temp
return new_list |
2b5e77b5c1248bc6e49019e90ffa7d77153fb856 | jideedu/Parsing_Alexa_Skllls | /processing the Json file.py | 456 | 3.5625 | 4 | import json
from pprint import pprint
############load the file
print('NOW WE LOAD AND PRINT THE FILE')
alll = []
with open('file.json', "r") as f:
for line in f:
jsonobj = json.loads(line)
print(jsonobj['name'])
#loading all the file into an array
alll.append... |
eae127412a01adbe45e534e59e322a98bf44bb92 | bartekkroczek/FAN | /problemGenerator/classes/block.py | 962 | 3.578125 | 4 | import random
class Block:
def __init__(self, list_of_experiment_elements):
self.list_of_experiment_elements = list_of_experiment_elements
def randomize_block(self):
block_trials = [x for x in self.list_of_experiment_elements if x.type == 'trial']
experiment_elements_to_randomize = [x... |
7c19e2fc0e00f59bf6bdbd970c41cf10134d0114 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-5/exercicio5-6.py | 240 | 3.953125 | 4 | # Exercício 5.6 Altere o programa anterior para exibir os resultados no mesmo formato de uma tabuada: 2x1 = 2, 2x2=4, ...
print('\nTabuada do 2: \n')
i = 1
while i <= 10:
print('2 x %d = %d' % (i, i * 2))
i += 1
print('\n') |
e6f3f21d7c79d6c4078e5004dbbc28e684b98082 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-5/exercicio5-17.py | 670 | 3.796875 | 4 | # Exercício 5.17 O que acontece se digitarmos 0 (zero) no valor a pagar?
# R: O programa para ao após imprimir o número de cédulas de 50 reais, no caso, 0 cédulas.
valor=int(input("Digite o valor a pagar:"))
cédulas=0
atual=50
apagar=valor
while True:
if atual<=apagar:
apagar-=atual
cédulas+=1
... |
f61136d341c298695363454aee52d4b0512a4422 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-6/exercicio6-6.py | 2,241 | 4.09375 | 4 | # Exercício 6.6 - Modifique o programa para trabalhar com duas filas. Para facilitar
# seu trabalho, considere o comando A para atendimento da fila 1; e B,
# para atendimento da fila 2. O mesmo para a chegada de clientes: F para fila 1; e G, para fila 2.
from collections import Counter
caixa = [1]
gerencia = [1]
pr... |
099dd08839b518ffc0391c3dc15b672fbd450b03 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-8/exercicio8-5.py | 414 | 4 | 4 | # Exercício 8.5 - Reescreva a função da listagem 8.5 de forma a utilizar os métodos de
# pesquisa em lista, vistos no capítulo 7.
def pesquisa(lista, valor):
if valor in lista:
n = lista.index(valor)
print('\n%d encontrado na posição %d.\n' % (valor, n))
else:
print('\n%d não encontrado... |
1b04a5fa6406178885622d92052a834d0e302ecf | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-8/exercicio8-11.py | 554 | 4.09375 | 4 | # Exercício 8.11 - Escreva uma função para validar uma variável string. Essa função
# recebe como parâmetro a string, o número mínimo e máximo de caracteres. Retorne
# verdadeiro se o tamanho da string estiver entre os valores de máximo e mínimo,
# e falso em caso contrário.
def validarString(word, min, max):
size... |
5fce543a57b02a3e3a6f58638ef5e6725af8de13 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-4/exercicio4-9.py | 1,126 | 4.25 | 4 | # Exercício 4.9 - Escreva um programa para aprovar o empréstimo bancário para
# compra de uma casa. O programa deve perguntar o valor da casa a comprar, o
# salário e a quantidade de anos a pagar. O valor da prestação mensal não pode ser
# superior a 30% do salário. Calcule o valor da prestação como sendo o valor da
# ... |
f8686831aa70fbf1e959fa54e177d173a4fc1d83 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-8/exercicio8-2.py | 443 | 4.25 | 4 | # Exercício 8.2 - Escreva uma função que receba dois números e retorne True se o
# primeiro número for múltiplo do segundo.
# Valores esperados:
# múltiplo(8,4) == True
# múltiplo(7,3) == False
# múltiplo(5,5) == True
def multiplo(x, y):
if x % y == 0:
print('\nMúltiplo(%d, %d) == True\n' % (x, y))
els... |
ba0938388a7bf7559e4fff50a7db9b4538040f1b | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-4/exercicio4-8.py | 940 | 4.0625 | 4 | # Exercício 4.8 - Escreva um programa que leia dois números e que pergunte qual
# operação você deseja realizar. Você deve poder calcular a soma (+), subtração (-),
# multiplicação (*) e divisão (/). Exiba o resultado da operação solicitada.
a = int(input('\nInforme um número inteiro: '))
b = int(input('Informe outro ... |
21015895144d3f94e1b617d3b255aa8cb166fcc6 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-3/exercicio3-15.py | 630 | 3.84375 | 4 | # Exercício 3.15 - Escreva um programa para calcular a redução do tempo de vida de
# um fumante. Pergunte a quantidade de cigarros fumados por dia e quantos anos
# ele já fumou. Considere que um fumante perde 10 minutos de vida a cada cigarro,
# calcule quantos dias de vida um fumante perderá. Exiba o total em dias.
c... |
4503677d57980b0d59ba4ff93f18b4907eb1eb79 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-4/exercicio4-6.py | 535 | 3.921875 | 4 | # Exercício 4.6 - Escreva um programa que pergunte a distância que um passageiro
# deseja percorrer em km. Calcule o preço da passagem, cobrando R$ 0,50 por km
# para viagens de até de 200 km, e R$ 0,45 para viagens mais longas.
km = int(input('\nInforme a distância que deseja percorrer (em KM): '))
if km <= 200:
... |
d0e001ec3d2c040fa8f7ace6adb63abb70439e11 | joaovictor-loureiro/data-science | /data-science/exercicios/livro-introducao-a-programacao-com-python/capitulo-5/exercicio5-25.py | 703 | 3.875 | 4 | # Exercício 5.25 - Escreva um programa que calcule a raiz quadrada de um número.
# Utilize o método de Newton para obter um resultado aproximado. Sendo n o nú-
# mero a obter a raiz quadrada, considere a base b=2. Calcule p usando a fórmula
# p=(b+(n/b))/2. Agora, calcule o quadrado de p. A cada passo, faça b=p e recal... |
baebcb18fb8f49e417cc046f1c15cb0689a43386 | jc345932/week_8 | /prac8-1.py | 658 | 3.828125 | 4 | def calcRetirement(birthYear):
retirementYear = birthYear + 70
return retirementYear
def main():
name1 = str(input("Enter name1:"))
birthYear1 = int(input("Enter birth year:"))
birthMonth1 = str(input("Enter birth month:"))
retirementYear1 = calcRetirement(birthYear1)
name2 = str(input(... |
2828691a3d1b6c647de27ffda7cef3482acb85e0 | rayraib/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 513 | 4.25 | 4 | #!/usr/bin/python3
class Square():
'''Represent a square'''
def __init__(self, size=0):
'''Initialize data for each instances'''
if (isinstance(size, int) is False):
print("size must be an integer")
raise TypeError
elif size < 0:
print("size must be >=... |
6a763a5369d48d93e02cef09451f6645799f0d07 | rayraib/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 534 | 3.78125 | 4 | #!/usr/bin/python3
'''
search and update
'''
def append_after(filename="", search_string="", new_string=""):
'''insert a line of text to a file, after each line containing
a specific string.
'''
with open(filename, 'r', encoding='UTF-8') as f:
upd_str = ""
for line in f:
... |
64f77d50020033e6aa896db5f5cfee935114c556 | rayraib/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 3,271 | 3.578125 | 4 | #!/usr/bin/python3
'''
Base class for geomtric shapes
'''
import turtle
import json
class Base(object):
'''
Defines a base class that other geometric shapes can inherit from
'''
__nb_objects = 0
def __init__(self, id=None):
''' initialize public instnace attribute `id` '''
... |
27468f59b67074e8088cfa2476fb43aa2197cd33 | rayraib/holbertonschool-higher_level_programming | /0x0B-python-input_output/11-student.py | 429 | 3.875 | 4 | #!/usr/bin/python3
'''Student to JSON'''
class Student:
''' represents a student'''
def __init__(self, first_name, last_name, age):
'''initialize the instance variables'''
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self):
'''... |
f85188e3f05344cc4a07164c136b2a07c79424db | rayraib/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,488 | 3.75 | 4 | #!/usr/bin/python3
'''
Moduel containing class Square that inherits from class Rectangle
'''
from models.rectangle import Rectangle
class Square(Rectangle):
''' Represent a square with size that inherits from Rectangle'''
def __init__(self, size, x=0, y=0, id=None):
'''initialize the instance attr... |
9b7353cccce5974327650bf5bb955929c4a77cd3 | rayraib/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 303 | 4.125 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for row in matrix:
for column in row:
if column != row[len(row) - 1]:
print("{:d} ".format(column), end="")
else:
print("{}".format(column), end="")
print("\n", end="")
|
b01965adda08ac7dbb5743dfc47dff5cd28db1cd | rayraib/holbertonschool-higher_level_programming | /0x0B-python-input_output/5-to_json_string.py | 179 | 3.515625 | 4 | #!/usr/bin/python3
import json
'''JSON representation'''
def to_json_string(my_obj):
''' return JSON representation of the my_obj'''
x = json.dumps(my_obj)
return x
|
7e33bffa66103ca43d3a39f541c27ed8d0f20f63 | hmosenge/Pangram | /Pangram.py | 812 | 3.546875 | 4 | Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
KeyboardInterrupt
>>> def pangram():
alphabet = set('abcdefghijklmnopqrstuvwxyz')
s = input()
s = s.replace(' ','').lower()
s= sorted(s)... |
8e919cae1df6a7d5558e26caf7ce9180aa8eabe0 | one-more-coder/SpaceCraft | /space.py | 9,912 | 3.796875 | 4 | from turtle import *
from random import *
from base import *
# functions for genetating the random positions for pipe , targets and random bullet direction
def random_pipe():
value = randrange(-150,250)
return value
def random_target():
value = randrange( -150,150 )
return value
def random_enemy_bul... |
269388093f4b55ce720c08512c3688ee7ecfcac2 | Mezuriki/python-for-everybody-learning | /src/regular_expressions/11_1.py | 757 | 4.21875 | 4 | """
Exercise 1: Write a simple program to simulate the operation of the grep command on Unix.
+Ask the user to enter a regular expression and count the number of lines that matched the regular expression:
+$ python grep.py
+Enter a regular expression: ^Author
+mbox.txt had 1798 lines that matched ^Author
+$ python... |
6081b034e5eaf1e70df9ecbcae496545b372062b | cjbucko/CLaG | /lesson01_zipcodes.py | 2,214 | 4 | 4 | # Challenge Level: Intermediate and Advanced
# NOTE: Please don't use anyone's *real* contact information during these exercises, especially because you're putting them up on GitHub!
# For the purposes of this exercise, we're going to use unrealistically perfect and uniform addresses, and one-word first names :)
... |
ad85439a10303232efbef4ba04b5bc186045d942 | mwartell/wordlist | /wordlist/xkcd_pass.py | 1,441 | 3.96875 | 4 | """Create a passphase in the style of xkcd 'correct horse battery staple'"""
import sys
import random
from . import wordlist
def correct_horse_battery_staple(words, word_count):
"""Return n cryptographically "strong" shorter words from the standard list
without repeats as suggested in https://xkcd.com/936/
... |
45bce8ff4acf02a216b28d04875cb13f172c6d5f | perkinss3642/CTI-110 | /P2HW1_PoundsKilograms_StevenPerkins.py | 333 | 3.9375 | 4 | #Pounds to Kilograms converter
#April 6, 2019
#CTI-110 P2HW1 - Pounds to Kilograms Converter
#Steven Perkins
#Input pounds to be converted
pounds = float(input("Enter pounds:"))
#Convert pounds to kilograms
kilograms = pounds/2.2046
#Display kilograms
print("number of kilograms is", \
format(kilog... |
343ea3607f9fe8fbdc29e6f8e9fd2baed07a3952 | Gokulankkp/python-practice | /area of t.py | 111 | 3.890625 | 4 | b = float(input('enter base of a triangle: '))
h = float(input('enter height of a triangle: '))
area = (b*h)/2
|
a9b2cca40d1c9121619eb6101218f05815a226e9 | ebookleader/Programmers | /Level2/matrixProduct.py | 614 | 3.546875 | 4 | import numpy as np
def solution(arr1, arr2):
# answer = []
# n, l, m = len(arr1), len(arr2), len(arr2[0])
# for i in range(n):
# lst = []
# for j in range(m):
# total = 0
# for k in range(l):
# res = arr1[i][k] * arr2[k][j]
# total += ... |
a0ed32e31c78d5103937d5ed9373694a85bf7585 | ebookleader/Programmers | /Level1/strangeString.py | 333 | 3.609375 | 4 | def solution(s):
answer = []
lst = s.split(' ')
for l in lst:
st = ''
for i in range(len(l)):
if i % 2 == 0:
st += l[i].upper()
else:
st += l[i].lower()
answer.append(st)
return " ".join(answer)
print(f'"{solution("try hell... |
2791b06f19d4c22321a2b22fbbf33f8e9c30e0bf | ebookleader/Programmers | /Level1/2016.py | 384 | 3.65625 | 4 | import datetime
def solution(a, b):
# week = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
# d = datetime.datetime(2016, a, b)
# answer = week[d.weekday()]
# return answer
month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
week = ['FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU']
re... |
4628c677de8204085856bcacd0a8f2b41187f7d4 | ebookleader/Programmers | /Level2/getNumOfSquare.py | 262 | 3.546875 | 4 | def solution(w,h):
answer = 1
square = gcd(w, h)
# num = (w // square) + (h // square) - 1
return (w * h) - (w + h - square)
def gcd(a, b):
while b != 0:
k = a % b
a = b
b = k
return a
print(solution(8, 12)) |
335ebbbf472a8abdb980fc49b9e921f2c235fd0a | dkatz23238/fconvert | /fconvert/functions.py | 295 | 4.1875 | 4 | def convert_farenheit_to_cel(val):
""" Converts a number in farenheit to celsius.
Args:
val (float): The value in celsius that our functions will convert.
Returns:
float: The value converted to farneheit.
"""
c = (val-32)* (5/9.0)
return round(c,2) |
c72644536234ce7dc29dac32af38cec62ae38011 | Orazumov/MFTI | /test.py | 1,148 | 3.90625 | 4 | from functools import reduce
from sys import getsizeof
variables = [] # массив для оценки памяти
n = int(input('Введите количество элементов ряда чисел: '))
lst = [1]
number = 1
for i in range(1, n + 1):
number = number / 2
if i % 2 == 0:
lst.append(number)
else:
l... |
24f41a52f162ec35d577fc12c6e6907d1fbffff2 | rengare/python_od_podstaw | /odc6.py | 377 | 3.8125 | 4 | masa = int(input("podaj swoja mase w kg "))
wzrost_w_centymetrach = int(input("podaj wzrost w cm "))
wzrost_w_metrach = wzrost_w_centymetrach / 100
bmi = masa / (wzrost_w_metrach**2)
if bmi < 18.50:
print("masz niedowage")
if bmi >= 18.50 and bmi < 25:
print("optimum")
if bmi >= 25 and bmi < 30:
print("masz ... |
ae719c732687ca2b5d64c430b44adf6fc885a6c0 | Dmfp2011/CS101-Python | /Project 3.py | 8,642 | 4.03125 | 4 | #####################################################
#####################################################
## CS 101
## Program 3
## Dylan Pembrook
## dmpfzf@mail.umkc.edu
##
## Problem: Slice of life
##
## Algorithm:
## rounds=int(input(“how many rounds do you want to play? (1-20)=>”))
## while rounds<0 or ... |
e8f680320645451f085e51cf76e91f5446a00e33 | nad0u/game_project | /python/game/CrossFade.py | 4,175 | 3.8125 | 4 | # CREDIT: https://www.youtube.com/watch?v=vLYwl9MFvQQ
# Synthesizes a cross-fade effect by changing the transparency
# of a Surface over time
# python_bro
# 9/7/13
import pygame
class CrossFade(pygame.sprite.Sprite):
"""Synthesizes fades by incrementing the transparency
of a black surface blitte... |
7d7cdb6a0ad7f7ab0beb19163e71e2b16a147ba5 | erik-t-irgens/algorithmic-toolbox-assignments | /fibonacci_last_digit.py | 509 | 3.90625 | 4 | # Uses python3
import sys
def fib_last_digit(n):
if n < 2: return n
else:
a, b = 0, 1
for i in range(1,n):
a, b = b, (a+b) % 10
return(b)
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1... |
503dba0300083c31b92b347ec1643777a356a582 | TrekkerVikk/python-random-quote | /LoopsCommand1.py | 508 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
number = 1
while number <=15:
print(number)
number = number +1
# In[10]:
number = 1
while number <=10:
if number % 2 !=0:
print(number)
number = number +1
# In[14]:
L = []
while len(L)<5:
new_name = input("Please add a new name:").... |
1da8b01c62bc2ede6934c993fff71bbfe2f061af | thangioletti/Interpretador | /classes/explog.py | 1,813 | 3.71875 | 4 | # comparacao -> > < >= <= == !=
#
class Explog:
def __init__(self, expreg1=None, comparacao=None, expreg2=None, explog=None):
self.expreg1 = expreg1
self.comparacao = comparacao
self.expreg2 = expreg2
self.explog = explog
def __str__(self):
aux = "<EXPLOG> \n"
... |
85de2a72ff66f15b3c21493125d801de4fc59465 | katsuuuu/document_analysis | /result_report.py | 13,176 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[513]:
# “An Analysis of Social Media Company’s User Agreement” - Determining the readability
# Katsuhiko Nakanishi
# import file
def file_import(file):
f = open(file, encoding='utf-16')
lines = f.readlines()
f.close()
punctuation = "!#$%&'\"()*+, -.... |
f9c8df4a0a76aa546b2d6803cd6dafc10d5be74f | shion200/poker | /poker.py | 987 | 3.59375 | 4 | import random
l = [ 1,2,3,4,5,6,7,8,9,10,11,12,13]
SUIT = ["♣","♥","♠","♦",]
card = [ ]
for num in range(1,14):
for suit in SUIT:
card.append(suit +str(num))
#print(card[len(card)-1])
def getcard():
c = random.choice(card)
card.remove(c)
return c
number1 = getcard()
number2 = getcard()
n... |
e295771036b5ea52b446fe77f4e9397fb60d5428 | ahujasushant/leetcode_problems | /2.py | 558 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
n1, n2 = '', ''
while l1:
n1 = str(l1.val) + n1
... |
87b979e0cb9ed48ba7033c9a9bac41fb942df8f3 | MariaJavier/python-challenge | /PyBank/main.py | 3,328 | 3.53125 | 4 | import os
import csv
# Path to collect data from the Resources folder
budget_data = os.path.join('budget_data.csv')
with open(budget_data, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
month_line_count = 0
profit_losses_total = 0
average_profitloss_chang... |
ecf53ebb9967d6f2777977a0f53b807280b7adfb | niddhi787/Count-frequency | /func.py | 292 | 3.78125 | 4 | count={}
def most_frequent(a):
for i in a:
if i in count:
count[i]+=1
else:
count[i]=1
for key in count:
print(key,count[key])
b=input("Enter string:")
c=most_frequent(b)
print(c)
|
99845785255f3c4579486dcff0c27c8630807f64 | jbmoskow/NBABasketballAnalytics | /BayesCalculator.py | 8,826 | 3.890625 | 4 | import pandas
import matplotlib.pyplot as plt
import numpy
def cleanDraft(stringArray):
"""Returns a list of names in the format of 1st letter of first name and last name
e.g. Abraham Lincoln gets converted to A. Lincoln"""
cleanedNames = []
for n in stringArray: # for each name
if type(n) i... |
e850be8b06903738265ec70eefcf56d2f7adb94b | poojataksande9211/python_data | /python_tutorial/excercise_3/list_vs_string.py | 475 | 4.34375 | 4 | #list vs string
#strings are immutable (immutable means u can not change your string)
#we can not add character in string
#list are muttable
s="string"
# s.title() #title method covert 1st charecter of word to uppercase letter
# print(s) #original string cant be change
# p=s.title() #this is new string (u can change in... |
aa73764334cc86f02cce4533aee7fd5c4dd0b236 | poojataksande9211/python_data | /python_tutorial/excercise_4/convert_tuple_to_string.py | 119 | 4.25 | 4 | #Write a Python program to convert a tuple to a string.
num=("1","2","3")
str="".join(num)
print(str)
print(type(str)) |
962776ae0cf77ba004f01285e1e22e7a113252c5 | poojataksande9211/python_data | /python_tutorial/excercise/ip_for_char_count_string.py | 158 | 3.734375 | 4 | name=input("enter name")
temp=""
for i in range (len(name)):
if name[i] not in temp:
print(f"{name[i]}:{name.count(name[i])}")
temp=temp+ name[i]
|
0f02f6a8f756b304de497ba2ddd22b79d593e570 | poojataksande9211/python_data | /python_tutorial/excercise/infinite_loop.py | 171 | 3.75 | 4 | #infinite loop
# i=0 #infinite loop by mistske
# while i<=10:
# print("hellow amata")
# #.............................
while True: #True is boolean
print("pooja ganvir") |
db875462e0e0f488bb9774ae633c369a264a7895 | poojataksande9211/python_data | /python_tutorial/excercise_3/demo.py | 1,868 | 4.46875 | 4 | #list chapter summery
#list=list is a data structure that can hold any type of data
#create a list
words=["word1","word2"]
#u can store anything insight list
#----------------------------------------
# mixed=[1,2,3,[4,5,6],"seven",8.0,None] #None is a special value
# #list is a ordered collection of items
# print(mixed... |
f75d235fdbfff06696ddb4ee224f5acb290e28ac | poojataksande9211/python_data | /python_tutorial/excercise_2/funct_input.py | 159 | 3.90625 | 4 | def add(a,b):
return a + b
num1=int(input("enter first no"))
num2=int(input("enter second no"))
# total=add(num1,num2)
# print(total)
print(add(num1,num2)) |
90a7f173bd1f9b10b7ee406bd7a04eb845c9cb9e | poojataksande9211/python_data | /python_tutorial/excercise_3/list_insight_list_count_type.py | 266 | 3.921875 | 4 | #count list insight list using type func
def count_list_type(l):
count=0
for i in l:
if type(i) == list:
count=count+1
return count
number=[1,2,3,[1,2],[3,4,5]]
# number=[1,2,3,[4,5,6],"seven",8.0,None]
print(count_list_type(number)) |
18ba6c2bd07d31cd1c3f5aa88b9c3f34657d5751 | poojataksande9211/python_data | /python_tutorial/excercise_4/func_returning_two_values.py | 180 | 3.890625 | 4 | #func return two values
def func(int1,int2):
add=int1+int2
mult=int1*int2
return add,mult
# print(func(2,3)) #return one tuple
add,mult=func(2,3)
print(add)
print(mult) |
b8f54cc1c1a631d20d0f14462e83961b44d2ed75 | poojataksande9211/python_data | /python_tutorial/excercise/and.py | 168 | 3.8125 | 4 | name="pooja"
age=19
if name == "pooja" and age == 19: #(it requires both the conditions are true)
print("condition is true")
else:
print("condition is false") |
a0d695209524988d253d0dbf74d0da253b1df8b6 | poojataksande9211/python_data | /python_tutorial/excercise_2/func_greatest_3_no.py | 292 | 4.09375 | 4 | num1=int(input("enter first no"))
num2=int(input("enter second no"))
num3=int(input("enter third no"))
def great_3_no(a,b,c):
if a>b and a>c:
return a
elif b>a and b>c:
return b
else:
return c
bigger=great_3_no(num1,num2,num3)
print(f"{bigger} is greater") |
fa66e3ee94787f31b623ecaa8c87aebb55f464e5 | poojataksande9211/python_data | /python_tutorial/excercise_4/print_tuple_with_string_formating.py | 113 | 4.15625 | 4 | #Write a Python program to print a tuple with string formatting
tup=(100,200,300)
print(f"this is a tuple {tup}") |
91cc09be1c47601448cfe910821c559f6772755d | poojataksande9211/python_data | /python_tutorial/excercise_11_decorators/decorators_part_3.py | 429 | 3.546875 | 4 | #decoratos_part_3
from functools import wraps
def decorator_func(any_func):
@wraps(any_func)
def wrapper_func(*args,**kwargs):
"this is wrapper func"
print("this is awesome func")
return any_func(*args,**kwargs)
return wrapper_func
@decorator_func
def add(a,b):
"this is add func"... |
81107459419f27a09543e5c16f98465e7e781878 | poojataksande9211/python_data | /python_tutorial/excercise_3/practice_excercise_3/demo.py | 218 | 3.921875 | 4 | def eve_odd(l):
even=[]
odd=[]
for i in l:
if i%2==0:
even.append(i)
else:
odd.append(i)
output=[even,odd]
return output
num=[1,2,3,4,5,6]
print(eve_odd(num)) |
9a0cb86de3d9e7951695f865605694acb7844722 | poojataksande9211/python_data | /python_tutorial/excercise_3/practice_excercise_3/unique_values_in_list.py | 277 | 4.1875 | 4 | #Write a Python program to get unique values from a list.
def unique_value(l):
uni=[]
for i in l:
if i not in uni:
uni.append(i)
return uni
num=[1,2,3,4,5,1,2]
word=["a","bc","dc","p","a","bc"]
print(unique_value(num))
print(unique_value(word))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.