blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
af4779e613ae4ea2c34a0d4a89d5bfc03e69cc18 | kmutya/Nonlinear-Optimization | /unconstrained_optimization.py | 7,640 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 13:57:51 2019
@author: Kartik
"""
import numpy as np #arrays
from numpy import linalg as LA #Linear Algebra
import matplotlib.pyplot as plt #plotting
import sympy #symbolic computing package
from sympy.utilities.lambdify import lambdify #conver... |
8d8c6d7bf7cd63ece8498ad8a5e7653dfb9d008a | rondemora/lstm_predictor | /trader_simulator.py | 7,411 | 4 | 4 | """
Simulates a trader in the stock market during the test dataset for different models:
1. LSTM
2. Prophet
3. Other implemented trading strategies
"""
from keras.models import load_model
import lstm
import data_preprocessor
import prophet
import random
import numpy as np
import pandas as pd
from sklearn.metrics impor... |
ba9c0bcd80f26936d0fc42729056ed59291603b6 | Adrian0207/-LetsGo_Python | /Ejercicios_POO/ejercicio1.py | 1,317 | 3.875 | 4 | '''
Crear una clase Persona que tenga como atributo Nombre, Edad y DNI.
Aplique el uso de decoradores.
Crear una funcion que permita verificar si es mayor a 18 años
Usar la funcion __str__ para imprimir el nombre y la edad
'''
class Persona():
def __init__(self,nombre="",edad=0,dni=""):
self.__nombre=nombr... |
7208bf6250ee0f0e34ebfbff44bfe9d4e38ca59c | Parkyunhwan/Programmers | /Level_1/최대공약수와최소공배수.py | 746 | 3.59375 | 4 | # version1
# 유클리드 호제법을 이용한 최소공배수 최대공약수 구하기
# 작은 값은 big으로 간다. 서로의 나머지는 small로 간다. small이 0이 될 때까지 계속한다.
def gcd(a, b):
while b != 0:
tmp = a % b
a = b
b = tmp
return a
def solution(n, m):
answer = []
if (n < m):
tmp = n # 3
n = m # 12
m = tmp # 3
te... |
4628cb33312da7e7024301c5fdef2c367470c542 | marcos-mpc/CursoEmVideo-Mundo-2 | /ex061.py | 146 | 3.78125 | 4 | termo = int(input('TERMO: '))
razao = int(input('RAZÃO: '))
cont = 0
while cont < 10:
print(termo, end=' ')
termo += razao
cont += 1
|
8d80b107dde8aad1ccc9cc9f4e81c8ebd264230b | Neela25/python-75-hackathon | /dict.py | 709 | 4.0625 | 4 | #Creating 3 dictionaries consisting of student details
student1=dict(name="Neela",regno="16C050",sem=5)
student2={"name":"Meena","regno":"16C040","sem":5}
student3=dict(name="Abi",regno="16C003",sem=5)
#Using setdefault() method,the value for key roll is obtained in n
#Since key roll is not in the dictionary,it is... |
f5eccea0d481a56b3b13b3738ec4880d41c466cf | huyuexin/helloworld | /list2.py | 285 | 4.09375 | 4 | squares=[]
for values in range(1,11):
square = values ** 2
squares.append(square)
print(squares)
squares=[]
for values in range(1,31,3):
squares.append(values)
print(squares)
print(squares[0:3])
print(squares[2:5])
print(squares[2:])
print(squares[-3:])
|
5d73b593bf3f45a06eb22909a01e86cf8babdf6b | deepak1214/CompetitiveCode | /LeetCode_problems/Spiral Matrix/solution.py | 1,916 | 3.5 | 4 | #Logic:
#First, four variables containing the indices for the corner points of the array are initialized.
#The algorithm starts from the top left corner of the array, and traverses the first row from left to right.
#Once it traverses the whole row it does not need to revisit it, thus, it increments the top corner inde... |
0bcbeadeba532d6056209f34202662c855cadfe0 | chrhck/pyABC | /pyabc/pyabc_rand_choice.py | 436 | 3.546875 | 4 | import numpy as np
def fast_random_choice(weights):
"""
this is at least for small arrays much faster
than numpy.random.choice.
For the Gillespie overall this brings for 3 reaction a speedup
of a factor of 2
"""
cs = 0
u = np.random.rand()
for k in range(weights.size):
cs +... |
275f18aa119f11353e1c0be3ea3fe1f2d2116eb3 | rwalroth/roboto_gui | /roboto_gui/CommandLine.py | 2,392 | 3.5 | 4 | from PyQt5.QtWidgets import QLineEdit, QWidget, QHBoxLayout, QPushButton
from PyQt5 import QtCore
class CommandLine(QLineEdit):
"""Widget to simulate a command line interface. Stores past
commands, support enter to send and up and down arrow navigation.
attributes:
current: int, index of current ... |
020d405a5555b920cbf6c1e4c38f4fe95ab1f086 | akashlahane33/AkashPythonCodes | /FilterMapreduce.py | 246 | 3.59375 | 4 |
from functools import reduce
nums = [2,3,4,5,6,7,8,9,5,4,33,55,33,654,54]
evens = list(filter(lambda n : n%2==0,nums))
doubles = list(map(lambda n : n*2,evens))
sum = reduce(lambda a,b : a + b,doubles)
print(evens)
print(doubles)
print(sum) |
0b45c3d7ba91c51e821d2d7435d268a48b67f44d | mfa1980/python-012021 | /Lekce 3/Ukoly/priklad15.py | 1,715 | 3.5 | 4 | """
Prodej vstupenek
Vytvoř program na prodej vstupenek do letního kina. Ceny vstupenek jsou v tabulce níže.
Datum Cena
1. 7. 2021 - 10. 8. 2021 250 Kč
11. 8. 2021 - 31. 8. 2021 180 Kč
Mimo tato data je středisko zavřené.
Tvůj program se nejprve zeptá uživatele na datum a počet osob, pro které uživatel chce vstupenky k... |
32927fa81e1f43cca294874da6a9ee96de4453bf | neizod/problems | /codejam/18/2/falling-balls.py | 1,560 | 3.546875 | 4 | #!/usr/bin/env python3
def get_destination(last_row):
nudge = 0
destination = [None for _ in last_row]
for index, size in enumerate(last_row):
destination[nudge:nudge+size] = [index] * size
nudge += size
return destination
def get_table(last_row):
if last_row[0] == 0 or last_row[... |
ff3e3d679882abb9b0ab87c0ed7a5c790cd3f289 | sdmgill/python | /Learning/Chapter10/FindStringInFiles.py | 1,618 | 3.53125 | 4 | def get_lines_with(input_str, substr):
"""
Get all lines containing a substring.
Args:
input_str (str): String to get lines from.
substr (str): Substring to look for in lines.
Returns:
list[str]: List of lines containing substr.
"""
lines = []
for line in input_str.... |
2ea7e3e8fd4f05be82bbee822a99d8cba6b5d5ce | gabriellaec/desoft-analise-exercicios | /backup/user_222/ch47_2019_03_28_12_22_57_662078.py | 175 | 3.859375 | 4 | mes=int(input('numero do mes'))
lista=['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro']
print(lista[mes-1])
|
a657f0ae35e6f4bd6430d74f546c410e65b9b812 | susunini/leetcode | /281.zigzag-iterator.py | 2,477 | 4 | 4 | #
# [281] Zigzag Iterator
#
# https://leetcode.com/problems/zigzag-iterator
#
# Medium (50.16%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[1,2]\n[3,4,5,6]'
#
#
# Given two 1d vectors, implement an iterator to return their elements
# alternately.
#
#
# For example, given two 1d vectors:
#
# v1 = [1, 2... |
c2cb3276c020e883219a49a70291127bc3f11f6f | gtshepard/TechnicalInterviewPrep2020 | /assignments/week1/day3/garrison_shepard_lc/find_all_anagrams/garrison_shepard_LC_438.py | 577 | 3.640625 | 4 | def findAnagrams(s, p):
result = []
p = sorted(p)
#generate all substrings
for i in range(len(s)):
j = i + 1
for j in range(len(s)+1):
if len(s[i:j]) is len(p):
#sort string of same length
sub_str = sorted(s[i:j])
# should be s... |
1aa18a01c26f4d9b5af8bf5fc22e01039ff57813 | ronak-kachalia/python-tutorial | /Python Lectures/28- if __name__ == '__main__'/first_module.py | 631 | 3.859375 | 4 | # =============================================================================
# __name__ is a python reserved variable that stores name of the current module.
# if the current module is the one which is run directly by Python then __name__ = '__main__'
# else, if it is not run directly by python, then __name__ = '{Na... |
e1b652e525c423db8e42b9dcd2da24561b057c85 | ParthDeshpande27/PH-354-2019-IISc-Assignment-Problems | /hw5/01/1.py | 622 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 12:02:37 2019
@author: alankar
"""
import numpy as np
np.random.seed(500)
dice1 = np.random.randint(low=1,high=6)
dice2 = np.random.randint(low=1,high=6)
print('Dice 1: %d'%dice1)
print('Dice 2: %d'%dice2)
N = int(1.e6)
dice1 = np.random.ran... |
3f2573a4d86c6c02c0041404f362c0106251b9e1 | vcatafesta/chili | /python/decorators.py | 6,665 | 4.125 | 4 | def outer_function():
message = 'Hi'
def inner_function():
print(message)
return inner_function()
outer_function()
hi_func = outer_function()
#################################################################################
def outer_function(msg):
message = msg
def i... |
f9212a3a72f965cad9c72387e1669cea7bb7353a | Troy-Wang/LeetCode | /201611_Week2/20161108_2.py | 507 | 3.859375 | 4 | """
Count Numbers with Unique Digits
Given a non-negative integer n, count all numbers with unique digits, x, where 0 <= x < 10n.
"""
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
... |
889809ecfa1525b20408b3e63edcb25409273c9a | gcctryg/cs362_hw4 | /q2.py | 694 | 3.734375 | 4 | import unittest
def calc_avg(num):
sumNum = 0
for i in num:
sumNum = sumNum + i
length = len(num)
avg = ( sumNum / length) if length != 0 else 0
return avg
class testCase(unittest.TestCase):
def test_func(self):
self.assertEqual(calc_avg([1,3,5,7,9]), 5)
self.assertEq... |
c28faf8c80a3b738e80aaebfce38ecd275b67972 | shantanu-python/Python | /prime.py | 428 | 4.125 | 4 | import math
def is_prime(a):
n = abs(a)
if (n<2):
return False
elif (n%2==0):
return False
n1 = int(math.sqrt(n))+ 1
return all(n%i for i in range(3,n1,2))
q = None
while(q!= "q"):
x = int(input("Enter the number :"))
p = is_prime(x)
s = "is prime."... |
a22d626df17fcca840d974e601e4169f4cce5de3 | rescenic/Softuni-Python-v2 | /python-fundamentals/09 RegEx - Excercise/01. Capture the Numbers.py | 159 | 3.5625 | 4 | import re
pattern = r'\d+'
numbers = []
line = input()
while line:
numbers.extend(re.findall(pattern, line))
line = input()
print(' '.join(numbers)) |
65ea595058056595299b2c9d3df6279623e0868f | bssrdf/pyleet | /F/FindLatestGroupofSizeM.py | 2,006 | 3.578125 | 4 | '''
-Medium-
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary
string of size n that initially has all its bits set to zero.
At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n,
the bit at position arr[i] is set to 1. You are given an integer ... |
f8e91d79531c94dd1c38e90a513aacc7af7a21f4 | edutilos6666/PythonExamples | /NumberExample.py | 1,885 | 3.96875 | 4 | import math
import random
def example2():
'random methods'
print('random.random() = ', random.random())
print('random.randint(10, 1000) =', random.randint(10, 1000))
print('random.randrange(10, 1000) =', random.randrange(10, 1000))
print('random.randrange(10, 1000, 2) = ', random.randrange(10, 1000... |
a08ace17e89a52ed82d2467cb7dea5823fac6923 | RansomBroker/self-python | /Recursive/binarySearchTree.py | 1,101 | 4.15625 | 4 | class Node:
#make constructor for insert data
def __init__(self, key):
self.left = None
self.right = None
self.value = key
#insert item based on root
def insertTree(self, root, node):
if root is None:
root = node
else:
#insert value ... |
0bd84834e8d43615e9a21b3b7544af06ebb1983f | priscilasvn10/Python_Desafios | /Desafio081.py | 568 | 3.984375 | 4 | '''ler vários números e colocar na lista
a) quantos números foram digitados
b)ordem decrescente
c)se o valor 5 foi digitado e está ou não
na lista'''
num = []
i = 0
while True:
num.append(int(input('Digite um número: ')))
c = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]
if c == 'N':
bre... |
d2c2746a4575cfbcadcc42469929b9e316a4b8f5 | github-markdown-ui/github-markdown-ui | /test/helpers.py | 414 | 3.828125 | 4 | from re import sub
def remove_whitespace(text: str) -> str:
"""Removes all whitespace from a string (including newline characters) after a > or before a <.
This function allows us to write the expected HTML syntax outputs of the test cases in a more readable form, as long as
we don't put whitespace aroun... |
a1768e5e3122e215c586a96248f962d1713ca816 | geislor/python-tdd-exercises | /count_num_vowels.py | 233 | 3.984375 | 4 | """
Exercise 4
"""
VOWELS = ['a', 'e', 'i', 'o', 'u', 'y']
def count_num_vowels(s):
"""
Returns the number of vowels in a string s.
whit listcomprehension
"""
return len([i for i in s if i.lower() in VOWELS ])
|
1cd259421166313dd885b7ec7c09362b2a5e0c5b | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/121_14.py | 3,246 | 4.25 | 4 | Python | Group and count similar records
Sometimes, while working with records, we can have a problem in which we need
to collect and maintain the counter value inside records. This kind of
application is important in web development domain. Let’s discuss certain ways
in which this task can be performed.
... |
4c8b05377b1b43858fc1cdc43c2828636fd21f4e | Praneta-Paithankar/CSCI-B505-Applied-Algorithm | /Assignment 1/Sorting.py | 6,066 | 4.1875 | 4 | import time,FileOperations
#Sort numbers using bubble sort
def bubble_sort(numbers):
for i in xrange(0, len(numbers)-1):
for j in xrange(len(numbers)-1, i, -1):
if numbers[j] < numbers[j-1]:
numbers[j], numbers[j-1] = numbers[j-1], numbers[j]
return numbers
#sort numbers us... |
d71625a6eff62580a14c614696ac4b2b2a0f9836 | Deiv101/functions_tutorial | /functions_tutorial.py | 7,807 | 3.84375 | 4 | # Creating a function
def my_function():
print("Hello from a function")
# Calling a Function
my_function()
####################################################################################################################################################################
# Arguments
def my_function(fname):
pr... |
8e72fb71eeaec9570b6721e89afeb3c783af2aac | GiovanniCassani/discriminative_learning | /nonwords/neighbors.py | 6,763 | 3.515625 | 4 | __author__ = 'GCassani'
import helpers as help
from collections import defaultdict, Counter
def map_neighbours_to_pos(neighbours_file, wordform2pos, ids2words):
"""
:param neighbours_file: the file with the neighbours retrieved for each test item: each item is on a different
colu... |
95a5575a9d0d210d3b7be2c99aeb587c9f0a2c40 | aowenb/Purwadhika-Excercise | /soal 5.py | 521 | 3.640625 | 4 | x = input('masukkan sebuah kalimat : ')
print('kalimat original : ',x)
def counter(x):
up = []
low = []
for i in x[::1]:
if i.isupper() == True:
up.append(i)
else:
low.append(i)
for i in low:
if i == ' ':
low.remove(' ')
return len(up), le... |
753aa4778234c296d70b2cfc2b01673aa93f58b5 | parolaraul/itChallengeML2017 | /Peru - Buscando Numeros - 60 pts/peru.py | 806 | 3.796875 | 4 | # Peru
pi = open('pi', 'r').read()
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
#number a... |
8b47a892df850416f780588f2791e63fd00f3d32 | LachubCz/VUT-FIT-MIT | /6_semestr/DIP/src/pero/src/arabic_helper.py | 572 | 3.609375 | 4 | import arabic_reshaper
import re
def normalize_text(text):
text = reverse_transcription(text)
text = arabic_reshaper.reshape(text)
text = reverse_transcription(text)
return text
def reverse_transcription(transcription):
transcription = transcription[::-1]
number_patter = r"[0-9]+"
match... |
af18dd3717966e3b12ca843ec77ce44b9472110e | Rifat951/PythonExercises | /Lists/exercises.py | 3,331 | 4.53125 | 5 | # 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people you’d like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner
print("\n\n#########################################... |
7b6dc37fb7010ad5636b9abafa56503ca1312f6e | opensourcex123/Data_Analysis | /demo1 pyplot的中文显示.py | 309 | 3.625 | 4 | # 作者:宁方笑
# 开发时间:2021/5/27 21:38
import numpy as np
import matplotlib.pyplot as plt
a=np.arange(0.0,5.0,0.02)
plt.xlabel('横轴:时间',fontproperties='kaiti',fontsize=20)
plt.ylabel('纵轴:振幅',fontproperties='kaiti',fontsize=20)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show() |
fd0ab39f0ab8d3065121cf5dfa9b65b83fc36bf9 | curieux/ProgMathSci | /matrix.py | 5,940 | 4.125 | 4 | #!/usr/bin/env python
""" A sample python module for working with matrices.
Abraham D. Smith """
import numbers
class Matrix:
def __init__(self, listOfLists):
""" Construct a Matrix object from a list-of-lists, packed by row.
Some minimal sanity checks are in place. """
... |
01f6cf366b6bda4a6f30d97aa2988b9ee21f284e | david-luk4s/sock | /Sock.py | 951 | 3.703125 | 4 | from turtle import Screen, Turtle, mainloop
def main():
space = Screen()
space.setup(450, 450), space.title('Sock')
space.bgcolor('green')
pen = Turtle(shape='circle')
pen.shapesize(0.3), pen.width(5)
create_sock(pen)
pen.ht()
def create_sock(pen):
pen.color('black', 'red'), pen.spee... |
c0211a75f578b1abe7b728a92778887eaa691b3f | daniel-reich/turbo-robot | /ZdnwC3PsXPQTdTiKf_17.py | 653 | 4.34375 | 4 | """
Create a function that takes two numbers and a mathematical operator `+ - / *`
and will perform a calculation with the given numbers.
### Examples
calculator(2, "+", 2) ➞ 4
calculator(2, "*", 2) ➞ 4
calculator(4, "/", 2) ➞ 2
### Notes
If the input tries to divide by 0, return: `"Can't d... |
139dd916ecf9a6189f5febc55171bf4fcb5452b1 | hwankyusong/Prime_Factorizer | /prime_factorizer_v2.py | 328 | 3.53125 | 4 | #returns prime factorization in list form
#fixed emptying list issue
from math import *
L=[]
def prime(n):
if len(L) != 0:
del L[:]
return helper(n)
return helper(n)
def helper(n):
for i in range(2,round(sqrt(n))+1):
if n % i == 0:
L.append(i)
return helper(n/i)
L.append(n)
ret... |
735097a9a3df21715ca85f19a381d29b3840c887 | kyoz/learn | /languages/python/1.learn_py_the_hard_way/ex15.py | 251 | 3.71875 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename} content:")
print(txt.read())
print("Type the filename again:")
new_file_name = input("> ")
new_txt = open(new_file_name)
print(new_txt.read())
|
fd101c8e4759db09b4434d728a23870f0d24bc6a | Rohan07Singh/264789_Daily_Commit | /Word_check.py | 249 | 4.09375 | 4 | def is_word_present(sentence, word):
s=sentence.split(" ")
for i in s:
if(i==word):
print("True")
print("False")
s=input("Enter a sentence")
word=input("Enter the word to be searched")
is_word_present(s,word) |
4941aeb787364f333c38e187ef47f60caa619cbd | Worcester-Preparatory-School-Comp-Sci/python-1-FrankTheTank87 | /Great Lakes .py | 480 | 4.125 | 4 | #Frank Carter, 9-16-19
water = float(input("How many milliliters of water are in the Great Lakes? "))
usa = float(input("What is the surface area in centimeters of the 48 contiguous US states? "))
def depth(x):
x = water/usa
return(x)
print("If all the water in the Great Lakes covered the USA, the water would b... |
90a86804d1f7eec8c3af0eda8be0703d517f1ab4 | AnotherContinent/thinkful | /FizzBuzz.py | 368 | 4.0625 | 4 | import sys
num_input = raw_input("Please enter a number: ")
try:
num_input = int(num_input)
except ValueError:
print("That is not a valid integer.")
else:
for n in range(1,num_input):
if n % 5 == 0 and n % 3 == 0:
print("FizzBuzz")
elif n % 5 == 0:
print("Buzz")
elif n % 3 == 0:
pr... |
c2676db89b7aa05a499bf1b0af4db1b39a934651 | jvfiel/pythonbasic1 | /level2_list.py | 407 | 3.984375 | 4 | #LISTS
bags = ['Hand Bag','Shoulder Bag']
print(bags)
print("---------------------")
for bag in (bags):
print(bag)
print("--------------------")
#Looping through the list and enumerate
for i,bag in enumerate(bags):
print(i, bag)
#In principle index always starts at 0
print("--------------------")
#split b... |
73f670325e65f119cb956b2f8a51ec64ee788f95 | kyungtae92/python-basic | /day1015/function14.py | 722 | 3.890625 | 4 | # 원의 넓이 : 반지름 * 반지름 * 3.14
# 원의 둘레 : 원의 넓이 * 높이
def circleArea(radius):
print('radius: ', id(radius))
area = radius * radius * 3.14
return area
def circleVolume(radius, height):
vol = circleArea(radius) * height
return vol
def printCircle(area, vol, radius):
print('반지름 %d인 원의 넓이... |
3d601056471a4541d63b99266c8b698207489e49 | hakan7822/Projet3Macgyver | /class_Square.py | 1,219 | 3.890625 | 4 | import pygame
from pygame.locals import *
from class_Coordinates import *
from class_Item import *
class Square:
"""
Description.
A class that will define the squares of the laby.
"""
def __init__(self, coord, is_wall):
"""Use Coordinates and is_Wall boolean as arguments.
Starts ... |
cca8e76be7a8651b3dfe346d7975d0900d8af01a | gitForKrish/PythonInPractice | /PythonCrashCourse/Theories/p07_Functions.py | 1,696 | 3.78125 | 4 | def greet_user():
""" Message for greeting """
print('hello')
greet_user()
def greet_user(name):
""" Message for greeting """
print(f'hello, {name.title()}')
greet_user('jack')
# greet_user() # TypeError: greet_user() missing 1 required positional argument: 'name'
def describe_animal(animal_typ... |
2e9e54bdf97bbd79c74085a86a401ebe65936270 | ebbitten/ScratchEtc | /Challenges/ZombitPath v 2.1a.py | 2,337 | 3.609375 | 4 | import operator
def answer(food,grid):
#initialize the input that we'll get all of the permutations of paths from
N=len(grid)
#if N>=20:
# return -1
bestFood=201
directions=[[0,1,0],[0,0,1]]
growingBranch=[[food,0,0]] #paths that need to have branches added
found=False
while not f... |
34eca39f58c01591a82ba1bec326b21d55110c85 | nsa18685/my_first_python | /4장/쳌4.22.py | 104 | 3.703125 | 4 | num = eval(input("수를 입력하세요: "))
num = True if num>0 and num <= 100 else False
print(num)
|
8846dbb60c1199a399b6db4832c3ddcc4c2d7ea8 | victor12416/Elam_Cabrera | /The Dealer ;).py | 7,111 | 4.125 | 4 | Inventory_list = ['Infiniti, Subaru, Lexus, GMC, Toyota, BMW, Honda, Lincoln' ]
#individual list of cars
Infiniti = ['Q50,QX80,QX30']
Subaru= ['Impreza,Legacy,Forester']
Lexus = ['Rx,IS,Ls']
GMC = ['Acadia,Yukon,Canyon']
Toyota = ['Corolla,Land Crusier,C-HR']
BMW = ['3 Series,X5,5 Series']
Honda = ['Accord,Civic,CR-... |
a2547f366d7f74fb83b1fdf7dc6b0a5c92923d84 | nguyenkims/projecteuler-python | /src/p25.py | 366 | 3.65625 | 4 | def fib_gen(n):
'''generate n first Fibonacci numbers'''
a,b,i=0,1,1
yield a,0
yield b,1
while i < n:
i += 1
if a > b:
b = a+b
yield b,i
else:
a = b +a
yield a,i
def test() :
t = fib_gen(10)
for i in t:
print i
# test()
def final():
k = 1000
t = fib_gen(6*k)
for i,j in t:
if len(... |
3253b5f418d1c40fc7a3590828fb1367e9632bfe | Juan-Tena/Codigo_VBA | /Trabajo_Serializacion.py | 396 | 3.53125 | 4 | import pickle
lista_nombres=["Pedro", "Ana", "Maria","Isabel"]
fichero_binario=open("lista_nombre","wb") #Escritura binaria
pickle.dump(lista_nombres, fichero_binario)
fichero_binario.close()
del(fichero_binario)
#Ahora, una vez creado el fichero binario, vamos a rescatar la información que contiene
import pickle... |
40a5b2ef1a707beeca6fbcce913af48d670dca79 | bendell02/nowCoder | /01_code/prj188_median.py | 380 | 3.84375 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
#Author: Ben
def median(nums1, nums2):
nums = nums1+nums2
nums.sort()
l = len(nums)
return nums[(l-1)/2]
while True:
try:
nums1 = map(int, raw_input().split())
nums1.pop(0)
nums2 = map(int, raw_input().split())
nums2.pop(0)
... |
467d5a3efb104f4a98fd54bc1975c8cf1186c732 | serenascalzi/python-specialization | /exercises/chapter01-exercises.py | 854 | 3.859375 | 4 | # chapter 1
# why should you learn to write programs?
# secondary memory - stores information for the long term, even beyond a power cycle
# program - set of instructions that specifies a computation
# compiler - translates a program written in a high-level language into a low-level language all at once, in preparat... |
1cc01064b5ed36b656b4e96809279d6a8eca04b0 | shohruh-abduakhatov-portfolio/go-apteka-py | /web/ui_methods.py | 761 | 3.78125 | 4 | def has_access(self, roles):
user = self.current_user
"""
user_roles = user["roles"]
has_access = False
for role in user_roles:
if _checkRole(role, roles) == True:
has_access = True
break
return has_access
"""
return True
def _checkRole(role, roles):... |
a36a06e81672816e45fd24bee6066bc28188420a | mcxu/code-sandbox | /PythonSandbox/src/sorting/merge_sort.py | 1,974 | 3.796875 | 4 | '''
Merge Sort
'''
from utils.number_utils import NumberUtils
class Prob:
def mergeSort(self, array):
if not array or len(array)==1:
return array
median = int(len(array)/2)
left = array[:median]
right = array[median:]
#print("mergeSort: median:{}, l:{}, r:{}".fo... |
1b6790391e5b6903372f0c9ff5bf76b3c396b2d2 | B14nk/Sorting_Algorithms | /Mergesort/Mergesort.py | 723 | 3.671875 | 4 | arr = [1,4,324,56,7,456, 45, 34, 3267,768, 100]
def mergesort(arr):
if len(arr) <= 1:
return arr
else:
l = mergesort(arr[0:len(arr)/2])
r = mergesort(arr[len(arr)/2:len(arr)])
return merge(l, r)
def merge(l, r):
if len(l) == 0:
return r
if len(r) == 0:
r... |
d4ccf81e659edef409ce7f6b7c4ca621d90cee51 | Crasti/Homework | /Lesson4/Task4.6.py | 782 | 4.21875 | 4 | """
Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
"""
from itertools import count
from itertools impo... |
59bf9e3eddbd3e50a5b0e787c1fa14e71ac55632 | macasubo/python_bootcamp | /python01/ex03/matrix.py | 2,448 | 3.703125 | 4 | class Matrix:
def __init__(self, data=[], shape=()):
if type(data) == type(list()):
self.data = data
if len(shape) == 0:
self.shape = (len(self.data), len(self.data[0]))
else:
self.shape = shape
elif type(data) == type(tuple()):
self.data = list()
self.data = [[0 for item in range(data[1])]
... |
43059fbcd356ec0f13831956367ede3368efeeff | marcus255/coding | /euler/37/37.py | 740 | 3.875 | 4 | def isPrime2(Number):
return 2 in [Number,2**Number%Number]
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
num = 11
primes_sum = 0
primes_count = 0;
while(primes_count < 11):
if isPrime(num):
temp_num = num
temp_num_2 = num
while temp_num > ... |
32be62f0179a2b2e07235c3da0cea65355b6326b | SEugene/python | /task_1_3.py | 1,304 | 3.640625 | 4 | num_list = []
for num in range(21):
num_list.append(num)
for ind in range(len(num_list)):
last_num_hun = num_list[ind] % 100
last_num_ten = num_list[ind] % 10
if 10 < last_num_hun < 15:
print('{} процентов'.format(num_list[ind]))
elif 1 < last_num_ten < 5:
print('{} процента'.format... |
e8852066638f03d2fe567ce9b75ed686de97e3ef | shonihei/road-to-mastery | /algorithms/sorting-algorithms/insertionsort.py | 1,288 | 3.5625 | 4 | import random, sys
m = 0 # keeps track of number of comparisons
def wrapper(l):
lst = l[:]
insertion_sort(lst)
return lst
def insertion_sort(lst):
global m
for i in range(1, len(lst)):
cur = i
for j in range(i - 1, -1, -1):
m += 1
if lst[cur] < lst[j]:
... |
3f2b3fb132ef8cfab2063dee8d8a87570a60d4e3 | blidt/metodosNumericos | /newton/newton.py | 490 | 3.96875 | 4 | from math import *
def newtonIterationFunction(x):
return x - (((-8*exp(1-x)+7/x)) / (8*exp(1-x)-7/x**2))
def function(x):
return -8*exp(1-x)+7/x
x = 1.6
c = 1
xold = 0
fc = 1
for i in range(1000):
print "Iteraciones: ",str(i),"Valor aproximado: ", str(x), "Intervalo", str(c), "f(c)", str(fc)
c ... |
61c1ed60d436e5cb70c3cc74cf375bf20baf8a76 | cikent/Python-Projects | /Automate-The-Boring-Stuff-With-Python/Section_03_Functions/Lesson_10_Global_&_Local_Scope/Local_Variable_Execution_Error_example.py | 276 | 3.890625 | 4 | """
Upon execution, the function 'spam()' throws an exception because eggs is utilized as a Local variable before assignment
"""
def spam():
print(eggs) # ERROR! -- can't use a local variable before it is assigned a value
eggs = 'spam local'
eggs = 'global'
spam() |
ca469bd9acb7c2fdba8ec887fc1e1eb531140dfb | PascalUlor/code-challenges | /python/linked_list_1.py | 6,447 | 4.25 | 4 | # Create Node constructror
class ListNode(object):
def __init__(self, value=None):
self.data = value
self.next_node = None #address to next node
# def __str__(self):
# return f"{self.data} → {self.next_node}"
# node = ListNode(5)
# node.next_node = 2
# print(node)
# create List Constr... |
15c5346462fcc619d7b98b02513d02c1a6f904b1 | superdun/9BillionNames | /9billion.py | 1,040 | 3.546875 | 4 | #! usr/bin/python #coding=utf-8 /
import time
from itertools import groupby,count
#打印神的一个名字
def printGodsName(words):
godsName = ""
#神没有带有三个连续字母的名字
if max(len(list(g)) for k, g in groupby(words) )>=3:
return
for singleWord in words[::-1]:
godsName+=chr(65+singleWord)
print godsName
#26进制
def twentySixDeci... |
8c03e411ea674d15b2520c39b15478f7abf37ad1 | sejal-varu/bigdata | /python/exception/play_input.py | 264 | 3.890625 | 4 | print 'Program starts'
n = raw_input('Enter n : ')
try :
i = int(n)
except ValueError:
#Executes when error
print 'Hey! Please enter numerals only'
else:
#Executes when no error raised in corresponding try block
print 'The number is ', i
print 'Program ends' |
2cf6cfffa8082ad0ef28188e2c5eaf74cb952a61 | shaileshr/leetcode | /binaryTrees/create_list_from_tree.py | 907 | 4 | 4 | from typing import List
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def create_list_of_leaves(tree: BinaryTreeNode) -> List[BinaryTreeNode]:
# TODO - you fill in here.
#result = []
#def create... |
3f2430fdf31e1e51064473a1a1de043e7299de17 | MotherTeresaHS/ICS3U-2019-Group22 | /docs/readthedocs_examples/egg+bomb_function_example.py | 1,335 | 3.5625 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Dec 2019
# This file is the contains the egg and bomb moving functions for Egg collector
def game_scene():
# Function to make eggs reappear at the top of the screen
def show_egg():
for egg_number in range(len(eggs)):
if e... |
886597afcc7737a15d17249d495c02b420d8f12c | IHAGI-c/GIS_class_2 | /decorator2.py | 326 | 3.796875 | 4 | def decorator(func):
def decorated(a, b):
if a > 0 and b > 0:
func(a, b)
else:
print('err')
return decorated
@decorator
def area(a, b):
T_A = a * b * 1/2
S_A = a * b
print('삼각형의 넓이 :', T_A)
print('사각형의 넓이 :', S_A)
area(2,8)
area(-2,4) |
dff38823f0c0b8932ac6f4ae4362bec85c9fc3fd | Cathryne/Python | /ex31.py | 2,723 | 4.40625 | 4 | # Exercise 31: Making Decisions
# http://learnpythonthehardway.org/book/ex31.html
# enables restarting of program
import sys
import os
def restart_program():
"""Restarts the current program, without returning anything before-hand
Hence, clean-up and save data before calling."""
python = sys.executable
... |
b116cdb1760778af80afabb2e367dfd1e982aef3 | EdikCarlos/Exercicios_Python_basico | /ex_Aumento_multiplo.py | 346 | 3.78125 | 4 | sal = float(input('Qual o valor do salário atual do funcionário?: '))
sal1 = sal + (sal * 10/100)
sal2 = sal + (sal * 15/100)
if sal <= 1250 :
print('O salário do funcionário terá um aumento de 15%, indo para R${:.2f}.'.format(sal2))
else:
print('O salário do funcionário terá um aumento de 10%, indo para R${:.2... |
fcc607412cf4bc6fe9cc73bc32504498b6ca47b1 | udayreddy026/pdemo_Python | /logical_aptitude/08-04-2021/Armstrong.py | 562 | 4.0625 | 4 | # # Armstrong Number means number ex:153 = 1cub+5cub+3cub = same as give number is called armstrong
#
# num = 153
# temp = num
# arm_total = 0
# while num > 0:
# l_num = num % 10
# num = num // 10
# arm_total = arm_total+(l_num**3)
# # print(arm_total)
#
# if arm_total == temp:
# print(arm_total, "is a... |
d1bd4b8f9483d961a0bc151fa10d5299ef3befeb | shikhalakra/python-code | /python_code1/candidate_code_1488906186.py | 486 | 3.671875 | 4 |
''' Read inputSTDIN. Print your output to STDOUT '''
#Use input() to read inputSTDIN and use print to write your output to STDOUT
def main():
n=int(raw_input())
for i in xrange(0,n):
for j in xrange(0,i):
print " ",
for k in xrange(0,n-i):
print "*",
for l i... |
d8e56d189545c8e3269f4727da34e595866353b8 | leorossa/first_platformer | /player.py | 1,934 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygame import *
MOVE_SPEED = 7
WIDTH = 22
HEIGHT = 26.5
COLOR = "#7cdbef"
JUMP_POWER = 10
GRAVITY = 0.35 # Сила которая удет тянуть наш прямоугольник
class Player(sprite.Sprite):
"""класс нашего прямоугольника"""
def __init__(self, x, y):
sprite.Spr... |
026a1a25d52e9fb46ad80ea9c7208b2d43981f27 | LexLau/dev-sprint2 | /chap7.py | 451 | 3.90625 | 4 | # Enter your answrs for chapter 7 here
# Name: Alex
# Ex. 7.5
def estimate_pi():
total = 0
k = 0
factor = 2 * math.sqrt(2) / 9801
while True:
num = factorial(4*k) * (1103 + 26390*k)
den = factorial(k)**4 * 396**(4*k)
term = factor * num /den
total += term
if abs(term) < 1e-15: break
k += 1
return 1... |
7271b4f9cae55ed3257ea33a8d77ea7b7979499c | 3salaz/python-Devops | /scripts/scriptThree.py | 196 | 4.21875 | 4 | # Given a word
# Have the program remove the given suffix
# Use the strip method
# Strip Method
def suffixStrip(suffix, word):
return print(word.rstrip(suffix))
suffixStrip('ed',"murdered")
|
d30565c4578a12deb775c04d6f42c8cd27420934 | RJBrooker/insult.ai | /insultAI.py | 1,141 | 3.6875 | 4 | """
Insult.AI is an API for predicting the offensiveness of insults. It takes a piece of text and returns a prediction of how insulting it is.
Its built using hug, gunicorn and pyTorch. The model is trained on top of torchMoji [1] using transfer learning and the “Detecting Insults In Social Commentary” dataset [2]. ... |
f168c90dd32996fca9d37991aad6938260189345 | EDG-UPF-ADS/Python-1 | /Todas/somatorio Z.py | 214 | 3.796875 | 4 | # FUAQ ler valor para Z. calcular e mostrar o somatório
# dos valores pares entre 1 e z.
z=int(input('Insira um Numero p/ Somatório: '))
acum=0
for i in range(2,z):
if(i%2==0):
acum=acum+i
print(acum) |
8612554ef86f3e5cb07a58fefea7d570f5ef115a | martsavy/stepik-basic-python | /exercises/func13_13.5.2.py | 1,139 | 4.34375 | 4 | """ Змеиный регистр
Напишите функцию convert_to_python_case(text), которая принимает в качестве аргумента строку
в «верблюжьем регистре» и преобразует его в «змеиный регистр».
Примечание 1. Почитать подробнее о стилях именования можно тут.
Примечание 2. Следующий программный код:
print(convert_to_python_case('ThisI... |
95907c6f1fb8ae387bbdb1303443b43116d40baf | tonyzhangqi2000/learning | /day02/exercise05.py | 232 | 3.59375 | 4 | """
练习:判断闰年
四年一润,百年不润
四百年再润
"""
import day01.helloworld as hw
year = int(input("输入年:"))
print((year % 400) == 0 or ((year % 4) == 0 and (year % 100) != 0))
hw.HW() |
12e1b6c65dfed071739226aee435641b5021b25a | dolomaniuk/python_project | /cours/week_1/KMperDay/solution.py | 124 | 3.734375 | 4 | N = int(input()) # km per day
M = int(input()) # count of day
days = M // N
if M % N > 0:
days += 1
print(days)
|
528b8ac11e24dc3a672293e151fa8f4d307bb4b6 | ozmaws/Chapter-2-Projects | /Project2.9.py | 414 | 4.1875 | 4 | #math notes
#10,000km between npole and equator
#90 degrees between npole and equator
#1 degree = 60 min
#1 min = 1 mile
#Request the inputs
kilometer = int(input("Enter the number of kilometers: "))
# Compute the nautical miles
nauticalMiles = ( kilometer / 10000 ) * 90 * 60
# Display the corresponding ... |
9f515d876147d885018c5b8f4b7728db9e10b206 | diegomonroy/Platzi-Curso-de-Python-y-Django | /clases.py | 598 | 3.59375 | 4 | class Persona:
def saludo_general(self):
return "Hola Persona"
class Estudiante(Persona): #Hereda de object, siempre se nombra con mayuscula
def __init__(self, nombre, edad): #Es el cosntructor, self se usa siempre en clases
self.nombre = nombre
self.edad = edad
def hola(self): #Es la funcion qu... |
893f0d34e8e792f675420b6e24fef7f9190495f3 | rachelkelly/game | /main.py | 2,383 | 3.84375 | 4 | # first game maybe
class Room(object):
def __init__(self):
#self.name = name
### doooon't get it here
#self.foo = thing1
#self.bar = thing2
# these are placeholdery, I feel like putting "pass"
# in the __init__ fn would be a bad time at this juncstuah
# zed did also say to not put too much in the __ini... |
221c6092a536825b8275a329c5118b1bccbccc11 | kensenwangka/UJIAN_1 | /KENSEN_20DESEMBER2019_UJIAN_1.py | 1,220 | 3.703125 | 4 | # Soal 1
def hashtag(string):
hashtag = "".join(string.title().split())
return [False, f"#{hashtag}"][bool(string and 0 < len(hashtag) <= 140)]
# print(hashtag("Helo there how are you doing"))
# print(hashtag(" "))
# Soal 2
def create_phone_number(n):
return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
... |
a064fa90bb4314027b4814da9a7d66ede0152171 | deepsinghsodhi/python-OOPS-assignments | /inheritance task/RBI bakn_inheritance.py | 3,830 | 4.1875 | 4 | '''
All the banks operating in India are controlled by RBI. RBI has set a well defined guideline
(e.g. minimum interest rate, minimum balance allowed, maximum withdrawal limit etc)
which all banks must follow. For example, suppose RBI has set minimum interest rate
applicable to a saving bank account to be 4% annuall... |
120432dd70141685477c73483f0d741830505204 | gbaghdasaryan94/Kapan | /Garnik/Python 3/Loops/2.py | 450 | 4.28125 | 4 | # 2. Write a Python program to convert temperatures to and from celsius, fahrenheit.
temp = input("Enter temperature: ")
if temp[-1] == 'C' and temp[:-1].isdigit():
print("The temperature in farenheit is", (int(temp[:-1]) * 9/5 + 32))
elif temp[-1] == 'F' and temp[:-1].isdigit():
print("The temperature in cel... |
2a0a4994e7174f9d0a0573030e1a86fb353a13be | ruinanzhang/Leetcode_Solution | /6-Largest Number Smaller In Binary Search Tree.py | 2,471 | 3.796875 | 4 | # Tag : Binary Search Tree
# 136.Largest Number Smaller In Binary Search Tree
# -----------------------------------------------------------------------------------
# Description:
# In a binary search tree, find the node containing
# the largest number smaller than the given target number.
# If there is no such number,... |
764f4d3a884ea043de7ebc0e70e80e0461e1aeb2 | Tammyqian/Python | /works/test/demo2.py | 701 | 3.78125 | 4 | import pandas as pd
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
print df1['HPI']
print '--------------------'
# if df1['HPI'] >= 80 :
# print df1['HPI'][0]
# i... |
89268608f88608bc648a807a48fc36c634ac18b4 | nchanay/night-class | /python labs/contactoop.py | 1,205 | 4 | 4 | # contact list with OOP
class ContactList:
"""
Contact list with class objects
"""
def __init__(self, csv=None, props=None):
if csv is None:
self.props = props
self.contacts = {}
else:
self.load(csv)
def load(self, csv):
"""
rea... |
edc76bb95787df715aaad8814b7494b9626f516d | nsdeo12/thinkPython | /Data/5_Execption Handling/3_Exception_finally.py | 810 | 3.609375 | 4 | try:
testfile = open('data.txt')
try:
txns = testfile.readlines()
print ("File data = ",txns)
finally:
print ("In Inner finally")
except IOError:
print ('unable to access test file\n')
finally:
print ("In Outer finally")
#testfile.close()
p... |
e186e1228ac647348157f1cc7fbd633399a577ea | t4d-classes/python_03222021_afternoon | /language_demos/dictionary2_demo.py | 347 | 3.921875 | 4 | person = {
"first_name": "Bob",
"last_name": "Smith"
}
# print(person["age"])
# print(person.get("age"))
# print(person.get("first_name"))
# if "age" not in person:
# person["age"] = 34
# print(person["age"])
print(person.setdefault("age", 34))
print(person.popitem())
print(person.pop("address", "123 ... |
6c46cddf38030d28f463267c8772ff3d1512c32c | ojhermann-ucd/comp10280 | /p19p3.py | 4,686 | 3.8125 | 4 | """
Pseudocode
create list of items we want to find, count, and compare
create associated index list
on each line:
- count each bracket and associated partner
- keep a running tally
compare the counts and report accordingly
"""
import sys
import os
import datetime
#list of strings to find in the document
sList = ["(... |
4494c79f8b28b0d03b657746752ad6b2f62e77a7 | fabinhosp2/lista-exercicios-python | /aula001_Exe003/calcula.py | 970 | 4.15625 | 4 | class Calculadora:
def soma(self, num1, num2):
return num1 + num2
def sub(self, num1, num2):
return num1 - num2
def multi(self, num1, num2):
return num1 * num2
def divi(self, num1, num2):
return num1 / num2
def calcula_todos(self, num1, num2):
print(f'As... |
7835e3bfdbaaa90472e8c155bef216d9a0af7d20 | Aasthaengg/IBMdataset | /Python_codes/p02594/s904973923.py | 94 | 3.890625 | 4 | import math
X = int(input())
if X>=30:
aircon='Yes'
else:
aircon='No'
print(aircon) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.