blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f67082924240fd2b8dd73006bde9e35a005342ba | yuryanliang/Python-Leetcoode | /100 medium/6/299 bulls-and-cows.py | 2,780 | 4.25 | 4 | """
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls... | true |
a551c51e0aba623ab79b53dc7b9ea1c039f1e3cc | ZdenekPazdersky/python-academy | /Lesson8/8.49_prime_numbers.py | 2,704 | 4.46875 | 4 | # ####2DO
# Your goal in this task is to create two functions:
#
# 1. list_primes
# Function that will list all the prime numbers up to the specified limit, e.g. list_primes(10) will list all the prime numbers from 0 to 10 including. The function should return a set or a list of prime numbers found.
#
# Example of usin... | true |
461dee7e05ee938b79e15b20ef369149601d91ba | ZdenekPazdersky/python-academy | /Lesson1/1.7-List.py | 1,435 | 4.3125 | 4 | #2do
# Create script, which will:
#
# assign an empty list to variable candidates,
# print the content of variable candidates introducing it with a string 'Candidates at the beginning:',
# assign a list to variable employees, containing strigns: 'Francis', 'Ann', 'Jacob', 'Claire',
# print employees content introducing... | true |
f6174ef98fe1c5fbe6b16402f882c82c8e9e39ea | ZdenekPazdersky/python-academy | /Lesson1/1_buying_cars.py | 929 | 4.375 | 4 | # ###2do
# #In the Python window you already have Mercedes and Rolls-Royce prices listed (don't forget to covert string to integer!). In addition, you have to create a variable that will ask the user for the extra cost. Then you will need to calculate:
# The price for two Mercedes,
# The Mercedes and Rolls-Royce prices... | true |
05b84ffa87c8d326935e1ac2aab5f0e027d9b5e0 | ZdenekPazdersky/python-academy | /Lesson7/7.41_reversed.py | 978 | 4.40625 | 4 | ####2DO
# Your task is to create a function that will imitate the built-in function reversed(). It will take any sequence as an input and will return a list of items from the original sequence in reversed order.
#
# Example of using the function:
#
# >>> reversed(range(10))
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>> revers... | true |
0c736360ff83966e361a231021f6b9e6b9482ed3 | mmaravilla28/tarea_3 | /calculadora.py | 2,689 | 4.125 | 4 | #definir clase CalculadoraBasica
class CalculadoraBasica:
#Menu de opciones
def Menu(self):
print('\n1)SUMAR 2)RESTAR 3)MULTIPLICAR 4)DIVIDIR 5)SALIR')
#constructor de la clase
def iniciar(self, num1, num2):
self.num1 = num1
self.... | false |
eb7e32e6c9d29fe746f5e48e3cc82bd0ae3f7018 | 4BPencil/hello-world | /salary_with_try_except_loops.py | 491 | 4.15625 | 4 | #asking for input
h=input("hours: ")
r=input("rate: ")
#nutrilizing input errors
try:
ih=float(h)
ir=float(r)
except:
ih=-1
ir=-1
#re-asking for input if there are some errors
while ih==-1 or ir==-1:
print("Please enter a numerical value")
h=input("hours: ")
r=input("rate: ")
try:
... | true |
2d7c28b85fb3133aaba47533de077cdd16e4a802 | yohanesusanto/Markovchaintextgenerator | /markov_chain_text_generator.py | 2,486 | 4.21875 | 4 | # https://blog.upperlinecode.com/making-a-markov-chain-poem-generator-in-python-4903d0586957
# I found this on the web where a text-file is read, first. Following this, for each word in
# the text-file as key, a Python-Dictionary of words-that-immediately-followed-the-key was
# constructed. We start from a random-in... | true |
57367bee7da71ff6af5f18f68296240fda53b7d1 | gkimetto/PyProjects | /GeneralPractice/ListComprehension.py | 415 | 4.21875 | 4 |
x = [i for i in range(10)]
print(x)
squares = []
squares = [i**2 for i in range(10)]
print(squares)
inlist = [lambda i:i%3==0 for i in range(5)]
print(inlist)
# a list comprehension
cubes = [i**3 for i in range(5)]
print(cubes)
# A list comprehension can also contain an if statement to enforce
# a condition on... | true |
d6fca675a0adb8f5a09db74ccc24d3b540ceb578 | gkimetto/PyProjects | /GeneralPractice/OddOrEven.py | 2,323 | 4.375 | 4 | '''
Exercise 2:
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an
even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: on... | true |
b413b106ed1265d8fbfd7748c0d04678475d9c04 | Teju-28/321810304018-Python-assignment3 | /321810304018-Three strings comparision.py | 658 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Take three inputs from user and check:
#
# 1. all are equal
# 2. any two are equal
# In[1]:
str1=str(input("Enter first string:"))
str2=str(input("Enter second string:"))
str3=str(input("Enter third string:"))
if (str1==str2==str3):
print("All Strings are equal")
eli... | true |
49f65af45d020264ca9c06467432b2c80784e5af | dongyuehanxue/python | /untitled/python_yunsuanfu.py | 2,623 | 4.5 | 4 | """
Python位运算符
& 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0
| 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。
^ 按位异或运算符:当两对应的二进位相异时,结果为1
~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1
<< 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。
>> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数
"""
"""
Python逻辑运算符
and 布尔"与"
如果 x 为 ... | false |
1dd8680331523d8688ae20e57dd58800f4d01a99 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter2/example_vector.py | 1,705 | 4.5625 | 5 | """
textbook example: class Vector
"""
class Vector:
""" Represent a vector in a multi-dimensional space"""
def __init__(self, d):
if not d >= 1:
raise ValueError("Dimension number must >= 1")
self._coordinates = [0] * d
def __len__(self):
return len(self._coordin... | false |
8e9a5d0c7b5e4fd51b61170d49ec38caeedf3df3 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter7/q1.py | 1,203 | 4.1875 | 4 | """
find the second-to-last node in a singly linked list.
the last node is indicated by a "next" reference of None.
Use two pointers: this idea is quite common in Leetcode
"""
from example_singly_linked_list import SinglyLinkedList
def find(linked_list):
# import a linked list, find the second-to-last node, prin... | true |
557bf6b8bd015627f607db208d919275ed3d275f | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter6/q13.py | 617 | 4.25 | 4 | """
a deque with sequence (1,2,3,4,5,6,7,8).
given a queue,
use only the deque and queue,
to shift the sequence to the order (1,2,3,5,4,6,7,8)
"""
from example_queue import ArrayQueue
from example_double_ended_queue import ArrayDoubleEndedQueue
D = ArrayDoubleEndedQueue()
for i in range(1, 8+1): D.add_last(i)
Q... | true |
49e88e6fe9c032dd82cec7a297c9a1b45c51d311 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter1/q1.py | 712 | 4.40625 | 4 | def is_multiple(n, m):
'''
if n = m * i, then return True, else return False
'''
if n == 0 and m == 0:
return True
elif m == 0:
return False
elif n % m == 0:
return True
else:
return False
if __name__ == '__main__':
print("{}: {} is a multiple of {}".fo... | false |
470b2df2a6bc64b4d49ede0eaf8e7e37e24df276 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter6/q21.py | 1,326 | 4.375 | 4 | """
use a stack and queue to display all subsets of a set with n elements
"""
from example_stack import ArrayStack
from example_queue import ArrayQueue
def subset_no_recursion_use_array_queue(data):
"""
stack to store elements yet to generate subsets,
queue store the subsets generated so far.
method:... | true |
94ff02e3cac8ae2fcd69ad2f9dde568f470a4650 | luke-mao/Data-Structures-and-Algorithms-in-Python | /chapter7/q3.py | 814 | 4.125 | 4 | """
describe a recursive algorithm that count the number of nodes
in a singly linked list
method:
similar to the counting of the height of a tree,
quite simple and straightforward
"""
from example_singly_linked_list import SinglyLinkedList
def count(node):
"""give the head element, count the number"""
if n... | true |
0297636bbc9549fdf551e3bf55740326e9c05f34 | je-clark/decoratorsexamples | /advanced_decorated_function.py | 1,445 | 4.21875 | 4 | # This is an advanced example for decorators. Not only can we access information
# about the function and control its execution, but the decorator can take arguments
# so that it can be reused for multiple functions
from random import choice, randint
def add_description(operation = ""): # Contains details about the d... | true |
ebea4a362f1872bd045bd5cd66f63c84586d31d8 | ymsonnazelle/MITx-6.00.1x | /odd.py | 440 | 4.28125 | 4 | '''
Week-2:Exercise-Odd
Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise.
You should use the % (mod) operator, not if.
This function takes in one number and returns a boolean.
'''
#code
def odd(x):
'''
x: int
returns: True if x is odd, Fal... | true |
3949de29e6514620371c592cb0a851ca575f7c0f | serviru/algo | /Lesson_1/4.py | 1,006 | 4.21875 | 4 | """
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Прог... | false |
d6ab975cd8404bb702b4bc7bd4a931914dea1ab9 | Constantino/Exercises | /Python/fill_it_nice.py | 796 | 4.15625 | 4 | from sys import argv
def quick_sort(List):
if len(List) > 1:
pivot = len(List)/2
numbers = List[:pivot]+List[pivot+1:]
left = [e for e in numbers if e < List[pivot]]
right =[e for e in numbers if e >= List[pivot]]
return quick_sort(left)+[List[pivot]]+quick_sort(right)
return List
de... | true |
9d43b7e00a1fdd19d9d3f6e17517347dbcee3b67 | leihuagh/python-tutorials | /books/AutomateTheBoringStuffWithPython/Chapter13/PracticeProjects/P4_PDFbreaker.py | 1,497 | 4.21875 | 4 | # Say you have an encrypted PDF that you have forgotten the password to, but you
# remember it was a single English word. Trying to guess your forgotten password
# is quite a boring task. Instead you can write a program that will decrypt the
# PDF by trying every possible English word until it finds one that works.
#
#... | true |
01146104e5b2d6fb2000615363f9103a9ba7c385 | fedeweit-2/Programming | /problemset_08_weithaler/priority_queue.py | 1,552 | 4.25 | 4 | # Implementation of the unbounded Priority Queue ADT using a Python list # with new items appended to the end.
class PriorityQueue:
# Create an empty unbounded priority queue.
def __init__(self):
self._qList = list()
# Returns True if the queue is empty.
def is_empty(self):
return len(... | true |
ef566a5ea5da4dc682bd2948db1b60cc5ca4d5b1 | bouzidnm/python_intro | /notes_27Feb2019.py | 2,620 | 4.75 | 5 | ## Notes for 27 Feb 2019
## For loops; .append(); .keys(); .values()
## Used to iterate over a sequence of values; to simplify redundant code
## Print out each item of a list individually
my_list = ['A', 'B', 'C', 'D', 'E']
## Two types of for loops
### Easy way: prints item
for i in my_list: # 'i is a variable that ... | true |
410bd8f7ae4f92900d83942c680df24852cbe029 | kevinlong206/learning-python | /70sum.example.py | 360 | 4.1875 | 4 |
# there is a list comprehension in this one
# but it the entire list needs to be created
# before sum can run on the list
s1 = sum([n**2 for n in range(10**6)])
# these are the same, s3 just has redunant parenthesis
# this is a generator expression
s2 = sum((n**2 for n in range (10**6)))
s3 = sum(n**2 for n in range... | true |
e1be6d365efe0a2972c48dff9551d9d53fb53778 | drafski89/useful-python | /file_handling/file_handling.py | 1,577 | 4.4375 | 4 | # Purpose: Demonstrate basic file handling with Python 2
# Declare the input and output file names (same directory)
# Note: Possible to declare the full path if reading from another directory
INPUT_FILE_NAME = "input.txt"
OUTPUT_FILE_NAME = "output.txt"
# Open the input file as "r" reading
with open(INPUT_FILE_NAME, ... | true |
68021c77c0ee0ad4339ea6f035207dae6ea9a485 | drafski89/useful-python | /loops/for.py | 305 | 4.1875 | 4 | # Basic example of implementing a for-loop
# Create a variable called count to hold the current count
count = 1
print x
# For loop
# for [variable] in range (start amount, stop amount, increment amount)
for count in range(1, 12, 1):
# Add 1 to count and print the result
count = count + 1
print count | true |
5f4a1d080a21abda6e4845432c751bb691c6378b | GitOrangeZhang/pythonDemo2 | /src/one/test7.py | 270 | 4.1875 | 4 | str='abcdefghij'
#查看字符串长度
# print(len(str))
#
# print(str[:])
#
# print(str.startswith('b'))
# print(str.endswith('j'))
#给定一个字符串str1,返回使用空格或者\t分割后的倒数第二个字符
str1 = 'my name is zhang cheng'
print(str1.split()) | false |
e1d807afe73812d5149402af15cac11853f59233 | o9nc/CSE | /Jazmeene Hangman.py | 1,127 | 4.15625 | 4 | import random
# import string
"""
A general guide for Hangman
1. Make a word bank - 10 items
2. Pick a random item from list
3. Add a guess to the list of letters guessed
4. Reveal letters already guessed
5. Create the win condition
"""
movie_list = ["Love in basketball", "Vampire diaries", "Insidious", "Split", "The ... | true |
d854cfb16d1bdb14f8d9e70f84718d40557b371b | SuperLavrik/Class_work | /work_6.py | 558 | 4.125 | 4 | def is_year(year):
return year %4 ==0 and year %100 != 0 or year %400 == 0
# if year %4 ==0 and year %100 != 0 or year %400 == 0:
# return True
#
# else :
# return False
# x = 4
# y = 101
# if 3 <= x <= 100 and x !=4 or y >= 100 and y <= 200 :
# print ("inside")
# else :
# print("outside")
year =... | false |
a99987bd4112710b8d4e4e10c9de1e9c7e3710ba | humengdoudou/a_func_a_day_in_python | /test_random_20180329.py | 1,275 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# This is the python code for testing random function in python lib.
#
# Author: hudoudou love learning
# Time: 2018-03-29
import random
# random lib test
print(random.random()) # randomly generate a float in [0,1)
print(random.uniform(1, 5)) ... | true |
8dbdc538a049d3e4552a1ddc9e328975bd4abbe6 | cvhs-cs-2017/practice-exam-lucasrosengarten | /Range.Function.py | 291 | 4.34375 | 4 | """Use the range function to print the numbers from 1-20"""
x = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
print (x)
"""Repeat the exercise above counting by 2's"""
a = (2,4,6,8,10,12,14,16,18,20)
print (a)
"""Print all the multiples of 5 between 10 and 200 in DECENDING order"""
| true |
c6c6d77afa2d449f6763a5bb23130d419a37a84a | Olugbenga-GT/Python-Chapter-three | /Cubes _and _Squares.py | 597 | 4.5625 | 5 | # 3.7 (Table of Squares and Cubes) In Exercise 2.8, you wrote a script to calculate the
# squares and cubes of the numbers from 0 through 5, then printed the resulting values in
# table format. Reimplement your script using a for loop and the f-string capabilities you
# learned in this chapter to produce the following ... | true |
399a79413492afd93a739cab16fe2e8a67d08d20 | Tusharsharma118/python-learning | /basics/enhanced_calculator_with menu.py | 873 | 4.15625 | 4 | number1 = input('Enter First Number:')
number2 = input('Enter Second Number:')
def menu():
print('1 - Add \n2 - Subtract \n3 - Multiply \n4 - Divide \n5 - Exit')
def calculator(choice, number1, number2):
num1 = int(number1)
num2 = int(number2)
if choice == 1:
print (num1 + num2)
... | false |
877fcdfb0769400495a89e19e70e4d3404fca59e | deepikavashishtha/pythonLearning | /gen.py | 525 | 4.3125 | 4 | """Modules for demonstrating generator execution"""
def take(count, iterable):
"""
This method takes items from iterable
:param count:
:param iterable:
:return: generator
Yields: At most 'count' items from 'iterable'
"""
counter = 0
for item in iterable:
if counter == cou... | true |
bd09846b2d246ce7e11ebf73af0254c249690554 | utkarshsaraf19/python-object-oriented-programming | /08_docstrings/eigth_class.py | 1,263 | 4.375 | 4 | import math
class Point:
"""Represents the point in two dimensional coordinate"""
def __new__(cls):
"""
Constructor class which is called before object is created
"""
print("Creating instance")
return super(Point, cls).__new__(cls)
# default values initializer
... | true |
3b227b93f6e65cd6c6ff748afec1474172627bb8 | jp-tran/dsa | /problems/subsets/evaluate_expression.py | 1,291 | 4.4375 | 4 | """
Given an expression containing digits and operations (+, -, *),
find all possible ways in which the expression can be evaluated
by grouping the numbers and operators using parentheses.
Soln: If we know all of the ways to evaluate the left-hand
side (LHS) of an expression and all of the ways to evaluate
the rig... | true |
113e00314debeb37a36fcf3e82b203f5d5a3dd34 | yaswanth12365/coding-problems | /Ways to sort list of dictionaries by values in Python.py | 893 | 4.5625 | 5 | # Python code demonstrate the working of sorted()
# and itemgetter
# importing "operator" for implementing itemgetter
from operator import itemgetter
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
# using sorted an... | true |
d658869baf27a2d2dc76621f91fbece0700f136c | yaswanth12365/coding-problems | /Python program to interchange first and last elements in a list.py | 342 | 4.25 | 4 | # Python3 program to swap first
# and last element of a list
# Swap function
def swapList(list):
# Storing the first and last element
# as a pair in a tuple variable get
get = list[-1], list[0]
# unpacking those elements
list[0], list[-1] = get
return list
# Driver code
newList = [12, 35, 9, 56, 24]
prin... | true |
886af12ca48a2c80ab930372a4c03897c6cc5b70 | wangjiliang1983/test | /crashcourse/ex08_08_albumwhile.py | 448 | 4.15625 | 4 | def make_album(singer, album):
album_dict = {'singer': singer, 'album': album}
return album_dict
while True:
print("\nPlease give me the singer name and album name:")
print("(Enter 'q' to quit)")
singer = input("Please enter the singer name: ")
if singer == 'q':
break
album = input... | true |
f8bfeceaa6e54f795b199327b66439031eca81f5 | rayallen20/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python | /Chapter1. Introduction/code/input.py | 268 | 4.1875 | 4 | aName = input('Please enter your name ')
print("Your name in all capitals is ", aName.upper(), "and has length ", len(aName))
sRadius = input("Please enter the radius of the circle ")
radius = float(sRadius)
diameter = 2 * radius
print("diameter is %E\n" % diameter)
| true |
ae4cf9a310cb91aa9e3f5c3f8f59178816f898c2 | lukapejic23/pythonintro | /big_fibonacci.py | 276 | 4.34375 | 4 | def big_fibonacci():
previous_num, result = 0, 1
desiredlength = int(input("enter the number of digits : "))
while len(str(result)) < desiredlength:
previous_num, result = result, previous_num + result
return result
print(big_fibonacci()) | true |
009c7bb85317759c5b43e03e579f3186251f5d1e | Platforuma/Beginner-s_Python_Codes | /9_Loops/32_For_Loop--Counting-char-in-string.py | 466 | 4.28125 | 4 | '''
Write a Python program that accepts a string and calculate the number of
digits and letters.
Sample Data : Python 3.2
Expected Output :
Letters 6
Digits 2
'''
string = input("Enter a string: ")
digit = length = 0
for char in string:
if char.isdigit():
digit = digit + 1
elif char.... | true |
d2f76c0be047088b29d7ea7097a8b4e0ea4c8ce4 | Platforuma/Beginner-s_Python_Codes | /8_Conditional_Statements/18_if_Dictionary--Month-Days.py | 2,510 | 4.34375 | 4 | '''
Write a Python program to convert month name to a number of days.
Expected Output:
List of months: January, February, March, April, May, June, July, August
, September, October, November, December
Input the name of Month: February
No. of ... | true |
c10a2dcde5720729a9f65896926ccc379a198563 | Platforuma/Beginner-s_Python_Codes | /6_Dictionary/1_Dictionary--adding-3-dicts.py | 756 | 4.21875 | 4 | '''
Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result :
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
'''
dic1={1:10, 2:20}
print('dic1: ', dic1)
dic2={3:30, 4:40}
pr... | false |
1cb8ef9470f34c0afaa29c2f2b63b4a76b1c5416 | marcelosdm/python-alura | /app.py | 1,870 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
def cadastrar(nomes):
print 'Digite um nome'
nome = raw_input()
nomes.append(nome)
def listar(nomes):
print 'Listando nomes'
for nome in nomes:
print nome
def remover(nomes):
print 'Qual nome você deseja remover?'
nome = raw_input()
nomes.remove(nome)
... | false |
38c52b307d8135e8ee48d71215fe91edbda459bf | TomKite57/advent_of_code_2020 | /python/headers/day2.py | 1,701 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Day 2 of Advent of Code 2020
This script will read a file formatted as such:
int1-int2 char: string
and will process the code according to two criteria
1) int1 <= string.count(char) <= int2
2) (string[int1-1], string[int2-1]).count(char) == 1
Tom Kite - 02/12/2020
"""
from aoc_tools.adve... | true |
f025a098e554f22e773293e2af3086f3c4c60233 | pallegithub/Python | /Assignment5_case3.py | 220 | 4.1875 | 4 | def multiplication(num):
for i in range(1,11):
print(num,"X",i,"=",num*i)
number = int(input("Enter any number==>"))
print("Multiplication Table for",number)
print("")
multiplication(number)
print("") | false |
ea668e1782babe68ed94acd935f12034030bb7c9 | pallegithub/Python | /Assignment5_case5.py | 471 | 4.28125 | 4 | def max(num1,num2,num3):
if num1>=num2 and num1>=num3:
print("Maximum of",num1,",",num2,",",num3,"is",num1)
elif num2>=num1 and num2>=num3:
print("Maximum of",num1,",",num2,",",num3,"is",num2)
else:
print("Maximum of",num1,",",num2,",",num3,"is",num3)
number1 = int(... | false |
d6bcd3d1109cc2db021ae1e6850cfad606f11e05 | pallegithub/Python | /Assignment5_case8.py | 251 | 4.15625 | 4 | def factorial(n):
if n == 0:
print("")
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(result)
return result
n=int(input("Enter the number=======>"))
factorial(n)
| true |
49dc5f99bdc0a52cebad58b4c102456ad0383451 | estoicodev/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/2-read_lines.py | 516 | 4.34375 | 4 | #!/usr/bin/python3
"""This module defines the read_lines function"""
def read_lines(filename="", nb_lines=0):
"""Reads n lines of a text file (UTF8) and prints it to stdout
Args:
filename (str): Filename
nb_lines (int): number of lines to read
"""
with open(filename, encoding='utf-8') as file... | true |
1bc0031510add098424fd3a602ed2c68445f64c6 | nicolasilvac/MCOC-NivelacionPython | /27082109/000619.py | 1,325 | 4.125 | 4 | import numpy as np
a = np.zeros(3) #crea una matriz de 1 fila y 3 columnas
print a
#[ 0. 0. 0.]
print type(a[0]) #entrega el tipo de elemento numero 0 del array a
#<type 'numpy.float64'>
z = np.zeros(10)
print z
#[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
z.shape = (10, 1) #cambia la forma del array
p... | false |
6504a26d94a200a40a376726a549f90017fb5784 | nairaaoliveira/ProgWeb | /Exercicios_Python/Lista 3_Python/q17_Lista3_Ex_Python.py | 702 | 4.125 | 4 | '''
17. A partir de dois números fornecidos pelo usuário, escreva uma das seguintes mensagens:
Os dois são pares
Os dois são impares
O primeiro é par e o segundo é ímpar
O primeiro é ímpar e o segundo é par
'''
def RetornaMensagem(n1, n2):
if (n1 % 2 == 0) and (n2 % 2 == 0):
return "Os dois são pares"
... | false |
759e320069935d34f7434e46fe0f667162b53f26 | nairaaoliveira/ProgWeb | /Exercicios_Python/Lista 5_Python/q01_Lista 5_Ex_Python.py | 386 | 4.34375 | 4 | '''1. Faça uma função que recebe uma quantidade desejada de itens e retorna uma
lista carregada com essa quantidade. Faça outra função para exibir esses itens
esperados por espaço em branco.'''
def ListaQuant(quant):
L = [12, 9, 5]
i = 0
while i < 3:
print(len(L[quant]))
break
... | false |
31bc6174231c4eddfc6d46e9ce624b9e89e5b9f9 | starryKey/LearnPython | /03-高级语法/17-协程/Example01.py | 1,889 | 4.15625 | 4 | # 案例01
list1 = [i for i in range(6)]
# list1是可迭代的,但不是迭代器
for index in list1:
print(index)
# range是个迭代器
for ind in range(3):
print(ind)
# isinstance案例
# 判断某个变量是否是一个实例
# 判断是否可迭代
from collections import Iterable
# 是可迭代的
list2 = [1,2,3,4,5]
print(isinstance(list2, Iterable))
# from collections import Iterator
... | false |
8732c89f39d09ae65d70f900e2ab925c346d600f | debajit13/100Days-of-Code | /Practice/Sum_of_first_&_last_digit.py | 324 | 4.125 | 4 | def sum(n): #calculate sum of the first and last digit
last_digit = n%10
first_digit = n
while(first_digit > 10):
first_digit = first_digit//10
s = first_digit + last_digit
return s
print("_____SUM OF FIRST AND LAST DIGIT_____")
number = int(input("Enter the number : "))
print(sum(numbe... | true |
f9c6385b3b4024830c34dd69cd813a906e253bc3 | ramondfdez/57Challenges | /1_InputProcessingOutput/6_RetirementCalculator.py | 1,295 | 4.625 | 5 | # Your computer knows what the current yearis, which means
# you can incorporate that into your programs. You just have
# to figure out how your programming language can provide
# you with that information.
# Create a program that determines how many years you have
# left until retirement and the year you can retire. I... | true |
a5e7632f74441340f70c9be95fda130df0b0f128 | ramondfdez/57Challenges | /7_WorkingWithFiles/44_ProductSearch.py | 1,522 | 4.21875 | 4 | # Create a program that takes a product name as input and
# retrieves the current price and quantity forthat product. The
# product data is in a data file in the JSON format and looks
# like this:
# {
# "products" : [
# {"name": "Widget", "price": 25.00, "quantity": 5 },
# {"name": "Thing", "price": 15.00, "quantity": ... | true |
9acd2a0ca2f4a748b78c5e01956821ce6eb66b7f | ramondfdez/57Challenges | /1_InputProcessingOutput/3_PrintingQuotes.py | 880 | 4.40625 | 4 | # Quotation marks are often used to denote the start and end
# of a string. But sometimes we need to print out the quotation
# marks themselves by using escape characters.
# Create a program that prompts for a quote and an author.
# Display the quotation and author as shown in the example
# output.
#
# Example Output
... | true |
5bad112b200e163bc45bc8371d13b0f41b0f13e0 | ramondfdez/57Challenges | /7_WorkingWithFiles/46_WordFrequencyFinder.py | 1,255 | 4.3125 | 4 | # Knowing how often a word appears in a sentence or block
# of text is helpful for creating word clouds and other types
# of word analysis. And it’s more useful when running it
# against lots of text.
# Create a program thatreads in a file and counts the frequency of words in the file. Then construct a histogram displa... | true |
f6e368eb5ae65130f7c0b7b26b64fbaf4d4f726c | ramondfdez/57Challenges | /2_Calculations/12_ComputingSimpleInterest.py | 1,364 | 4.3125 | 4 | # Computing simple interest is a great way to quickly figure
# out whether an investment has value. It’s also a good way
# to get comfortable with explicitly coding the order of operations in your programs.
# Create a program that computes simple interest. Prompt for
# the principal amount, the rate as a percentage, an... | true |
1ea4a6f2876cf5613140319832f031efa1ec3870 | ramondfdez/57Challenges | /6_DataStructures/38_FilteringValues.py | 1,189 | 4.40625 | 4 | # Sometimes input you collect will need to be filtered down.
# Data structures and loops can make this process easier.
# Create a program that prompts for a list of numbers, separated by spaces. Have the program print out a new list containing only the even numbers.
#
# Example Output
# Enter a list of numbers, separa... | true |
c41227cc0a11d76294c67a8362ba93b1d7562c42 | mohanraoroutu/PythonTraining | /Regex.py | 2,110 | 4.25 | 4 | # Example of w+ and ^ Expression
import re
xx = "mohan1678,education is fun"
r1 = re.findall(r"^\w+",xx)
print(r1)
# Example of \s expression in re.split function
import re
xx = "guru99,education is fun"
r1 = re.findall(r"^\w+", xx)
print((re.split(r'\s','we are splitting the words')))
print((re.split(r's... | false |
1cf1bff4094a457338c7a323d27381ea688c5aa2 | liuyang2239336/xuexi | /PythonTest/demo4.py | 620 | 4.21875 | 4 | # 1. 输入用户名和密码
# 2. 去判断登录是否成功- 如果登录成功-打印登录成功;反之,打印失败!
# 能够看懂就可以
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "" and password == "":
print("用户名或者面不能为空!")
exit() # 退出程序
# db的作用就是模拟数据
db = {"username":"test", "password":"test"}
# 如何去判断输入的密码和db里面的密码一致
if username == db.get("username") a... | false |
acf0cd446796519b7c0d70fb3b4c4b136462fec2 | arpan-k09/INFOSYS-PYTHON-PROG | /palindrome.py | 317 | 4.1875 | 4 | #PF-Assgn-31
def check_palindrome(word):
str1 = word
str2 = "".join(reversed(str1))
print(str2)
if str1==str2:
return True
else:
return False
status=check_palindrome("malayalam")
if(status):
print("word is palindrome")
else:
print("word is not palindrome") | false |
a86966cedb820536a599aaec9cbe373c3f7a659f | arpan-k09/INFOSYS-PYTHON-PROG | /6_1.py | 389 | 4.28125 | 4 | #PF-Assgn-40
def is_palindrome(word):
s = word.lower()
string = "".join(reversed(s))
if string == s:
return True
else:
return False
#Provide different values for word and test your program
result=is_palindrome("MadAMa")
print(result)
if(result):
print("The given word is a... | true |
4b8cf0ab6a4a0e6a4baa6118840c963513b3dbd9 | GarciaFrida/Python_Projects_DC | /multiple.py | 956 | 4.25 | 4 | #Create a program that will ask for a username and then a password.
#If the username or password length is less than 6 charecters give a too short message.
#if the username or password length is greater than 12 charecters give a too long message
#Have the user confirm the password in again.
#If the passwords match give... | true |
e8afc6fd440c9102c0c60ac608e4c8d2ad29c966 | GarciaFrida/Python_Projects_DC | /hello.py | 730 | 4.5 | 4 | my_name = "Frida"
#my_name is the variable name and it prints out the statement "Frida" which is my name
my_favorite_drink = "beet juice"
my_favorite_dessert = "cookie"
my_favorite_meal = "french fries and a big fat juicy burger"
#print(my_name)
#print(my_favorite_drink)
#print(my_favorite_dessert)
#print(my_favorite... | true |
a7eae1870e22708722fe5ebb8d5a8ae208eea9a0 | GarciaFrida/Python_Projects_DC | /name_welcome.py | 412 | 4.40625 | 4 | #Create a program that asks for your name and the returns it back to you with a greeting.
#Use Variables when possible
#Create a program that will ask for you age and then put 3 lines down and say "wow" at the end.
#Only 2 strings can be used.
print("Hi there, please insert your name ")
user_name = input()
print("W... | true |
6bf763f1050fb481c74265266eddba815411b32a | rtate7/CSS-225-Module-4 | /time.py | 421 | 4.21875 | 4 | # Edited for debugging by Robert Tate on 1/22/21
#
# Gets current time and wait time from user and prints the time
# when the wait will be completed
currentTimeStr = input("What is the current time (in hours 0-23)? ")
waitTimeStr = input("How many hours do you want to wait? ")
currentTimeInt = int(currentTimeStr)
wa... | true |
c00c0f0befdb7c80ed1d2fc8f46af15f8f8f8497 | enchantress085/Python-Basic | /Functions_loops/even_odd_num.py | 1,290 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Odd or even Number using for loops
"""
for n in range(1, 20): #-- [2,3,4,5,6,7,8,9.....]
for x in range(2,n):#-- [],[2],[2,3],[2,3,4]....
if n % x == 0:
print(f'{n} Equals {x} * {n//x} >')
break
else:
print(f"{n} is a prime Number >")
#... | true |
2bf0cd37388de534df591c7deaad55e45bafdbc5 | enchantress085/Python-Basic | /Functions/f_argument.py | 1,092 | 4.5 | 4 | """
You can call a function by using the following
types of formal arguments −
1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable-length arguments
"""
print("\n")
print("--------Required arguments-------\n")
def me(st):
print ("Print : ", st)
return
me("MD. Golam Maulla Shaju")
print(... | false |
a431d456c7bff65f589faf3675b398599b44a543 | enchantress085/Python-Basic | /advance_set.py | 976 | 4.46875 | 4 | """
A set is an unordered collection of items.
Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable.
We can add or remove items from it.
Sets can be used to perform mathematical set
operations like union, intersection,
symmetric difference etc.... | true |
bfdc139dac8ca8b94e190e2dd501f540934dc64f | sebaheredia/HO-python | /Ej1c.py | 771 | 4.125 | 4 |
# Importamos la libreria con las funciones que se van a utilizar
import numpy as np
# Aqui se define el numero a descomponer en numeros primos
n=2*3*5*7
print("n = ",n)
# El primer divisor de prueba se define 2, ya que todo numero es divisible por 1
i=2
# aux es un valor auxiliar que seria el ultimo cociente de la d... | false |
52aba787d8f08ce8b0b4da76027d837bb6cfb922 | Maopos/Basic_Python | /008_Sentencias_de_control/8.04_Condiciones_multiplies.py | 309 | 4.15625 | 4 | # Evaluacion de condiciones multiples.
print()
numero = int(input('Escriba un numero: '))
print()
if numero % 5 == 0 and numero >= 20 and numero <= 40:
print('El numero {} es divisible entre 5 y se halla entre 20 y 40'.format(numero))
else:
print('El numero no cumple los requerimientos.')
print() | false |
ae52b915af1beb863ad16ffb7674f31209196aa8 | Maopos/Basic_Python | /005_Tipos_de _Datos/5.03_complejos_complex.py | 677 | 4.125 | 4 | # Numeros Complejos
print()
numero_complejo = 2 - 3j #forma literal
print('Contenido variable compleja: ', numero_complejo)
print('El tipo de dato de numero_complejo es: ', type(numero_complejo))
print()
numero_complejo = complex(2, -3)
print('Contenido variable compleja: ', numero_complejo)
print('El tipo de dato ... | false |
b64e882d9ce63c2869fe0a387a0bf83ad7202876 | Maopos/Basic_Python | /005_Tipos_de _Datos/5.06_tuplas_tuple.py | 2,199 | 4.125 | 4 | # Tipo de dato compuesto - Tupla - estatico
print()
punto = (2, 5)
print('Tipo de dato', type(punto))
print(punto)
print('Cantidad de elementos:', len(punto))
print()
# Acceso a los elementos de una Tupla
x = punto[0]
y = punto[1]
print('El valor de x es: ', x)
print('El valor de y es: ', y)
print()
# Desempaq... | false |
064ddfe004bda126d3128c2c0f499dda2c5e3bd3 | Maopos/Basic_Python | /009_Ciclos/Ejercicios/9.08_cant_digitos_letras_txt.py | 507 | 4.1875 | 4 | # Ejercicio 9.8: Contar la cantidad de dígitos y letras que tiene un texto.
print()
texto = input('Escribe un texto: ')
print()
digitos = 0
letras = 0
spaces = 0
otros = 0
for i in texto:
if i.isnumeric():
digitos += 1
elif i.isalpha():
letras += 1
elif i.isspace():
spaces += 1
... | false |
3a692657fc46dfbd42609d9b2cbb2db41969449a | Maopos/Basic_Python | /020_Problemas_map_reduce_filter_zip/001_map.py | 530 | 4.34375 | 4 | ''' Problema #1:
Utilizar la función incorporada map() para crear una función que retorne una lista con la longitud de cada palabra (separadas por espacios) de una frase. La función recibe una cadena de texto y retornará una lista. '''
print('======================')
print()
frase = 'Bienvenidos a Python utilizando m... | false |
923a2750ce32aa7d85faff4dd2ca3b54dec3626f | Maopos/Basic_Python | /010_Errores_y_excepciones/10.03_indices_listas.py | 650 | 4.1875 | 4 | # Acceso de elementos de una lista
print('======================')
print()
lenguajes = ['Python', 'C#', 'Html', 'Css', 'Java', 'C', 'JavaScript']
print('Cantidad de lenguajes: ', len(lenguajes))
print('Primer elemento: ', lenguajes[0])
print()
indice = 7
try:
print('Ultimo elemento: ', lenguajes[indice])
except... | false |
f154da00adc92b4aee4b2782e23da8360820e5cd | maoriko/w3resource | /6 get list and tuple input.py | 316 | 4.34375 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
input_list = input("to get list please enter your numbers seperated with comma: ")
list = input_list.split(",")
tuple = tuple(list)
print('List :', list)
print('Tuple:', tuple) | true |
7296f0582bf06e594301717eb27c51d2cfbafc3b | anniboo/hw-and-les | /lesson 2.py | 934 | 4.15625 | 4 | friends = 'Максим Леонид1'
print(friends)
print(len(friends))
print(friends.find('Лео'))
print(friends.split())
friends = 'Максим;Леонид1'
print(friends.split(';'))
print(friends.isdigit())
number = '123'
print(number.isdigit())
print(friends.upper())
print(friends.lower())
# Форматирование строк
name = 'Leo'
age... | false |
28027fb02ced983b8365a26bae6b7b9ef4f4d39f | abhishekbisneer/Python_Code | /Exercise-24.py | 1,364 | 4.46875 | 4 | #Exercise 24 (and Solution)
'''
This exercise is Part 1 of 4 of the Tic Tac Toe exercise series.
The other exercises are: Part 2, Part 3, and Part 4.
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | ... | true |
09277ed6f52083f817f9bdc9226d7b14836b92a5 | abhishekbisneer/Python_Code | /Exercise-26.py | 2,855 | 4.15625 | 4 | #Check Tic Tac Toe Solutions
#Exercise 26
'''
This exercise is Part 2 of 4 of the Tic Tac Toe exercise series.
The other exercises are: Part 1, Part 3, and Part 4.
As you may have guessed, we are trying to build up to a full tic-tac-toe board.
However, this is significantly more than half an hour of coding, so we’r... | true |
e12517c6df4f7796b63bdc26efef650d43c127c6 | abhishekbisneer/Python_Code | /Exercise-33.py | 1,210 | 4.625 | 5 | #Birthday Dictionaries
#Exercise 33 (and Solution)
'''
This exercise is Part 1 of 4 of the birthday data exercise series.
The other exercises are: Part 2, Part 3, and Part 4.
For this exercise, we will keep track of when our friend’s birthdays are,
and be able to find that information based on their name.
Create a ... | true |
77a3451304bd206bd2ef1da261fa8dc55c14f3d1 | sandruskyi/CursoPythonOW | /EjerciciosVariables/ejerCadenas.py | 691 | 4.125 | 4 | #!/usr/bin/env python
"""
#1. Crear un programa que lea por teclado una cadena y un carácter, e inserte el carácter entre cada letra de la cadena. Ej: separar y , debería devolver s,e,p,a,r,a,r
cad = input("Cadena")
car = input("Caracter")
print(car.join(cad))
#2. Crear un programa que lea por teclado una cadena y un... | false |
96f6a4af0f3d01f702cc3785c70d2ae712206015 | SnyderMbishai/python_exercises | /reverse.py | 372 | 4.125 | 4 |
def reverse_string():
string = input("Write a sentence of your own choice: ")
new_string = []
string = string.split()
l = len(string)-1
for i in string:
new_string.append(string[l])
l -= 1
return (' '.join(new_string))
print(reverse_string())
#a simpler way
string2=input("sentence here: ... | true |
9f50209768c777ae643c87f4e036ffabed413545 | SnyderMbishai/python_exercises | /arithmetic.py | 761 | 4.15625 | 4 | """Create a program that reads two integers, a and b, from the user.Your program should
compute and display:
• The sum of a and b
• The difference when b is subtracted from a
• The product of a and b"""
from math import log10
def arithmetic():
a = int(input("Enter a number: "))
b = int(input("Enter ... | true |
fc8e802b9f6a17e1ab0d7b60063e5088c80f7e6e | eduardmak/learnp | /lesson2/homework/lines.py | 775 | 4.4375 | 4 | # Написать функцию, которая принимает на вход две строки.
# Если строки одинаковые, возвращает 1.
# Если строки разные и первая длиннее, возвращает 2.
# Если строки разные и вторая строка 'learn', возвращает 3.
def function(stroka1, stroka2):
if stroka1 == stroka2:
return 1
elif stroka2 == "learn":
... | false |
53584396541214a896e050f167ba024c47cbf905 | AngryCouchPotato/AlgoExpert | /arrays/LongestPeak.py | 1,405 | 4.40625 | 4 | # Longest Peak
#
# Write a function that takes in an array of integers and returns
# the length of the longest peak in the array.
#
# A peak is defined as adjacent integers in the array that are strictly
# increasing until they reach a tip ( the highest value in the peak),
# at which point they become strictly decreasi... | true |
f88a0df1e2462fa7f8914f4dd2477603f9acc51b | JpryHyrd/python_2.0 | /Lesson_2/7.py | 474 | 4.34375 | 4 | """
7. Напишите программу, доказывающую или проверяющую, что для множества
натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2,
где n - любое натуральное число.
"""
def mn():
a = 1 + 2 + 3 + 4 + 5
n = 5
if a == n * (n + 1) / 2:
print("Формула верна!")
else:
print("Что-то не ... | false |
ef9b1893fc0559fed7835ae8f434577db66302cc | nchullip/Group-Project-I-Data-Analysis | /GetCountryList.py | 863 | 4.34375 | 4 | # Importing Dependencies
import pandas as pd
import numpy as np
def get_country_list(data_file, num):
################################################
# This function takes the Data file as input and returns
# a list of countries with the most population.
#
# Argument: data_file - CSV file
# num - In... | true |
50799ccd441cbb2651a1e265d81def7c9b083d4d | guhaneswaran/Django-try | /scratch_7.py | 782 | 4.125 | 4 | # Instance variables - changes depends on the object. Defined inside __init__
# Class Variables - is fixed. Defined outside __init__ inside the class
# Namespace- the space where we create and store object/variable
# Class namespace - to store all the class variable
# Instance namespace - to store all the ... | true |
4eafb7b0b9bd65b3f7cb8184dd33250f056cf10f | guhaneswaran/Django-try | /scratch_8.py | 1,387 | 4.15625 | 4 | # Methods:
# Instance method , class method , static method
# Instance method - two types Accessor method and Mutator method
# Accessor method - Just fetch the value of instance variable
# Mutator method - Change the value of the instance variable
class Student:
school = 'Telusko' # Class variable
... | true |
e36fe2b79f4190942303519cef67a3ddc26a7982 | VendrickNZ/GuessTheNumber | /GuessTheNumber.py | 1,677 | 4.3125 | 4 | import random
"""The computer generates a random number and the user tries to guess it."""
def random_number():
"""picks a random number from a range function and
returns the range bounds and chosen number"""
range = number_range()
low = range[0]
high = range[1]
return (random.randrange(low, ... | true |
973095bd95e959ab76aaa94a2cc19ced49761efd | marshalloffutt/lists | /places.py | 650 | 4.5625 | 5 | places = ["Mars", "Egypt", "Venice", "Tokyo", "Vancouver"]
# Print places
print(places)
# Print sorted places in alphabetical order
print(sorted(places))
# Print original places
print(places)
# Print sorted places in reverse alphabetical order
print(sorted(places, reverse=True))
# Show that original list is unchan... | true |
1504c91c99c544ff2fd4baa478f7ac6a048d7132 | pallavim98/ProxyCloud | /Threading/threading_example.py | 1,789 | 4.78125 | 5 | # Python program to illustrate the concept
# of threading
# importing the threading module
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
... | true |
eae3a2e937b369a24d403bc317d22b985e72fc02 | fadedphoenix7/ProgramacionEstructurada | /Unidad 2-Estructuras de Control/Ejercicio4.py | 1,047 | 4.21875 | 4 |
#Autor:Jorge Chí 03/Febrero/19
#Entradas: numero (a redondear).
#Salidas: numero (redondeado).
#Procedimiento general: Se ingresa un numero. Si es negativo se pide de nuevo.
#Se redondea el numero a la centena más cercana
#se inicia la variable que guarda el número
numero = int( 0 )
while 1 :
print( ... | false |
18fcd3a4caf16cd7d9283d4f7f8db8fab953b052 | adityatanwar800/FSDP2019 | /Day03/intersection.py | 257 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 18:16:29 2019
@author: Aditya Tanwar
"""
lst1=input("enter the value").split()
set1=set(lst1)
lst2=input("enter the value for set 2").split()
set2=set(lst2)
set3=set1.intersection(set2)
lst=list(set3)
print(lst) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.