blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
032107e7803703a94b9a81e1508bdaa3030e2c5c | dxe4/project_euler | /python/7.py | 472 | 3.8125 | 4 | '''
Also read:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Probably better than bforce?
'''
def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
else:
for i in range(2, int(n / 2) + 1, 1):
if n % i == 0:
return False
return True
... |
ae5807bc71a45643fa6ac2c830a6aa75e60f31ee | adamorhenner/Fundamentos-programacao | /exercicios/exercicio-8.py | 220 | 4.03125 | 4 | #8. Faça um programa que lê um número inteiro, o incrementa em 1 e exibe o resultado
print("====== Incremento do numero ======")
x = (int)(input("Digite um numero inteiro"))
x += 1
print("o valor do incremento eh", x) |
719cb4e6b2c0042354680dbf019a58ff4dae652b | steveSuave/practicing-problem-solving | /turtle-graphics/pyth-with-angle-input.py | 923 | 3.9375 | 4 | import turtle
import math
def square(side):
for i in range(4):
turtle.forward(side)
turtle.left(90)
def pyth(length, depth, angle):
# make sure the output will resemble a tree
if angle>83: angle%=83
if angle<0 : angle=-angle
if angle<7 : angle*=7
square(length)
if dep... |
e6960a989543cec8f79c0ae759ef03e1d44036d2 | gigix/machine-learning-specialization | /course-3/module-3-probability.py | 334 | 3.5 | 4 | import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
for n in [2.5, 0.3, 2.8, 0.5]:
print('{0} - {1}'.format(n, sigmoid(n)))
print sigmoid(2.5) * (1 - sigmoid(0.3)) * sigmoid(2.8) * sigmoid(0.5)
print 2.5 * (1 - sigmoid(2.5)) + 0.3 * (0 - sigmoid(0.3)) + \
2.8 * (1 - sigmoid(2.8)) + 0.5 * (1 - ... |
1e6b3e564091cd78959dbe936040dd9aa9365f3d | Ph0enixxx/PyDict | /App.py | 152 | 3.53125 | 4 | from Data import Data
def display(Data):
print("type the word:",end="")
print(Data(input()))
if __name__ == '__main__':
while True:
display(Data) |
9274ea0543c6f61d6a056d2ee5f176d6cf7d5313 | BillyDevEnthusiast/Programming-with-Python | /Python Fundamentals/Regular Expressions/02_match_phone_number.py | 146 | 3.5625 | 4 | import re
pattern = r"(\+359-2-\d{3}-\d{4}|\+359 2 \d{3} \d{4})\b"
text = input()
phones = re.findall(pattern, text)
print(", ".join(phones))
|
d85f9cbccb242a6912e8e3a17d2492eb90719744 | nehavari/beginnerspython | /src/sorting/quicksort.py | 1,409 | 4.09375 | 4 | """
Time Complexity: Worst case time complexity is O(N2) and average case time complexity is O(N*logN)
Auxiliary Space: O(1)
"""
import random
def partition(start, end, nums):
"""
output of partition is =>
1. pivot has moved to its correct position in sorted array
2. all the elements left to pivot are... |
b57ccfc7086c44bbfffc5cac57fd4fc1acb0a770 | misshebe/PycharmProjects | /s14/day3/decode.py | 214 | 3.828125 | 4 | #python3.x
#-*- coding:utf-8 -*-
# a = "正视你的邪恶" #现在编码是unicode 因为python3默认 不能指定utf-8就能看中文
a = "正视你的邪恶".encode("utf-8") #unicode转utf-8编码
print(a) |
3794bea1700068e702b0605bef26f1c520682980 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2901/49361/245588.py | 265 | 3.859375 | 4 | def solution(number):
(number, flag) = divmod(number, 2)
while number:
(number, remainder) = divmod(number, 2)
if remainder == flag:
return False
flag = remainder
return True
num = int(input())
print(solution(num))
|
0836c66cacbf05f6cc2fee35594bbdd9fba71318 | xZoomy/word2vec-korea | /codes/extractASM.py | 1,122 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 14:46:36 2019
@author: jlphung
"""
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:ret... |
62e038c21bf2868aa979ff7689b01aade8db4bbb | yukraven/vitg | /Archive/Sources/Tools/Instruments.py | 1,037 | 3.671875 | 4 | import random
from Archive.Sources.Tools.Exceptions import ValueIsNotProbabilityError
def getRandFromArray(array, withWhat):
""" Returns a random index from an array of probabilities """
if type(array) is not list:
raise TypeError
if len(array) == 0:
raise ValueError
if withWhat == "w... |
fc18c7a92523d66d7f79d3cf273d18d97335f11c | happinessbaby/Project_Euler | /fib1000.py | 248 | 3.59375 | 4 | fib = {}
def find_fib():
fib[0] = 1
fib[1] = 1
n = 2
fib_length = 0
while fib_length < 1000:
fib[n] = fib[n-1] + fib[n-2]
fib_length = len(str(fib[n]))
n += 1
return n
print(find_fib())
|
e48be50d8c3ec2b4cc01d89ada1a208859db735e | FelipeMacenaAlves/Project_Euler | /Even_Fibonacci_numbers/Even_Fibonacci_numbers.py | 319 | 3.78125 | 4 | def fibonacci(n,limit=None):
data = [1,2]
if limit:
while data[-1] < limit:
data.append(data[-1] + data[-2])
else:
data = data[:-1]
else:
if n < 3:
return data
for element in range(n-2):
data.append(data[-1] + data[-2])
return data
print(sum(filter(lambda x: x%2 == 0,fibonacci(None,4000000)))) |
2b1afbec0bb98c6cf3d244cbc263687a574cf8fb | a100kpm/daily_training | /problem 0083.py | 751 | 4.09375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
'''
class Node:
def __init__(self,data):
self.l... |
bbcbe86d5f902fed12113aa2ff2cafdb7fe9019b | Gayatr12/Data_Structures | /linklist.py | 2,044 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 16:20:25 2020
@author: STSC
"""
#LinkedList
# creating LinkedList and printing
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initializ... |
33eccc02fbbca665a68d4ddea024269decfd9666 | westgate458/LeetCode | /P0498.py | 1,654 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 14:03:42 2020
@author: Tianqi Guo
"""
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
# trivial case
if not matrix: return []
# initial pos... |
2012b904e6af6533751d661a205d538aaa187153 | bingli8802/leetcode | /0958_Check_Completeness_of_a_Binary_Tree.py | 814 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: boo... |
4361e0152eaf364f27e799fed182118a16e586e0 | jinger02/testcodes | /exer5_9.py | 1,105 | 4.125 | 4 | #Exercise 1&2: Write a program which repeatedly reads numbers until the user enters "done".
#Once "done" is entered, print out the total, count, and average of the numbers.
#if the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.... |
7f2927ae1943864e1c0fcafd2a258e208b59f234 | talt001/Java-Python | /Python-Fundamentals/Loan Calculations/combs_loan_calculations_program.py | 1,840 | 4.3125 | 4 | #Step 1 write a python function that will calculate monthly payments on
# a loan.
#Step 2 pass the following to your function
#Principle of $20,000, with an APR of 4% to be paid in
# 1.) 36 months
# 2.) 48 months
# 3.) 60 months
# 4.) 72 months
#Step 3 include code for user supplied loan terms and comment out... |
fb44cad292742f3bf54372af37d96e3b39f4bfb5 | cbhust8025/primary-algorithm | /LeetCode/python/2_addTwoNumbers.py | 1,362 | 3.859375 | 4 | # Definition for singly-linked list.
import string
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def show(self, a):
while(a):
print a.val,
a = a.next
class Solution(object):
def addTwoNumbers(self, l1, l2):
... |
9f8dd7132bc87b76549886774eea5a750fdeea17 | FarhatJ/HackerRank | /10DaysOfStatistics/Day 4- Binomial Distribution II.py | 1,379 | 3.90625 | 4 | # Objective
# In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.
# Task
# A manufacturer of metal pistons finds that, on average, of the pistons they manufacture are rejected because they are incorrectly sized. What ... |
f4638e39bb78bcb942270ad7334d4e6ebdb4096d | sjwar455/PythonCodeChallenges | /diceSim.py | 1,178 | 3.84375 | 4 | ##############################################################################################
# File: diceSim.py
# Author: Sam Wareing
# Description: script to determine probability of dice rolls using monte carlo simulation
#
#
#
##################################################################################... |
ae61084ed337666de0d355ec54bb404ca201fc4d | pbrandiezs/python-ex15 | /Ex15.py | 158 | 4.125 | 4 | the_string = input("Enter a long string? ")
result = the_string.split(" ")
backwards_result = result[::-1]
reverse = " ".join(backwards_result)
print(reverse) |
d2154f94c4375f395ef1f1b027ee3872a4eb0d52 | shanminlin/Cracking_the_Coding_Interview | /chapter-4/5_validate_BST.py | 4,183 | 3.90625 | 4 | """
Chapter 4 - Problem 4.5 - Validate BST
Problem:
Implement a function to check if a binary tree is a binary search tree.
Solution:
1. Clarify the question:
Repeat the question: We are given a binary tree, and we need to check whether it is a binary search tree.
Clarify assumptions: - Definition of a BST:
... |
b22e269c2c5c02aff496d9570e9e934292973656 | andreaorlando333/EserciziTPSIT | /Python/Es_DizionarioFunzioni.py | 478 | 3.765625 | 4 |
# Esercizio con Dizionario Funzioni
# Programma per somma/moltiplicazione
def somma(a, b):
return a+b
def moltiplicazione(a, b):
return a*b
dizionario_funzioni = {0: somma, 1: moltiplicazione}
def main():
print("Seleziona un'opzione:")
val_utente = int(input("0. Somma \n1. Moltiplicazione:\n\nInput: "))
a =... |
15e554a4e61cfb50460a99421ca822b809f150a5 | rjadmscpfl/HelloGitHub | /while-for-range.py | 1,133 | 3.875 | 4 |
#num = 0
#while num <10:
# print(num)
# num += 1
#for i in range(1, 101):
# print(i)
#score_list = [90, 45, 70, 60, 55]
#num = 1
#for score in score_list:
# if score >= 60:
# result = "Pass"
# print("Num {} is Pass".format(num))
# else:
# result = "Fail"
# print("Num {} is... |
807d884981d42182ab9837f8979e4df698594c4c | kkejian/pytests | /p6/p6e09.py | 723 | 3.6875 | 4 | class Statement:
def __init__(self):
self.line = ''
def state(self):
print('%s:\t%s' % (self.__class__.__name__, self.line))
class Parrot(Statement):
def __init__(self):
self.line = None
class Customer(Statement):
def __init__(self):
self.line = '"That\'s one ex-bird!"'
... |
f49d6c449768f2d678d17dc06586864932bdd69f | helloarthur0623/happy_code | /weather_1to100/pandas_perfect.py | 3,909 | 3.59375 | 4 | # 讀取 CSV File
import pandas as pd # 引用套件並縮寫為 pd
import time
df = pd.read_csv('2014-08-30.csv',encoding='utf-8')
print(df)
df= df.dropna()
print(df)
df = df.drop(columns=['Unnamed: 0'])
print(df)
df.index = range(len(df))
df=df.reset_index()
df=df.drop(['index'],axis=1)
print(df)
def column_filter(s):
return s.sp... |
435ebd93fb5f8bc00a36504995eb64048d426917 | valbertoenoc/basic-datastructures-python | /ArrayQueue.py | 1,614 | 4.03125 | 4 | class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty queue."""
self.m_data = [None]*ArrayQueue.DEFAULT_CAPACITY
self.m_size = 0
self.m_front = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self.... |
3a3017f8a2bedcf845f8d1006ed30853e575ac8e | crebiz76/checkio | /python/HOME/LongRepeat.py | 832 | 3.921875 | 4 | def long_repeat(line: str) -> int:
"""
length the longest substring that consists of the same char
"""
# your code here
ret = 0
buf = ''
Max = 0
linelist = list(line)
for i in linelist:
if i == buf:
ret += 1
if ret >= Max:
Max = ret... |
e348d6a1651563b8a1d2b6959cc4c01077fc9dd7 | guilmeister/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 440 | 3.984375 | 4 | #!/usr/bin/python3
def text_indentation(text):
if isinstance(text, str) is False:
raise TypeError("text must be a string")
x = 0
while x < len(text):
if text[x] == '.' or text[x] == '?' or text[x] == ':':
print(text[x], end="")
print("")
print("")
... |
b8d58f0ea95acbc38f8f4c743e0f23355d5f04c5 | engenmt/Lingo | /main.py | 2,224 | 3.796875 | 4 | from setup import words
def response(guess, correct):
"""Return the information received upon guessing the word `guess` into the word `correct`."""
guess = list(guess)
correct = list(correct)
known = []
misplaced = []
for idx in range(5):
if guess[idx] == correct[idx]:
know... |
7d98121dc7ec94ef176697800b5473db958b00ae | kimgwanghoon/openbigdata | /01_jumptopy/chap03/135.py | 193 | 3.546875 | 4 | #coding:cp949
print("<< α ver1>>")
for i in range(2,10):
print("**%d**"%i)
for j in range(1,10):
print("{0}*{1}={2}".format(i,j,i*j))
print('')
|
bfe1f48e4da80437fbf932ed5200ab18bdb089fc | bobcaoge/my-code | /python/leetcode_bak/925_Long_Pressed_Name.py | 799 | 3.65625 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if set(name) != set(typed):
return False
index_of_name = 0
length = len(na... |
cbe336705a436b7b704858273a80127ece50a0c2 | chl218/leetcode | /python/stuff/0231-power-of-two.py | 532 | 4.09375 | 4 | """
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: ... |
73340653ea02720c283edddc5d5787b1036b8505 | algorithm005-class01/algorithm005-class01 | /Week_02/G20190343020234/LeetCode_49_0234.py | 578 | 3.671875 | 4 | import collections
class Solution:
def groupAnagrams(self, strs):
# res = collections.defaultdict(list)
# for s in strs:
# count = [0] * 26
# for c in s:
# count[ord(c) - ord('a')] += 1
# res[tuple(count)].append(s)
# return res.values()
... |
85f24ce855ad72f3e1dbee6f8e5529be951d92f5 | tiaedmead/Data_24_repo | /UnitTesting_TDD/testing.py | 324 | 4.125 | 4 | # from addition import *
#
# if addition(1, 2) == 3:
# print("addition function working as expected")
# else:
# print("addition function not working as expected")
#
#
# if subtraction(3, 2) == 1:
# print("subtraction function working as expected")
# else:
# print("addition function not working as expect... |
a114c079e28f7cbb0fb996646f7e551c64ab71a7 | UkrainianProgrammer/Client-Server-Architecture | /PythonModel/client.py | 520 | 3.546875 | 4 | # Written by Oleksandr Sofishchenko
# Simple socket programming in Python.
# Server socket does not receive any data. Instead, it produces
# client sockets.
# client.py
import socket
# create a socket object
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# fetching local machine's name
server_address = ("l... |
60001fb88d93af6ab02030383ff69de4df7cc70c | ktyagi12/Driving_License_Initial_Validations | /DLApplication.py | 836 | 3.921875 | 4 | # Driving License Application Form
print '*' * 150
print '\t\t\tSaarthi Driving License Application'
print '\t\t', '*' * 150
vision_thres = 6
fname = raw_input('Enter your first name: ')
lname = raw_input('Enter your last name: ')
year_birth = input('Enter your year of birth: ')
vision = input('Enter your eyesight (eg... |
f0583af002084271bf6ab0b110162b3c5c7226f7 | barbieauglend/Learning_python | /Lvl01/Ladebalken/ladebalken_2.py | 554 | 3.515625 | 4 | #python 2.7 and python 3.5
import sys
import time
def progressbar(it, size):
count = len(it) + start
def _show(_i):
x = int(size * (_i + start) / count)
sys.stdout.write("[%s%s] %i %s\r" % ("#" * x, " " * (size - x), _i + start, '%'))
sys.stdout.flush()
_show(0)
for i, item i... |
c835dddbcdc61682489a8bd025337e32238aad36 | Aniketgupta2007/prepinsta-top100-codes-python | /29.LargeAndSmall.py | 238 | 3.890625 | 4 | arr = list(map(int, input().split(" ")))
large = arr[0]
small = arr[0]
for i in range(1, len(arr)):
if arr[i] < small:
small = arr[i]
if arr[i] > large:
large = arr[i]
print('Smallest', small, 'Largest', large)
|
e9bd56303d5a025354a977cbf1fb5a286242fe3c | PedroMorenoTec/practica-examen | /2.1/lustros.py | 204 | 3.625 | 4 | nacimiento = int(input('Introduzca su año de nacimiento: '))
year = int(input('Introduzca el año en el que estamos: '))
lustros = (year - nacimiento)/5
print(f'Usted ha vivido {lustros} lustros') |
e33f738367bbe437122e2af2c242192a175e38b6 | OleksandrNikitin/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp-for-2021 | /day-4/main.py | 1,218 | 4.09375 | 4 | import secrets
rock = """
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
"""
paper = """
_______
---' ____)____
______)
_______)
_______)
---.__________)
"""
scissors = """
_______
---' ____)____
______)
__________)
(____)... |
9a3498f23f3dfaf3c7e86a57729913a132441f6d | ruidazeng/online-judge | /Kattis/cetiri.py | 218 | 3.625 | 4 | lst = sorted([int(x) for x in input().split()])
diff1 = lst[1] - lst[0]
diff2 = lst[2] - lst[1]
if diff2 > diff1:
print(lst[1] + diff1)
elif diff1 > diff2:
print(lst[0] + diff2)
else:
print(lst[2] + diff1) |
14f61595a5eac990a23c3593af3b580907d9e1e4 | KakaC009720/Ptyhon_train | /質數判斷.py | 212 | 3.890625 | 4 | n = int(input())
sum = 0
for i in range(1, n+1):
a = n%i
if a == 0:
sum = sum + i
else:
pass
if sum == n + 1:
print(n, "is prime")
else:
print(n, "is not prime") |
84ab6534c6eae23ff75049b2cc1a09701bac82c8 | nghiattran/playground | /hackerrank/palandir-degree/expand_the_acronyms.py | 1,408 | 4.03125 | 4 | dictionary = {}
def parse_abbr(entry, i):
i += 1
abbr = ''
while entry[i] != ')':
abbr += entry[i]
i += 1
return abbr, i
def parse_real(entry, abbr, i):
i -= 2
end_pos = i
stop = False
name = ''
uppercase_cnt = 0
while not stop and i >= 0:
name = entry... |
ae5f9e6524794939647ebbeebe7b7895bc99671a | coder-dipesh/Basic_Python | /labwork2/checking_item_in_list.py | 145 | 3.96875 | 4 | # Check wether 5 is in list of first 5 natural numbers or not.
# Hint List => [1,2,3,4,5]
list=[1,2,3,4,5]
if 5 in list:
print('It is there') |
b5942e81ce5c5d01d7ef94bfcc64f8c1261c16b1 | TapeshN/Portfolio | /Python1_CourseWork/HW03_TapeshNagarwal.py | 902 | 4 | 4 | #Tapesh Nagarwal CS100-H01
#1
a = 3
b = 4
c = 5
if a < b:
print('OK')
if c < b:
print('OK')
if a+b == c:
print('OK')
if a**2 and b**2 == c**2:
print('OK')
#2
if a < b:
print('OK')
else:
print('NOT OK')
if c < b:
print('OK')
else:
print('NOT OK')
if a+b == c:
print('OK')
else:
... |
7192425bcebb4b8772b5aa8f5ac6c76dcb2e0074 | RyanClement/100-Days-of-Code | /Day5/highest_score-day5.py | 508 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created: Apr 25 2021
@author: Ryan Clement
Day #5: Highest Score.
"""
# Can't change block: start
student_scores = input("Input a list of student scores ").split()
for n in range(0,len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# C... |
34649c24c99b0b69f182f5fe03939fe80e600af4 | Antikythera/SkriptJezici | /Practice/zadatak_11.py | 630 | 3.921875 | 4 | #!/usr/local/bin/python3
# Napisati Python funkciju check_duplicates koja kao parametar
# prima listu brojeva na osnovu kojih se proverava da li
# postoje duplikati. Funkcija treba vratiti True ili False
# vrednost u zavisnosti od toga da li se u listi nalazi duplikat
# nekog elementa ili ne.
#
# Primer:
#
# check_du... |
5443c5073db5bc1d670963c2881089e90a2da19e | NoirKomBatman/leetcode | /617.py | 1,156 | 3.984375 | 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 mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
... |
df31e3e3b7309e9b0594a09e8d107caced35d3f8 | nathannicholson/dominion | /Dominion Sim.py | 28,251 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 13:08:56 2020
@author: NNicholson
"""
import random
import shelve
class Game:
def __init__(self,game_name,card_dict,supply,trash_pile,players):
self.game_name = game_name
self.card_dict = card_dict
self.supply = supply
... |
0e99419b90d9bdaafa76ebbda14479182632f074 | dzieber/python-crash-course | /ch4/dimensions.py | 492 | 3.828125 | 4 | '''
chapter 4, Tuples
'''
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
# to copy a tuple into a list you have to cast it
temp_dimensions = list(dimensions[:])
print(temp_dimensions)
temp_dimensions[0] = 250
print(temp_dimensions)
# and it works the other way as well. Note that you don't need to make... |
43f1caa94b1a6e66ee5143314e66f9fa8b4fa190 | Williandasilvacode/Calculadora | /index.py | 1,064 | 4.34375 | 4 | print('\n <<------Calculadora Simples----->>')
print('+ Adição')
print('- Subtração')
print('* Multiplicação')
print('/ Divisão')
print('Presione a tecla "s" para encerra o programa!')
# (\n) faz uma quebra de linha
while True:
op = input('\n Qual operação deseja fazer? ')
if op == '+' or op =='-' or op =='*... |
72c6c1035e7eac46699d7b528415c3c567abec3c | prerna2896/Percept | /CreateDatabase.py | 2,293 | 4.25 | 4 | # A program to create the tables for the inventory database.
# There are 4 tables to store the data in the inventory.
# Table Users
# The username for the user
# The password for the user
# Table Students
# First Name of student
# Middle Name of student
# Last Name of student
# Age of student
# Univer... |
4dd4c5e53ac89e98f775616d4158f76c72da9dab | jsngo/hackbright | /week3/sweep-count.py | 986 | 4.0625 | 4 | # http://labs.bewd.co/putting-it-together/
import csv
days_counts = {
"Mon": 0,
"Tues": 0,
"Wed": 0,
"Thu": 0,
"Fri": 0,
"Sat": 0,
"Sun": 0,
"Holiday": 0
}
ordered_days = [
"Mon",
"Tues",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun",
"Holiday"
]
def day_counter()... |
9cded9d0208286821735967df6ad0172606b5024 | keivanipchihagh/Intro-to-ML-and-Data-Science | /Courses/MIT-OpenCourseWare/MIT-6.0001/Lecture 8 - Object Oriented Programming/My codes/Object Oriented Programming.py | 1,380 | 3.875 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_dif... |
59246d41af97e32e491bab6c3dc97bed24474815 | pipazi/leetcode | /index/2.py | 615 | 3.5625 | 4 | from util.ListNode import ListNode
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a = l3 = ListNode(0)
quo = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
res = x + y + quo
rem = res if r... |
838a43a53a5473563c2cf47dbcadf2e9ab5e87de | abhisheksahu92/Programming | /Solutions/93-Sentence from list of words.py | 1,060 | 4.15625 | 4 | # Recursively print all sentences that can be formed from list of word lists
# Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion?
# Example:
#
# Input: {{"you", "we"},
# {"have", "are"},
# {"sleep", "eat", "drink"}}
#
# Output:
# you hav... |
4182910fe564422cb6fbe07d5037f71b00219414 | hazzel-cn/leetcode-python | /80.py | 848 | 3.5625 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
j = 0
jcount = 0
for i in range(1, len(nums)):
if nums[i] == nums[j]:
jcount += 1
... |
0abbb4ed4b69676ee6d58292bb04153879c2cf64 | momentum-team-6/python-oo-money-matthewbenton224 | /blackjack.py | 547 | 3.734375 | 4 | SUITS = ["♥️", "♠️", "♣️", "♦️"]
RANKS = ["Ace", "J", "Q", "K", 2, 3, 4, 5, 6, 7, 8, 9, 10]
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'card is a {self.rank} of {self.suit}'
class Deck:
def __init__(self, suits, ranks... |
b4d19986fe7e9137c3b9bfcc97cfdaa073692160 | nbrahman/HackerRank | /02 30 Days of Code Challenges/Day11-2D-Arrays.py | 2,038 | 4.125 | 4 | '''
Objective
Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!
Context
Given a 6 X 6 2D Array, A:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in A to be a subs... |
33636ed7a66b1a87961c8f5c4e979606f77ba803 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/maths/is_strobogrammatic.py | 731 | 4.3125 | 4 | """
A strobogrammatic number is a number that looks
the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic.
The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
"""
def is_strobogrammatic(num):... |
dd47a473a78bee9e24b56cd91a7627f1ef6fb27d | maykkk1/curso-em-video-python | /exercicios/MUNDO 1/Condições (Parte 1)/ex032.py | 466 | 3.9375 | 4 | from datetime import date
x = int(input('digite o ano '))
if x == 0:
x = date.today().year
if x > 3:
r4 = x % 4
r100 = x % 100
r400 = x % 400
if r100 == 0:
if r400 == 0:
print('Esse ano é bissexto')
else:
print('Esse ano não é bissexto')
if r4 == 0 and r10... |
eab354b7e65ba7d8fd766e037f8e5e5097a37224 | rendersonjunior/UriOnlineJudge-Python | /1051_Taxes.py | 689 | 3.828125 | 4 | # Taxes
def main():
salary_taxes = [(0.00, 2000.00, 0.00),
(2000.01, 3000.00, 0.08),
(3000.01, 4500.00, 0.18),
(4500.00, 9999999999999.00, 0.28)]
salary_taxes.sort(reverse=True)
salary = float(input())
salary_tax = 0
for m... |
86d9214e5c4b4e43ab21b182cd28bd1769074592 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Interview_Questions/LogicMonitor/Reverse_strings.py | 2,298 | 4.34375 | 4 | """
Available Concepts :
1) slicing
2) reversed keyword
3) join keyword
4) list comprehension
"""
"""
Reverse a string
"""
def string_reversal_one(*args):
for input in args:
print('Original \t : ', input, '\nReversed\t : ', input[::-1], '\n' + '*' * 40)
def string_reversal_two(*args):
for test_stri... |
643d89e1ee42170a18a516e86e0f89b25e9c5977 | thanhdao/data_science | /histogram.py | 164 | 3.59375 | 4 | import matplotlib.pyplot as plt
numbers = [0.1, 0.5, 1, 1.5, 2, 4, 5.5, 6, 8, 9]
plt.hist(numbers, bins=3)
plt.xlabel('Number')
plt.ylabel('Frequency')
plt.show() |
6edcb3df883d5de2de49413dfd64a39c9c98b8e2 | danielsimonebeira/cesusc-lista1 | /exe26.py | 1,359 | 4 | 4 | # 26 - Faça um programa que receba duas listas e
# retorne True se são iguais ou
# False caso contrário,
# além do número de ocorrências do primeiro elemento da lista.
import random
def gera_lista(numero_lista):
lista = []
contador = 1
quantidade = random.randint(2, 9)
while contador < quantidade:
... |
edd8ae88bdb716c28936f6ba5eae0823e83962f7 | beenorgone-notebook/python-notebook | /py-recipes/mutilpe_dispatch-rock_paper_scissors.py | 2,049 | 3.65625 | 4 | # To explain how multiple dispatch can make more readable and less
# bug-prone code, let us implement the game of rock/paper/scissors in
# three styles.
class Thing(object):
pass
class Rock(Thing):
pass
class Paper(Thing):
pass
class Scissors(Thing):
pass
# First, a purely imperative version
d... |
03da09f98cc59fcd777c511991bf42e2869abdd6 | FronTexas/Fron-Algo-practice | /beautifuly.py | 2,871 | 3.59375 | 4 | def isOdd(n):
return n % 2 != 0
def beautifulSubarrays(a, m):
dp = [0 for i in range(len(a))]
dp[0] = 1
ans = 0
odd_counter = 0
for i in range(1,len(dp)):
if isOdd(a[i]):
if odd_counter + 1 > m:
ans += 1
odd_counter = m
dp[i... |
0d9d78880f6718a982379f6cff4cc7f9b0c08d0f | MrJouts/learn-python | /ch6/04.glossary2.py | 418 | 3.8125 | 4 | glossary = {
"string": "chain of characters",
"indentation": "left espace at the beginning of a line",
"if": "conditional clause",
"or": "comparicion operator",
"python": "Programming language",
"for": "loop through a list",
"dictionaries": "key value pair storage",
"list": "list of valu... |
e3fb2935b7a3453d1b42e6ad60f7dc4cd3ac0fef | Matheus-Novoa/Python-Scripts | /neural_network/neural_network.py | 1,693 | 4.15625 | 4 | import numpy as np
def sigmoid(x):
# Activation function: f(x) = 1 / (1 + e^(x))
return 1 / (1 + np.exp(-x))
def deriv_sigmoid(x):
"""Derivate of sigmoid: f'(x) = f(x) * (1 - f(x))
Args:
x (float): Sigmoid function argument
Returns:
float: Sigmoid function derivate
"""
... |
94df0b1a6e328cccbd94960edbe0db4ff8cb0c1d | BenjaminElifLarsen/PythonPratice | /class.py | 1,259 | 3.8125 | 4 | class TestingClass:
__privateValue = 4
_protectedValue = 3
def __init__(self):
self.__number = 5
def GetValue(self):
return self.__privateValue
def SetValue(self,value):
self.__privateValue = value
@property
def value(self):
return self.__number
@value.setter
def value(self, value):
... |
bd3e8d1670f528401a2a16088c26322131dce209 | suresh3870/WorkingWithPy | /addnumber.py | 106 | 3.6875 | 4 | # program to add
a=5
b=10
def add_number (x,y):
z= x+y
return z
c= add_number(a, b)
print(c) |
c0dc2e4ae61ca0653d8036521fc7859c86def1d0 | madeibao/PythonAlgorithm | /PartA/PyMapFunction2.py | 224 | 3.5625 | 4 |
m2 = [1, 2, 3, 4, 5, 6, 7]
print(list(map(lambda x: x+10, m2)))
# 结果为:[11, 12, 13, 14, 15, 16, 17]
res = lambda sex:"带把的" if sex == "男" else "仙女降世"
res2 = res("男")
print(res2)
|
015b5a144fa84b43ad034e6bc83cf5eafb48da5b | antrent/Cursos | /01_datos.py | 641 | 3.859375 | 4 | x = 'Hola'
print(x,type(x))
# Tipado dinamico
x = 34
print(x,type(x))
# Tipado estatico (OTROS LENGUAJES), no existe en Python
# Tipado float
x = 34.78
print(x,type(x))
# Tipado palabras reservadas
x = True
print(x,type(x))
x = False
print(x,type(x))
x = None
print(x,type(x))
# Tipos complejos
# listas, arrays, ... |
d088ee076b5ed33903bb8c3f93134443b2c73859 | rbadvaith/Hybrid-Ciphers | /autokey2.py | 1,058 | 3.96875 | 4 | ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
prin... |
1d72ca747228ee6fb74bce0bfc0eb597d156f620 | felipeonf/Exercises_Python | /exercícios_fixação/025.py | 383 | 4.125 | 4 | # Desenvolva um programa que leia um número inteiro e mostre se ele é PAR ou ÍMPAR.
stop = 'y'
while stop == 'y':
number = int(input('Write a number: '))
if number % 2 == 0:
print('This number is pair.')
else:
print('This number is odd.')
stop = input('Do you want to co... |
79da11b8d911fc21de9d192f398aa2c076dc0e72 | wujjpp/tensorflow-starter | /py/l2.py | 2,213 | 3.84375 | 4 | # 关键字参数
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
person('Jane', 20)
person('Jack', 20, city='Suzhou', job='Test')
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack'... |
f2584a67cc6b402b3475b565aaeb916db9593216 | rakheg/calculator | /prj2calculator.py | 1,626 | 3.890625 | 4 | import tkinter as tk
from tkinter import messagebox
mainWindow=tk.Tk()
mainWindow.title("calculator")
heading_label1 = tk.Label(mainWindow,text="first number")
heading_label1.pack()
first_number=tk.Entry(mainWindow)
first_number.pack()
heading_label2= tk.Label(mainWindow,text="second number")
heading_lab... |
03db618b9ddc44eb97cc4e85b0e827c461a47509 | joy3968/Algorithm_Python | /stack.py | 429 | 4.09375 | 4 | ## Stack Class
class stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
# 비어있는지 확인하는 메서드
def isEmpty(self):
return not self.items
stk = stack()
print(stk)
print(stk.isEmpty()... |
841d906493793e8157b061633dff9e579bd1b2de | JoshW-G/peaDetection | /xml_to_csv.py | 1,299 | 3.59375 | 4 | ##
#Author: Josh Gardner
#Parses XML data into a pandas DataFrame to be saved in a csv
#
##
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import argparse
import csv
def xml_to_csv(path):
#function to parse xml files and extract the data to a dataframe
xml_list = []... |
327fe87813a71f0e02fffeaf9d8442c32185ce69 | Olddays/myExercise | /Python/LeetCodeTest/lc098_ValidateBinarySearchTree.py | 1,329 | 3.8125 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root:
dataSet = []
self.doCheck(root, da... |
db95fe3975f545a0554e37739177481eabc14f19 | rakietaosx/osx | /pprogram_ulamki.py | 251 | 3.75 | 4 | print("Program ulamki Olafa.")
while True:
licznik = input("wpisz licznik:")
mianownik = input("wpisz mianownik:")
if mianownik == 0:
print("gamonie")
else:
print(" " + str(licznik))
print("--- ")
print(" " + str( mianownik))
|
5b9613c9a3ba1eb0e19902b2f50b4e946c4d96f1 | Zerobitss/Python-101-ejercicios-proyectos | /practica31.py | 496 | 3.84375 | 4 | """
Escribir un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces
que aparece la letra en la frase.
"""
def run():
contador = 0
word = str(input("Ingresa una frase: "))
letter = str(input("Ingresa una letra: "))
for i in word:
if i == ... |
b8e214b4499b4904e1c13d41086d483eca8c52f1 | monicador/Python | /1_Ciclo_While1.py | 632 | 4.34375 | 4 | '''
Mientras que (While)
El Ciclo Mientras que es conocido en los lenguajes de programación como
ciclo While, una de sus características es que verifica si la condición
se cumple antes de ingresar al bloque de código que se va a repetir, el
límite de ejecuciones estará dado por la condición, se ejecutará mientras
... |
c102e69ffef15a0a566a92af7fa5939c752b64b4 | angishen/algorithms-datastructures | /ch07_linkedlists.py | 9,667 | 3.953125 | 4 | # 7.1 MERGE TWO SORTED LISTS
class ListNode(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def merge_sorted_lists(L1, L2):
result = head = ListNode()
while L1 and L2:
if L1.data <= L2.data:
result.next = L1
result = resu... |
f9af2d519e174eafe39969cbe65517d477cb86ce | roblivesinottawa/python_bootcamp_three | /FUNCTIONS/fibo.py | 350 | 3.515625 | 4 | def fib(n):
if n >= 3:
return fib(n-1) + fib(n-2)
return 1
print(fib(10))
def fbnc(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fbnc(n-1) + fbnc(n-2)
print(fbnc(10))
def fibo(num):
a = 0
b = 1
for i in range(num):
a, b = b, a+b... |
e9c7b24e582755ae36a035a964d34b6085caef5a | jungiejungle/python-project | /.gitignore/hello.py | 384 | 3.9375 | 4 | print("Hello, World")
print("Python", 3)
print("Hello, World", sep=";", end="$")
print("{}{}".format("ADNU", 2018))
age = 18
weight = 60.21
print (type(age))
print (type(weight))
print (type("Hello"))
data = {"name" : "Juggernaut",
"age" : 18,
"height" : 178.50,
"fave_fruits" : ["apple" , "m... |
6ae55f5dfda37025fc5c7faff6a09842612aa31b | NicholasLePar/NicksNeuralNetwork | /Initialization.py | 5,446 | 3.796875 | 4 | import numpy as np
########################################################################################################################
"""
GROUP: Parameter Initialization
-Handles the initialization of the neural networks weights and biases
EXTERNAL FUNCTIONS:
1) initialize_parameters: initializ... |
e433d756ca4aaca9abe1ac37737c4858d2d662ae | guoheng/ProjectEulerPy | /p046.py | 1,000 | 3.8125 | 4 | #It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
#
#9 = 7 + 2x1^2
#15 = 7 + 2x2^2
#21 = 3 + 2x3^2
#25 = 7 + 2x3^2
#27 = 19 + 2x2^2
#33 = 31 + 2x1^2
#
#It turns out that the conjecture was false.
#
#What is the smallest odd composite that can... |
0fc85d64f6653fd913bd485e2b7725aa07cdd3d7 | wiegandt/week_3 | /variable mutation.py | 515 | 3.546875 | 4 | a = 3
a = a + 10
print(a)
b = 100
b-=7
print(b)
c = 44
c*=2
print(c)
d = 125
d/=5
print(d)
e = 8
e^=3
print(e)
f1 = 123
f2 = 345
if f1 > f2:
print(True)
else:
print(False)
g1 = 350
g2 = 200
if 2*g2 > g1:
print(True)
else:
print(False)
h = 1357988018575474
if 11 / 1357988018575474:
pri... |
81f10c9142a3fd138487e015ccaa957db1a7c0e0 | abhs26/Daily-Coding-Problem | /problem_85.py | 567 | 3.96875 | 4 | #!/usr/bin/env python
"""
Given three 32-bit integers x, y, and b,
return x if b is 1 and y if b is 0,
using only mathematical or bit operations.
You can assume b can only be 1 or 0.
"""
import sys
__author__ = "Abhishek Srivastava"
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Abhishek Srivastava"
__e... |
935116098e2c3123e543b49968db2f9b9014d76a | vietnguyen2000/CPU-Scheduling-and-Demand-Paging-question-for-CodeRunner | /CPU Scheduling/FCFS.py | 1,025 | 3.734375 | 4 | def findavgTime(processes):
#TODO: write function to calculate avgWaitingTime and avgTurnAroundTime of FCFS Algorithm
n = len(processes)
wt = [0] * n
tat = [0] * n
completeTime = [0]*n
# Function to find turn around time
for i in range(n):
completeTime[i] = max(completeTime[i-1]... |
6612b6803bfef4c9ddc47fd0ea5874be62f26a54 | ynzerod/actual_06_homework | /02/songxiang/kuaisupaixu.py | 669 | 3.640625 | 4 | def kuaisupaixu(num_list,left,right):
i = left
j = right
if i == j:
return num_list
while j > i:
while j > i and num_list[j] >= key:
j = j - 1
num_list[i],num_list[j] = num_list[j],num_list[i]
while i < j and num_list[i] <= key:
i = i + 1
num_list[i],num_list[j] = num_list[j],num_list[i]
return ... |
9dfec636c50c31524829f3ac65ac6646a695c1ba | shadiqurrahaman/python_DS | /Binary-tree/Binary_tree_to bst.py | 1,051 | 3.796875 | 4 | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Main:
def inorder(self,root):
if root==None:
return
self.inorder(root.left)
print(root.data,end=' ')
self.inorder(root.right)
def insert_in_array(self,root,array):
if root==None:
... |
72c60a4d1e89249b46c912cfd48efc3aced37ca5 | vijaypalmanit/coding | /date to bned months.py | 1,197 | 3.5625 | 4 | import pandas as pd
import numpy as np
# normal datafrmae having date filed which needs to be labeled with corresponding business month
df=pd.DataFrame({'id':[23,45,65,76,21,54],'day':['2019-04-30','2019-05-31','2019-06-29','2019-07-15','2019-10-12','2019-11-22']})
df['day'] = pd.to_datetime(df['day'],format='%Y-%m-%... |
c40eee1967d02dbf6af7d3a95398f7822d23f785 | reanimation47/ledoananhquan-fundametal-c4e13 | /Session05/homework/bacteriaB.py | 322 | 4.125 | 4 | n = int(input("How many B bacterias are there?"))
t = int(input("How much time in minutes we will wait?"))
if t % 2 == 0:
T = t / 2
x = (2**T)*n
print("After", t, "minutes,we would have", x, "bacterias" )
else:
T = (t-1)/2
x = (2**T)*n
print("After", t, "minutes,we would have", x, "bacterias" ... |
88a9e82597df7206c7a11a836bb3bb65de10e0f2 | westonwilson08/Python | /brute_force1.py | 1,516 | 3.625 | 4 | import itertools
import string
import zipfile
import argparse
def extractFile(zFile, password):
try:
zFile.extractall(pwd=password)
print "[+] Found password = " + password
return True
except:
return False
def main():
parser = argparse.ArgumentParser("%prog -f <zipfile>")
... |
96152d12a2474add6c324dd88b95e2974b62c0c5 | arnabs542/Leetcode-18 | /Palindrome Number.py | 548 | 3.96875 | 4 | class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
num = 0
tmp = x
while tmp > 0:
num = num*10 + tmp%10
tmp /= 10
return num == x
"""
:type x: int
:rtype... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.