blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6f495df40c8b39406fa304693140fddb4d8330d7 | chaosWsF/Python-Practice | /leetcode/0645_set_mismatch.py | 1,421 | 3.953125 | 4 | """
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of
the numbers in the set got duplicated to another number in the set, which results in repetition of
one number and loss of another number. Given an array nums representing the data status of this set
after the erro... |
fa9158d75cc69533dd99db47b0d542a8e7e7fa4e | chaosWsF/Python-Practice | /leetcode/0696_count_binary_substrings.py | 1,683 | 3.9375 | 4 | """
Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's,
and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times
are counted the number of times they occur.
Example 1:
Input: "00110011"
Ou... |
f8bf920e142a542fca072e3c139bcfd5c686c94e | chaosWsF/Python-Practice | /leetcode/0637_average_of_levels_in_binary_tree.py | 1,074 | 3.671875 | 4 | r"""
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 ... |
bcd5d58a4b1789a205e03f69fe2458b9b4a5b5a2 | chaosWsF/Python-Practice | /leetcode/0088_merge_sorted_array.py | 2,069 | 4.21875 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m
and n respectively.
You may assume that nums1 has enough space (size that is
greater or equal to m + n) to hold additional elements from... |
b7303bbe2c2c11044f4c898394f59b677c723ddb | chaosWsF/Python-Practice | /leetcode/0163_missing_ranges.py | 953 | 3.515625 | 4 | """
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return [“2”, “4->49”, “51->74”, “76->99”].
"""
class Solution:
def findMissingRanges(self, nums: List[int], lower: int... |
dd0ca36d22e09a8278608bbd0c02f554bc9cab26 | chaosWsF/Python-Practice | /leetcode/1002_find_common_characters.py | 1,281 | 4.15625 | 4 | """
Given an array A of strings made only from lowercase letters, return a list of all characters that show up
in all strings within the list (including duplicates). For example, if a character occurs 3 times in all
strings but not 4 times, you need to include that character three times in the final answer. You may r... |
674ef5c016216bb2e64195ccb36ccb056773a720 | chaosWsF/Python-Practice | /leetcode/0434_number_of_segments_in_a_string.py | 546 | 4.15625 | 4 | """
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
"""
class Solution:
def countSegments1(self, s):
... |
4c7b367c3b9b4fb7a767da6410d7ad047f3f6dd5 | chaosWsF/Python-Practice | /leetcode/0108_convert_sorted_array_to_binary_search_tree.py | 2,191 | 4 | 4 | """
Given an array where elements are sorted in ascending order,
convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a
binary tree in which the depth of the two subtrees of every node
never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
... |
3ec92e150f46c43513d64ac38dc3fe1243aa8c46 | chaosWsF/Python-Practice | /leetcode/0475_heaters.py | 1,570 | 4.03125 | 4 | """
Winter is coming! Your first job during the contest is to design a standard heater with
fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters
on a horizontal line, find out minimum radius of heaters so that all houses could be covered
by those heaters. So, your input will b... |
e30b5665dd51874c3dc42c5b6da4230749c666e5 | chaosWsF/Python-Practice | /leetcode/1010_pairs_of_songs_with_total_durations_divisible_by_60.py | 1,107 | 3.75 | 4 | """
In a list of songs, the i-th song has a duration of time[i] seconds. Return the number of
pairs of songs for which their total duration in seconds is divisible by 60. Formally, we
want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.
Example 1:
Input: [30,20,150,100,40]
Out... |
91a3945e0a5c64e742044561e604036f4a408ea6 | chaosWsF/Python-Practice | /leetcode/0053_maximum_subarray.py | 1,076 | 4.09375 | 4 | """
Given an integer array nums, find the contiguous subarray
(containing at least one number) which has the largest sum
and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try ... |
d61a2852a0d87f5edd504db5c7579043d3ac4148 | chaosWsF/Python-Practice | /leetcode/1217_minimum_cost_to_move_chips_to_the_same_position.py | 1,593 | 4.03125 | 4 | """
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position
of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return ... |
e7baad6ba3c463da0405fa12f511a4a904e16de4 | chaosWsF/Python-Practice | /leetcode/1266_minimum_time_visiting_all_points.py | 1,266 | 3.703125 | 4 | """
On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the
minimum time in seconds to visit all points.
You can move according to the next rules:
In one second always you can either move vertically, horizontally by one unit or diagonally (it means
to move one u... |
7b2752b18f530955d474b380776b3aa4677a4d0c | chaosWsF/Python-Practice | /leetcode/0653_two_sum_iv_input_is_a_bst.py | 1,558 | 3.734375 | 4 | r"""
Given a Binary Search Tree and a target number, return true if there exist two elements in the
BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
... |
7b2c82d7b9928932e755886797ac6248403e492c | eskit3r/Ejercicios_python | /conversor_moneda.py | 282 | 3.828125 | 4 | import time
print("Hola, quiero cambiar mis libras a euros")
time.sleep(2)
tc=1.17
print("Buenos dias, el tipo de cambio es " +str(tc))
time.sleep(2)
b=float(input("Ingrese la cantidad de libras a cambiar:"))
c=b*tc
print("Su dinero cambiado seria " +str(c)+ " euros") |
400142c7d92f56ad7af22a82663441976791369d | JQuinSmith/learning-python | /ex15.py | 813 | 4.34375 | 4 | # imports the module
from sys import argv
# the script, and the text file are used as modules
script, filename = argv
# Assuming "open" opens the file being passed into it for use in the rest of the script.
txt = open(filename)
# # Serves up the filename based on what is entered into the terminal.
# print ("Here's y... |
c054e9c21ef555e6f9fe7d877ff3ed9449454a21 | teosz/IA | /homeworks/T1testing.py | 1,990 | 3.515625 | 4 |
# coding: utf-8
# In[1]:
# globals
Alphabet = {}
Tests = []
def init():
with open("alphabet.txt") as f:
AlphabetRaw = " ".join(f.readlines())
alphalist = AlphabetRaw.split()
i = 0
while i < len(alphalist):
Alphabet[alphalist[i]] = alphalist[i+1]
i += 2
for i in range(4)... |
169134528a37c4191721f8ab53bc23c6914f91b6 | 4rfel/compilador | /main.py | 805 | 3.5 | 4 | import sys
def split_by_list(l, s):
s = s.split(l[0])
for i in l[1:]:
temp = []
for j in s:
temp += j.split(i)
s = temp
return s
if len(sys.argv) == 1:
sys.exit("invalid input")
numbers = split_by_list(["+", "-"], sys.argv[1])
numbers = [x.strip() for x in numbers]
for i in numbers:
for j in i:
if j ... |
051d152a08808d4a5a990c4e8aa744edc05a0d70 | iamsix/leetcode | /2.addtwonumbers.1.py | 936 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
#iterative version...
if not l1:
return l2
if not l2:
return l1
car... |
f9dda556d169d2563730521a4cc6557889d2a937 | asud16/week1 | /exercise54.py | 378 | 3.9375 | 4 | # This is where Exercise 5.4 goes
# Name: Aparna Sud
def is_triangle (x, y, z):
if x > y+z or y > x+z or z > x+y:
print "No"
elif x+y == z or x+z == y or y+z == x:
print "Yes"
else:
print "Yes"
#is_triangle(6,10,4)
def is_triangle2 (x, y, z):
a= x%2
b= y%2
c= z%2
if a or b or c != zero:
is_t... |
71678e32831ef0554e88ee5e916b749ba0a8ced9 | Program-Explorers/Random_Password_Generator | /random_password.py | 1,963 | 4.21875 | 4 | # import statements
#Random Password Generator
import random
import string
def greeting():
print("This programs makes your password more secure based on a word you provide!"
+ "\nIt increases the strenth of your password by adding random letters and digits before or after the word\n")
class password_g... |
87e405b352f0847f92c64e5595ad119c191981f9 | JSwidinsky/CompetitiveProgramming | /cpsc3200/RockyMountain2014/ContinuedFraction.py | 744 | 3.65625 | 4 | #The approach here is to convert each partial quotient of the input into a fraction, then
# do +, -, *, and /, then convert back to continued fraction form
#Had to learn python for this one, which was pretty nasty
from fractions import Fraction as Frac
def getInput(n) :
a = [int(x) for x in input().split()]
ret ... |
1cb20485ce03458d71b766dc450d2b9f624f8e21 | Benjamin-Menashe/Project_Euler | /problem1.py | 470 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 10:09:34 2021
@author: Benjamin
"""
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
import numpy as np
fives = np.array(rang... |
21b758467903c4a665acb0a9d0f2da0a4a6c84f7 | Benjamin-Menashe/Project_Euler | /problem57.py | 655 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 12:24:19 2021
@author: Benjamin
"""
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
# In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?
counts =... |
44b515842cf401d015e64f4ba5c2b686c5a1c7fc | timgates42/django-yubin | /django_yubin/iter_utils.py | 327 | 3.921875 | 4 | import itertools
def peek(sequence):
"""
Returns the value of the top of the sequence without removing the value
from the data.
"""
iterable = iter(sequence)
try:
first = next(iterable)
return first, itertools.chain([first], iterable)
except StopIteration:
return No... |
b0a767a9b454a9bfe31e9d291e668a3f80b6336c | gabrielthecruz/hackerrank-challenges | /compress_the_string/compress_the_string.py | 299 | 3.578125 | 4 | from sys import stdin
from itertools import groupby
def compress_str(string):
for char, group in groupby(string):
length = len(list(group))
print('({}, {})'.format(length, char), end=' ')
if __name__ == '__main__':
string = stdin.read().strip()
compress_str(string)
|
f086f51420a6fc08f0fc1a95bf3a3623d5935f00 | jordanr03/Python---Computing-OOP | /W5 - Object-Oriented Concepts/Optimisation Project - Multiple Files/Class_Menu.py | 660 | 3.5625 | 4 | import sys
class Menu:
userObject = None
def __init__(self, userObject):
self.userObject = userObject
if self.userObject.auth:
option = int(input(f"Welcome {self.userObject.username}!\n"
f"1 - Say Hello\n"
f"2 - Exit Pr... |
46d7d658d1ac911eb835094e1ce9f8523830aaad | jordanr03/Python---Computing-OOP | /W3 - OOP/Dog.py | 325 | 3.8125 | 4 |
class Dog:
name = ""
breed = ""
age = ""
colour = ""
def __init__(self, name, breed, age, colour):
self.name = name
self.breed = breed
self.age = age
self.colour = colour
def eat(self):
print("I've eaten food!")
def bark(self):
print("Woof!... |
d9644ee1a66bcb39190faacfc5888dadb856ebe8 | Yasaman1997/My_Python_Training | /Practice/Practice/Element_search/Test.py | 368 | 3.9375 | 4 | def find(my_list,new_element):
for element in my_list:
if element == new_element:
return True
return False
if __name__ == "__main__":
l = [2, 4, 6, 8, 10]
print(find(l, 5)) # prints False
print(find(l, 10)) # prints True
print(find(l, -1)) # print... |
e9f825970e7debe33eab4111889aa6de5241f061 | Yasaman1997/My_Python_Training | /Practice/Practice/Divisor/EndList/test.py | 95 | 3.5 | 4 | def list_ends(a_list):
print a_list[0], a_list[len(a_list)-1]
a=[1,2,3,4,5]
list_ends(a) |
4a142521847fc805a536ad344f14290c3108fe87 | Yasaman1997/My_Python_Training | /Practice/Practice/Fibonacci/test.py | 392 | 3.921875 | 4 | def gen_fib():
count = int(input("How many fibonacci numbers would you like to generate? "))
i = 1
if count == 0:
fib = []
elif count == 1:
fib = [1]
elif count == 2:
fib = [1, 1]
elif count > 2:
fib = [1, 1]
while i < (count - 1):
fib.append(f... |
8d208cee28c4dc5fa45b42d4a7e57e2508840a3d | Yasaman1997/My_Python_Training | /Test/lists/__init__.py | 1,599 | 4.375 | 4 | zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];
# One animal is missing!
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth... |
422c3b26b40811f75075b55f678dc729824b2345 | harshpreetkaur13/Scientific_Calculator | /calc.py | 14,126 | 3.671875 | 4 | from tkinter import *
import math
import parser
import tkinter.messagebox
#====================================Window=====================================================================================
root=Tk() #creating window
root.title("Scientific Calcul... |
4a97a4d9b8877d63723d35d23dbccb1b2861f2d6 | fmorel/kspCalc | /kspCalc.py | 3,735 | 3.515625 | 4 | #!/usr/bin/python
import math
import csv
import argparse
import sys
from body import *
from utils import *
#----------------------------------------------
#Main code
#Open csv data retrieved from http://wiki.kerbalspaceprogram.com/wiki/Celestials
csvFile = open('orbitals.csv', 'r')
csvDict = csv.DictReader(csvFile... |
baf6d794c568c77a0f710800b014e408b947e1dd | P-ppc/leetcode | /algorithms/FlattenAMultilevelDoublyLinkedList/solution.py | 748 | 3.75 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
... |
cccb94dbd67ab505776085d00886a896e6e85b3c | P-ppc/leetcode | /algorithms/IntersectionOfTwoLinkedLists/solution.py | 924 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p1 = headA... |
056d38d6d904a09f645949adcd0d22d98d05e2cf | P-ppc/leetcode | /algorithms/NonDecreasingArray/solution.py | 870 | 3.546875 | 4 | class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
parts = []
part = []
for i in range(len(nums)):
part.append(nums[i])
if i + 1 < len(nums) and nums[i + 1] < nums[i]:
... |
d0f11abb9f73e067eb74f3fb6c68f13d4ac34f41 | P-ppc/leetcode | /algorithms/RotateImage/solution.py | 679 | 3.546875 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
i = 0
while i < n / 2:
x = i
y = i
... |
37c212c3a0ebd8f1c897dd3e4ece114adc9cb6a8 | P-ppc/leetcode | /algorithms/ConstructQuadTree/solution.py | 1,608 | 3.75 | 4 | """
# Definition for a QuadTree node.
class Node(object):
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = b... |
8a9b218433963208947545f4bf9617fc7c84424f | P-ppc/leetcode | /algorithms/PathSumIII/solution.py | 986 | 3.734375 | 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 pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
... |
724011be289b5ed828dfaa573397a13eaf1173b3 | JCBrown602/responsipy | /hrequest.py | 2,235 | 3.75 | 4 | """
Response Tool
https://github.com/JCBrown602/responsipy
Command line (*nix) tool that asks for URL and gets HEADERS
for that URL.
TODO:
- Isolate Content-Type
- Open text file containing URLs and get Content-Type for all of them
- Could be 100+ URLs
- Get port number? Available in requests module?
"""
# Imp... |
84b576eaa5264a6d0e3a73ec6bcbd7103ee9efc7 | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_005.py | 197 | 4.25 | 4 | # Vai mostrar o sucessor e o antecessor de um número
num = int(input("Digite um número: "))
print(f"Você digitou o número {num}\nSeu sucessor é o {num + 1}\nE seu antecessor é o {num - 1}") |
922d759d15436de40816b7bf03f8c6d357d9a96a | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_035.py | 321 | 4.0625 | 4 | # Mostra se um triângulo pode ou não existir
r1 = float(input("Digite a 1° reta: "))
r2 = float(input("Digite a 2° reta: "))
r3 = float(input("Digite a 3° reta: "))
if r1 + r2 > r3 and r1 + r3 > r2 and r2 + r3 > r1:
print("Esse triângulo pode existir!!")
else:
print("Esse triângulo não pode existir!!") |
b3b79f7f01bee57c0eca157d2034692141628364 | pedrohenriquebraga/Curso-Python | /Mundo 3/Aulas/Aula_17_Listas_1.py | 645 | 4.34375 | 4 | # PARA ADICIONAR ELEMENTOS A LISTAS USAMOS: lista.append(elemeto ser adicionado)
# PARA ADICIONAR ELEMENTOS EM LUGARES ESPECÍFICOS DA LISTA USAMOS:
# lista.insert(posição a ser adicionada, o que vai ser adicionado)
# PARA EXCLUIR ELEMENTOS: del lista[elemento]
# Também pode - se usar o lista.pop(elemento)
# OUTRA MANEI... |
667eabe6a4597d04e35d8f01e2e1887e2521a5b9 | pedrohenriquebraga/Curso-Python | /Mundo 2/Exercícios/ex_061.py | 186 | 3.609375 | 4 | # Desafio 051 Aprimorado
cont = 0
pt = int(input("Primeiro Termo: "))
r = int(input("Razão: "))
while cont != 10:
print(pt, end=" • ")
pt = pt + r
cont += 1
print("Fim") |
ac10ee98696cf669f2c0a7605ea435c2d66c5a37 | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_078.py | 482 | 4 | 4 | # MAIOR E MENOR NÚMERO EM LISTA
num = list()
for c in range(0, 5):
num.append(int(input(f"Digite o {c}° valor: ")))
print(f"Você digitou os números:{num}")
print(f"O maior valor digitado foi o {max(num)} nas posições ", end="")
for i, v in enumerate(num):
if v == max(num):
print(i, end=" ")
print()
pr... |
4c9ea2d052ab1fab415dbcdd52dc7871ebafc9fc | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_097.py | 193 | 3.84375 | 4 | # Função para linha adaptativa
def escreva(msg):
print("~" * (len(msg) + 2))
print(f" {msg} ")
print("~" * (len(msg)+2))
msg = str(input("Escreva uma mensagem: "))
escreva(msg) |
1c0eea60706c0eb265496f3dcf2a7e4c5086a6cb | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_115/Comandos/cadastrar/.last_tmp.py | 1,206 | 3.671875 | 4 | def ExisteArq(nome):
try:
open(nome, "rt")
except:
return False
else:
return True
def CriarArq(nome):
try:
open(nome, "wt+")
except:
print("HOUVE UM ERRO!!")
finally:
nome.close()
def cadastrar(nome="<desconhecido>", idade=0):
try:
... |
43af5f6e93313eb6ee4e73558a761d17195f2ed8 | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_112/utilidadescev/dado/__init__.py | 278 | 3.578125 | 4 | def leiaDinheiro(msg):
while True:
entrada = str(input(msg)).replace(",", ".").strip()
if entrada.isalpha() or entrada == "":
print(f"\033[1;31mERRO!! '{entrada}' NÃO É VÁLIDO!!\033[m")
else:
break
return float(entrada) |
c57cd7f705639865c0832d6ea4a0017e87e4562f | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_079.py | 639 | 4.125 | 4 | # Verificação de valores em listas
valores = list()
while True:
print("~" * 45)
num = int(input("Digite um valor: "))
if num not in valores:
valores.append(num)
print("VALOR ADICIONADO COM SUCESSO...")
else:
print("VALOR DUPLICADO!! NÃO VOU ADICIONAR...")
continuar = str(in... |
b93fd6ff5d3bcacc7e4a6ef5394c95f35f920a89 | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_016.py | 174 | 3.921875 | 4 | # Mostra a parte inteira de um número
from math import trunc
num = float(input("Digite um número com vírgula: "))
print(f"A parte inteira desse número é {trunc(num)}") |
cc98e5c510ef233fe98ba8d9c0634ea6587236bb | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_109/main.py | 340 | 3.6875 | 4 | # Modularização para moeda
from ex109 import *
v = float(input("Digite um valor: R$ "))
print(f"A metade de {moeda(v)} é {metade(v, True)}")
print(f"O dobro de {moeda(v)} é {dobro(v, True)}")
print(f"{moeda(v)} com 10% de aumento fica {aumentar(v, 10, True)}")
print(f"{moeda(v)} com 13% de diminuição fica {diminuir(v... |
893bda590b41d447674cb6f7568940815b7021cb | pedrohenriquebraga/Curso-Python | /Mundo 2/Exercícios/ex_040.py | 399 | 3.890625 | 4 | # Mostra médias de alunos
nota1 = float(input("1° nota do aluno: "))
nota2 = float(input("2° nota do aluno: "))
media = (nota1 + nota2) / 2
if media < 5:
print(f"A média é {media:.2f}, o aluno está REPROVADO!!")
elif media >= 5 and media <= 6.9:
print(f"A média é {media:.2f}, o aluno está de RECUPERAÇÃO!!")
e... |
1c9c51ac3d33fd9d7e5d90421dbebb3d206a3f45 | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_003.py | 195 | 4 | 4 | #Ele vai ler dois números e mostrar sua soma
num1 = float(input("Digite um número: "))
num2 = float(input("Digite outro número: "))
print(f"A soma entre {num1} + {num2} vale {num1 + num2}")
|
3f14bd267858896543d5655ee7e7b2274fef9cb2 | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_100.py | 453 | 3.859375 | 4 | # Sorteio e soma os números pares com funções
from random import randint
num = list()
def sorteia():
for c in range(0, 5):
num.append(randint(0, 10))
def somapar(lst):
par = 0
pos = 0
while pos < len(lst):
for n in lst:
pos += 1
if n % 2 == 0:
... |
97e0ffb3b399e93acb994708b60b7400449492f6 | pedrohenriquebraga/Curso-Python | /Mundo 3/Aulas/Aula_23_Erros_Exceções.py | 485 | 3.9375 | 4 | try:
a = int(input("Numerador: "))
b = int(input("Divisor: "))
r = a / b
except (ValueError, TypeError):
#Exception mostra o que ocorreu de errado
print("Tivemos um erro o tipo de dados que você enviou!!")
except ZeroDivisionError:
print("Nenhum número pode ser dividido por ZERO!!")
except Keybo... |
f9c9e51b9fb7ad949fa8da98779e70022fdaaf2f | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_029.py | 317 | 4.0625 | 4 | # Mostra o valor da multa de um carro que passou do limite de 80KM/h
speed = float(input("Qual a velocidade do carro? = "))
if speed > 80:
value = (speed - 80) * 7
print(f"Você foi multado em R$ {value:.2f}!")
else:
print("Parabéns, você tá dentro do limite de velocidade!")
print("Fim do Programa")
|
bfc05c131b3f0a6c17b2c6d58cd9347b291dfc2e | emeraldtrejo/python | /try and except | 363 | 3.859375 | 4 | #!/usr/bin/env python3
def character_frequency(filename):
"""Counts the frequenct of each character in the given files. """
# First try to open the file
try:
f = open(filename)
except OSError:
return None
characters = {}
for line in f:
for char in line:
characters[char] = characters.get(char,... |
5404fb63d5f7bdc33bfd438a26997b79cdae0e7c | KingGenius5/Tech-Int-Prac-Prob | /complexity-analysis/long_palindrome.py | 526 | 4 | 4 | """
Using the same example that was used for the variable tables, we can see here that this
function has a time complexity of O(n^2) due to its nested loops giving it a quadratic running time.
"""
def long_pali(string):
substr = ''
for i in range(len(string)):
for j in range(len(string), i, -1):
... |
05c36d2fdd77e8e7428bf3af8925ed81f6a0a86a | JudoRooster0206/PythonStuff | /Tutorials/ForLoop.py | 195 | 3.78125 | 4 | nums=[1, 2, 3]
print(nums)
i=0;
for index in nums:
k=nums[i]
k+=1
nums[i]=k
i+=1
print(nums)
for index in range(1,6):
print("This is sentence number {} ".format(index))
|
aae9d0e37d61d9e1ea4eb77b98bc1e04d2cabba0 | JudoRooster0206/PythonStuff | /Challenges/Chapter 9 Challenges/Chapter9Challenges.py | 830 | 3.671875 | 4 | import os
import csv
print("\nChallenge 1:")
path=os.path.join("C:", "\\Users", "nicko", "OneDrive", "Documents", "SSH_Commands.txt")
with open(path, "r") as ReadFile:
print(ReadFile.read())
print("\nChallenge 2:")
answer= input("What's your favorite color?: ")
with open("Color.txt", "w") as File:
File.write(... |
8a6824b85d0579acb0ba2b9dae3a86ac27487c4f | korhanmd/sdcnd-search-quizzes | /first_search_program.py | 2,083 | 3.84375 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'... |
810e9b7a1d47e4c5e19b452bb3ecda92a5cd79d1 | zerojpyle/learningPy | /ex19_practice.py | 590 | 4.15625 | 4 | # define a function to do some math
# I'm trying to find 10 ways to run a function
def my_calc(number1, number2):
print(f"First, {number1} + {number2} = {number1 + number2}!")
print(f"Second, {number1} x {number2} = {number1 * number2}!")
print(f"And that's it! Come back later and maybe you'll get more.\n")... |
ea825b27fe780710ee9520c77bc7bdd9b69b6515 | zerojpyle/learningPy | /ex6.py | 887 | 4.4375 | 4 | # define variable with a number
types_of_people = 10
# define a variable as a literal string
x = f"There are {types_of_people} types of people."
# define a couple strings as variables
binary = "binary"
do_not = "don't"
# define a variable as a literal string
y = f"Those who know {binary} and those who {do_not}."
# pr... |
4508df8800ebc2a352753418b8134d816aa19f4c | HoNam007/HoHaiNam-Fundamental-C4E23 | /session4/Homeworks/EX1.2.py | 321 | 3.796875 | 4 | sizes = [5, 7, 300, 90, 24, 50, 75]
print("Hi, my name is Nam and these are my sheep sizes\n", sizes)
maxx = max(sizes)
print("My biggest sheep has size:", maxx)
x = sizes.index(maxx)
sizes[x] = 8
print("After shearing\n", sizes)
for i in range(len(sizes)):
sizes[i] += 50
print("One month has passed\n", sizes) ... |
729de129e75780ad8a566b3c28cbada876884fe0 | HoNam007/HoHaiNam-Fundamental-C4E23 | /session1/Homeworks/turtle2.py | 112 | 3.546875 | 4 | from turtle import *
speed(0)
shape(“turtle”)
for i in range (4):
forward(200)
left(90)
mainloop()
|
9384fa0529962b3defe465824e4c158b01310ea2 | HoNam007/HoHaiNam-Fundamental-C4E23 | /session1/Homeworks/Q&A.py | 487 | 3.75 | 4 | print("Q: How to check a variable's type?")
print("A: we use type() function")
print()
print("Q: in what cases, you will get SyntaxError from the compiler telling you that some of your variables have invalid names? Can you give 3 different examples of invalid names?")
print("A: names which start with a number, or... |
08c59051610623931949723c5f18175df6cbd097 | HoNam007/HoHaiNam-Fundamental-C4E23 | /session2/D2/for_explain.py | 110 | 3.6875 | 4 | from turtle import*
Shape("turtle")
speed(0)
for i in range(50):
forward(100)
left(50)
mainloop()
|
1691e719ecf06fe3d87de7f50347f85912b94b0d | fuzhanrahmanian/python_euler | /special_pythagorean_triplet.py | 280 | 4.0625 | 4 | import numpy as np
def pythagorean_triplet():
for a in range(1, 1001):
for b in range(a+1, 1001):
c = np.sqrt(a**2 + b ** 2)
if a + b + c == 1000.0:
x = a * b * c
break
return x
print(pythagorean_triplet()) |
70794e47a1f79b92bb5e3b084d4f39118666592c | SangheonOhWDC/neko | /neko/layers/base.py | 6,796 | 3.734375 | 4 | from abc import abstractmethod, ABC
from ..initializers import get_initializer
class Model(ABC):
def __init__(self, backend=None):
"""
Args:
backend: backend object
"""
self.parameters_dict = {}
self.initializer = None
self.initialized = False
... |
0a0c6c4bf139a100f1a50389ad91c8791b526053 | MigeloR/Catalogador | /pkmn.py | 2,567 | 4.09375 | 4 | '''el resultado es un documento en sql que sube UNA LINEA de info a la db
etapas:
1) nombre del pkmn en tabla pokemon
2) asociacion del pkmn con sus tipos en pkmn_tipos
2.1) agrega un tipo
2.2) pregunta si tiene segundo tipo
2.2.1) agrega segundo tipo
3) imprime el documento
la información debe agregarse a la lista da... |
0f5fb318ce86b2f7be8b7f7581ed7f572916617a | AP-Skill-Development-Corporation/Python-Students-PVP-03-08-2020 | /package/Module.py | 196 | 3.75 | 4 | # Even or odd
def even(n):
if n % 2 == 0:
return "Even"
return "Odd"
def unique(l):
li = []
for i in l:
if l.count(i) == 1:
li.append(i)
print(li) |
f4237699f37e3e90f5e14b608729732ba4c8d382 | 2997ms/Competitive-programming-problems | /ProjectEuler/57.py | 298 | 3.515625 | 4 | def main():
up = 1;
down = 2;
ans = 0
for i in range(0, 1000):
res = up + down;
if(len(str(res)) > len(str(down))):
ans+=1
up = down*2 + up
tmp = up
up = down
down = tmp
print ans
if __name__ == '__main__':
main() |
9b8e4958c14910a7e82b6e31de8c203adaeec9f0 | praak/think_python | /chapter7/7_4.py | 338 | 4.03125 | 4 | import math
# Using "eval" function on a loop to check different python functions and variable types.
#evaluate things. :)
def eval_loop():
print 'type "done" to end loop'
while True:
print '>',
userInput = raw_input()
if userInput == 'done':
break
print eval(userIn... |
263486d8994eed386e885f539f2d9e6733973b11 | praak/think_python | /chapter6/6_6.py | 884 | 4.15625 | 4 | # Palindrome
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
# Part 1:
# a = 'aaa'
# print a
# print 'first: ' , first(a)
# print 'middle: ' , middle(a)
# print 'last: ' , last(a)
# Part 2:
def is_palindrome(stringArg):
if (first(stringArg) == ... |
4b415851317bed67d12064f2f3f952f482c3aa51 | YTwho/learn_python_the_hard_way | /ex17.py | 771 | 4 | 4 | # copy one file to another
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
in_file = open(from_file)
indata = in_file.read()
print(f"The input file is {len(indata)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")... |
7a5514db341083026581cecba91d25a982780f20 | MacMacky/Python-Exercises | /codingbat/list2.py | 1,097 | 3.59375 | 4 | def sum13(nums=[]):
total = 0
lenNums = len(nums)
if lenNums == 0:
return 0
else:
i = 0
while i < lenNums:
if nums[i] != 13:
total += nums[i]
i += 1
else:
i += 2
return total
def has22(nums=[]):
... |
c3bbce3c82b056af7a4eba66f8686ee4e1226f67 | MacMacky/Python-Exercises | /codingbat/string2.py | 1,266 | 3.8125 | 4 | from re import findall
def count_hi(string):
return len([i for i in range(len(string)) if string[i:i+2] == 'hi'])
def end_other(a="", b=""):
lenA = len(a)
lenB = len(b)
return True if a[lenA-3:lenA].lower() == b[lenB-3:lenB].lower() else False
def double_char(string=""):
lens = len(string)
... |
7fd028a25f765483475383904efea714780c24be | yjiao1213/python-leetcode-offer | /剑指offer66题_pyhton实现/24_ReverseList.py | 981 | 3.875 | 4 | # -*- coding:utf-8 -*-
'''
输入一个链表,反转链表后,输出链表的所有元素。
三指针法
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def ReverseList(self, head):
if not head:
return None
if head.next == None:
return he... |
f66d92c20c0729f65a861d57476b50b04a26cea7 | yjiao1213/python-leetcode-offer | /剑指offer66题_pyhton实现/03_01_DuplicationInArray.py | 1,393 | 3.640625 | 4 | '''
找出数组中重复的数字
在一个长度为n的数组里所有数字都在0~n-1的范围内,数组中某些数字是重复的,
但不知道有几个数字重复了,也不知道重复了多少次
找出任意一个重复的数字
'''
# 使用哈希表解决
# 时间复杂度O(n),空间复杂度O(n)
class Solution1():
def solve(self, list1):
dic = dict()
res = -1
for item in list1:
if item in dic.keys():
res = item
... |
796bae6bb1a2a83bcc9f76bc5b18f8414eb0ed77 | yjiao1213/python-leetcode-offer | /剑指offer66题_pyhton实现/13_RobotMove.py | 2,098 | 3.546875 | 4 | # -*- coding:utf-8 -*-
'''
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,
但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
'''
class Solution:
def moving_count(self, threshold, rows, cols):
if threshold<0 or rows<0 o... |
2a2cfaedb06f7b9ec721a8550fd4b229f65c1319 | yjiao1213/python-leetcode-offer | /leetcode_top100_liked/Add_two_numbers.py | 1,154 | 3.90625 | 4 | #You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#Examp... |
b2caca67296912a7d9c9bac5edca79d1ba3e5bea | panfeng3141/python2016-12-29 | /ex13.py | 493 | 3.625 | 4 | # -- coding: utf-8 --
#modules模组 libraries库 argv参数 unpack解包
#执行命令 python ex13.py argv1 argv2 argv3
from sys import argv
a,b,c,d= argv
print "The script is called:", a
print "Your first variable is:", b
print "Your second variable is:", c
print "Your third variable is:", d
# 在终端运行会遇到问题,解决方法详见: https://www.zhihu.co... |
ec4f8c205e54b45c393dad1de1b48ceaa7f7ba0c | Wang-Guosheng/GaussianDistribution | /dist/source/gaussianRand.py | 943 | 3.796875 | 4 | # Generating independent standard normally distributed random number
# using Box-Müller Method.
from random import random as ran
from math import sqrt, log, pi, cos, sin
from statistics import mean, stdev
def gaussianRand(mu, sigma):
""" Two independent uniformly distributed random variables xi1 and xi2 become
tw... |
afbc2ba42d4b6c05d1bcfe536daecc0bc2c76128 | OlegZharkov/all_pangolin | /scripts/date-changer.py | 962 | 3.546875 | 4 | import argparse
import csv
from datetime import datetime
arguments = argparse.ArgumentParser(
description='Read a TSV file and compress in into a JSON with indexed key '
'storage. This assumes a sufficient degree of field value '
'repetitions'
)
arguments.add_argument(
'input... |
cefea503a419d31d29fb9cfc0c6b9424e5d91227 | tarpedro/random_dice_roller | /dice_roller.py | 1,020 | 3.59375 | 4 | import random
import os
import subprocess as sp
def clear():
os.system('clear')
def Roll_dice(number_of_rolls):
for i in range(0, number_of_rolls):
number = random.randint(1,6)
print(number)
play_again = input("do you want to play again? (y/n): ")
if play_again == "y":
clear()
... |
1b1777c912b82e59913ab122b6169b16785f1f88 | lucgiffon/traducteur | /model.py | 4,210 | 3.703125 | 4 | #!/usr/bin/python3
import math
import sys
def count_unigram_from_corpus(words):
"""
Récupère les nombres d'occurence de chaque mot.
"""
counted_unigrams = {}
for word in words:
if word not in counted_unigrams:
counted_unigrams[word] = 1
else:
counted_unigrams[word] += 1
return counted_unigrams
def pr... |
62ba1c6d1eedafb615cf70e8898fc3aef6cec354 | bartoszgajda55/PythonPlayground | /tuples_sets.py | 665 | 4.09375 | 4 | # A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# Create tuple
fruits = ("Apples", "Oranges", "Grapes")
# fruits2 = tuple(("Apples", "Oranges", "Grapes"))
# Single value tuple (needs trailing comma)
fruits2 = ("Apples",)
# Can't change a value
# fruits[0] = "Pears"
# Delete tu... |
2c467b3b2e736905086e4a012d733b583b7b3212 | amani2001/algorithm_study | /Hour_secretary.py | 3,239 | 3.84375 | 4 | # coding: utf-8
# author: amani2001
# 钟点秘书
import random
# 定义秘书类
class Secretary:
def __init__(self,name):
'''
初始化秘书
:param name:
'''
self.__name = name
self.meeting_list = []
def init_meetings(self, meeting_count, day_start_time, day_end_time):
'''
... |
37cbaaf0ded438d99d9a015e8d33bee20c2d515e | Mastermindpk/Raymobtime | /Python_codes/readAllEpisodeData.py | 1,051 | 3.578125 | 4 | import numpy as np
import h5py
import readArrayFromHDF5 as rah
'''function allEpisodeData=readAllEpisodeData(fileName)
Read all episode data within given file. Returns a data structure with all channels, scenes and rays. Each row of rays has a struct with 7 or 8 fields: path_gain, timeOfArrival, departure_elevation, de... |
e328d392ba043448b20bdfd11316871a3e77e9f7 | DonaldPG/PyTAAA | /functions/CheckMarketOpen.py | 1,583 | 3.65625 | 4 | import datetime
###
### Perform a check to see if the stock market is open
### - purpose is to stop calculating and sending emails when nothing has changed
###
def get_MarketOpenOrClosed( ):
import urllib
import re
base_url = 'http://finance.yahoo.com'
content = urllib.urlopen( base_url ).read()
... |
f2ba7e89f0bc6aa18ea4155b9957ae141c699ee0 | pipilugao/learn | /Python/12.py | 469 | 3.765625 | 4 | # 判断101-200之间有多少个素数,并输出所有素数。
#
# 判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。
flag = 0
arr = []
for i in range(101,201):
for j in range(2,i):
if i % j == 0:
flag = 1
break
if flag == 0:
arr.append(i)
else:
flag = 0
print('101-200间的素数共计:', len(arr))
p... |
ea64675681ec202fc0227a3acc828dec50972741 | zhenyong97/leecode_learning | /question2两数相加/normalsolution.py | 832 | 3.671875 | 4 | class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
add = 0
l3 = ListNode(0)
node = l3
while l1 or l2:
cur = ListNode(add)
if l1:
cur.val += l1... |
809069c55efebc2d7dfaf3d3edf9daee1c5f5b49 | samensah/Neuroscience-Lab | /LV.py | 1,293 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 25 13:57:47 2015
@author: emma
Example of use of odeint for system of equations.
Here we solve the Lotka-Volterra system for predator (y), prey (x)
dx/dt = ax-bxy
dy/dt = cxy - dy
or written as
dY/dt = F(Y,t)
where Y = [x,y]
and F(Y,t) = [ax-bxy,cxy-dy]
"""
from _... |
595f970414bf44a3985d8c51a894fb451d51e8d6 | dc-carrolls/a-level-python-code-2021 | /pygame/02-Controllers/oop/my-first-class.py | 1,679 | 3.78125 | 4 | import pygame
# -- Global Constants
# -- Colours
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (50,50,255)
YELLOW = (255,255,0)
RED = (255,0,0)
# -- My Classes
class Ball():
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
keys = pygame.key.get_pressed()
## - the u... |
3e20e0a5a7a2030cf0ad662f3895e470f2649801 | emlam/oo-melons | /melons2.py | 1,558 | 4 | 4 |
class AbstractMelonOrder(object):
""" You fill in the rest """
def __init__(self, species, qty, tax, order_type = "domestic", country_code = None):
"""Initializing a melon order"""
self.species = species
self.qty = qty
self.shipped = False
self.base_price = 5
... |
4670d5663f07fdced60227652185541d491e956d | Souvikdeb2612/DataStructures-Algorithms | /Algo/Recursion1.py | 282 | 3.953125 | 4 | def factorialRecursive(n):
if n == 1:
return 1
return n*factorialRecursive(n-1)
def factorialIterative(n):
factorial = 1
for i in range(1, n+1):
factorial = factorial*i
return factorial
print(factorialRecursive(4))
print(factorialIterative(5))
|
836677c5ae299ec6769bdb91285605297e76f2d7 | Souvikdeb2612/DataStructures-Algorithms | /DS/array2.py | 110 | 3.734375 | 4 | A = [1, 5, 8, 20, 24]
B = [0, 5, 10, 16, 32]
def merging(A, B):
return sorted(A + B)
print(merging(A, B)) |
0499632eb558820a8ac124805aa8a433a4b56d0a | shinjoe/Snake-Study | /Block.py | 1,113 | 3.9375 | 4 | import pygame
class Block:
""" A class that represents a drawable block on the screen. """
def __init__(self, row, col, color, boundary_offset, rect_size, direction):
self.row = row
self.col = col
self.color = color
self.boundary_offset = boundary_offset
self.... |
a0f73784a1ad1a2971e71c9844e3d48c9eeed9a1 | cyber-holmes/Centimeter_to_meter-and-inches_python | /height_cm.py | 418 | 4.4375 | 4 | #Goal:Convert given Height from Centimeter to Meter and Inches.
#Step1:Take the input.
height = input("Enter the Height in Centimeter: ")
#Step2:Calculate the value of Meter from Centimeter.
meter = height/100.0
#Step3:Calculate the value of Inch from Centimeter.
inch = height/2.54
#Step4:Print the Height in Meter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.