blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0423a1f2927e6d4ea4a16578801e4f237d0cda6d | 20040116/Learning-experience-of-python | /Day02(2021.07.07)_Class.py | 2,588 | 4.40625 | 4 | ###类的基础学习
###书上的例子
###属性:类中的形参和实参 方法:类中的具体函数
###将一个类作为另一个类的属性
class Wheel():
def __init__(self, maker, size):
self.maker = maker
self.size = size
def wheel_description(self):
print("This wheel is " + str(self.size) + " maked by " + self.maker)
class Car():
'''模拟汽车的... | false |
f0fb1d24bbeffbc40fbfed97db945a69ffd9a6a1 | AlexSR2590/curso-python | /07-ejercicios/ejercicio1.py | 433 | 4.3125 | 4 | """
Ejercicio 1
-Crear dos variables "pais" y "continente"
-Mostrar el valor por pantalla (imprimir)
-imprimir el tipo de dato de las dos variables
"""
pais = input("Introduce un país: ")
continente = input("Introduce un continente: ")
print("Pais: ", pais)
print("Tipo de dato de la variable pais: ")
print(type(pa... | false |
1a9900260ede8d1f9fa50622b31f2244ff70d858 | AlexSR2590/curso-python | /11-ejercicios/ejercicio1.py | 1,774 | 4.28125 | 4 | """
Hcaer un programa que tenga una lista de 8 numeros enteros
y hacer lo siguiente:
- Recorrer la lista y mostrarla
- Ordenar la lista y mostrarla
- Mostrar su longitud
- Bucar algun elemento que el usuario pida por teclado
"""
numeros = [1, 9, 4, 2, 30, 7, 28, 18]
#Recorrer la lista y mostrarla (función)
print("Rec... | false |
08af65139899c28b6e118af7f9c15ecfda947611 | AlexSR2590/curso-python | /03-operadores/aritmeticos.py | 446 | 4.125 | 4 | #Operadores aritmeticos
numero1 =77
numero2 = 44 #Operador asignación =
resta = numero1 - numero2
multiplicacion = numero1 * numero2
division = numero1 / numero2
resto = numero1 % numero2
print("***********Calculadora*************")
print(f"La resta es: {resta}" )
print(f"La suma es: {numero1 + numero2} ")
print("La... | false |
01f42ded2480038227e1d492193c9a1dbb3395bf | Chih-YunW/Leap-Year | /leapYear_y.py | 410 | 4.1875 | 4 | while True:
try:
year = int(input("Enter a year: "))
except ValueError:
print("Input is invalid. Please enter an integer input(year)")
continue
break
if (year%4) != 0:
print(str(year) + " is not a leap year.")
else:
if(year%100) != 0:
print(str(year) + " is a leap year.")
else:
if(year%400) == 0:
pr... | true |
999579d8777c53f7ab91ebdcc13b5c76689f7411 | ayushmohanty24/python | /asign7.2.py | 682 | 4.1875 | 4 | """
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
"""
fname = input("Enter file name: ")
... | true |
adfa2df9495c4631f0d660714a2d130bfedd9072 | jni/interactive-prog-python | /guess-the-number.py | 2,010 | 4.15625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
def initialize_game():
global secret_number, rangemax, guesses_remaining, guesses_label
rangemax = 100
guesses_remaining =... | true |
5fd5b964582057ac930249378e9b944ac1b31bc0 | raghav1674/graph-Algos-In-Python | /Recursion/05/StairCaseTraversal.py | 393 | 4.15625 | 4 |
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1):
if staircase_height == 0 or current_step == 0:
return 1
elif staircase_height >= current_step:
return max_ways_to_reach_staircase_end(
staircase_height-current_step, max_step, current_step-1) + stairc... | true |
a4a7c7db2d8fbfb5649f831e832190e719c499c6 | phos-tou-kosmou/python_portfolio | /euler_project/multiples_of_three_and_five.py | 1,459 | 4.34375 | 4 | def what_are_n():
storage = []
container = 0
while container != -1:
container = int(input("Enter a number in which you would like to find multiples of: "))
if container == -1: break
if type(container) is int and container not in storage:
storage.append(container)
... | true |
eec09d1b8c6506de84400410771fcdeb6fe73f73 | StephenTanksley/hackerrank-grind-list | /problem-solving/extra_long_factorials.py | 950 | 4.5625 | 5 | """
The factorial of the integer n, written n!, is defined as:
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
Calculate and print the factorial of a given integer.
Complete the extraLongFactorials function in the editor below. It should print the result and return.
extraLongFactorials has ... | true |
706fe7a6d67d4df85a66c25d952ef7cc2d6ba6d3 | jamiepg1/GameDevelopment | /examples/python/basics/fibonacci.py | 277 | 4.1875 | 4 | def fibonacci (n):
""" Returns the Fibonacci number for given integer n """
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-2) + fibonacci(n-1)
n = 25
for i in range(n):
result = fibonacci(i)
print "The fibonacci number for ", i, " is ", result
| false |
34c6867e4dc393cdcf455a09701e906b48cf5f5e | solitary-s/python-learn | /list/tuple.py | 329 | 4.15625 | 4 |
# 元组 不可以修改 类似字符串
tuple1 = tuple(range(1, 10))
print(tuple1)
# ,逗号才是元组的标识
temp1 = (1)
print(type(temp1)) # <class 'int'>
temp2 = (1,)
print(type(temp2)) # <class 'tuple'>
# 元组的更新和删除,通过切片拼接
temp = (1, 2, 4)
temp = temp[:2] + (3,) + temp[2:]
print(temp)
| false |
cf8e0b2ce24068f60f4c4cb056e2baa57cae3f8f | solitary-s/python-learn | /dict/dict.py | 479 | 4.125 | 4 | # 字典
dict1 = {'1': 'a', '2': 'b', '3': 'c'}
print(dict1)
print(dict1['2'])
# 空字典
empty = {}
print(type(empty))
# 创建
dict((('F', 70), ('i', 105)))
dict(one=1, two=2, three=3)
# 内置方法
# 用来创建并返回一个新的字典
dict2 = {}
dict2 = dict2.fromkeys((1, 2, 3), ('one', 'two', 'three'))
print(dict2)
# keys(), values() 和 items()
dict3 =... | false |
cfa8ff6a920cfbf24b950c8f47e8e109b52d2fde | Arpita-Mahapatra/Python_class | /List_task.py | 1,074 | 4.15625 | 4 | '''a=[2,5,4,8,9,3] #reversing list
a.reverse()
print(a)''' #[3, 9, 8, 4, 5, 2]
'''a=[1,3,5,7,9] #deleting element from list
del a[1]
print(a)''' #[1, 5, 7, 9]
'''a=[6,0,4,1] #clearing all elements from list
a.clear()
print(a)''' #o/p : []
'''n = [1, 2, 3, 4, 5] #mean
l = len(n)
nsum = sum(n)
mean = ... | false |
aad85067c090c60b6095d335c6b9a0863dd76311 | dpolevodin/Euler-s-project | /task#4.py | 820 | 4.15625 | 4 | #A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
num_list = []
result = []
# Create a list with elements multiplied by each other
for i in range(100,1000... | true |
41b6ee22ddfb9f6ad0d6dc18d0ec4e5bf1e0bb43 | anagharumade/Back-to-Basics | /BinarySearch.py | 827 | 4.125 | 4 | def BinarySearch(arr, search):
high = len(arr)
low = 0
index = ((high - low)//2)
for i in range(len(arr)):
if search > arr[index]:
low = index
index = index + ((high - low)//2)
if i == (len(arr)-1):
print("Number is not present in the input arr... | true |
3967fad907d30a59282306b168bfd3fa032bfaa9 | mootfowl/dp_pdxcodeguild | /python assignments/lab10_unit_converter_v3.py | 1,466 | 4.34375 | 4 | '''
v3 Allow the user to also enter the units.
Then depending on the units, convert the distance into meters.
The units we'll allow are inches, feet, yards, miles, meters, and kilometers.
'''
def number_crunch():
selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. ... | true |
d900cef1d0915808b0b213a6339636bf2dd3dcd2 | mootfowl/dp_pdxcodeguild | /python assignments/lab15_ROT_cipher_v1.py | 971 | 4.15625 | 4 | '''
LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a',
and displays it to the user in the terminal.
'''
# DP note to self: if a = 1, ROT13 a = n (ie, 13 letters after a)
# First, let's create a function that encrypts a word with ROT13...
alphabet = 'abcdefghijklmnop... | true |
858422c01e9d9390216773f08065f38a124cb579 | monicaneill/PythonNumberGuessingGame | /guessinggame.py | 1,724 | 4.46875 | 4 | #Greetings
print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!")
print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!")
#Computer Function
def computerGuess(lowval, highval, randnum, count=0):
if highval >= lowval:
... | true |
0a517656681efc1b179ca047ed54e2e210567824 | tnaswin/PythonPractice | /Aug18/recursive.py | 406 | 4.21875 | 4 | def factorial(n):
if n <= 1:
return 1
else:
return n * (factorial(n - 1))
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n - 1) + (fibonacci(n - 2)))
n = int(raw_input("Enter a number: "))
if n <= 0:
print("Plese enter a positive integer")
else:
print "Factorial: ", fact... | false |
0e5c69430dcddf93721e19e55a54d131394ca452 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/classes/class_02/cat.py | 2,211 | 4.125 | 4 | # import sys library
import sys
# this is a foor loop
#stdin refers to the lines that are input to the program
#typical python styling is indenting with four spaces
for line in sys.stdin:
#strip() removes whitespace at the end of the line
#strip() is a method of a line object
line = line.strip()
if "yo... | true |
47c9f72baa7577f726046a80f338e40fd199bb61 | montoyamoraga/nyu-itp | /reading-and-writing-electronic-text/assignments/assignment_04/this.py | 2,031 | 4.1875 | 4 | #assignment 04
#for class reading and writing electronic text
#at nyu itp taught by allison parrish
#by aaron montoya-moraga
#february 2017
#the digital cut-up, part 2. write a program that reads in and creatively re-arranges the content of several source texts. what is the unit of your cut-up technique? (the word, th... | true |
e7f50e19dbf531b0af4ae651759d714278aac06b | ribeiroale/rita | /rita/example.py | 498 | 4.21875 | 4 | def add(x: float, y: float) -> float:
"""Returns the sum of two numbers."""
return x + y
def subtract(x: float, y: float) -> float:
"""Returns the subtraction of two numbers."""
return x - y
def multiply(x: float, y: float) -> float:
"""Returns the multiplication of two numbers."""
return x ... | true |
299cc5fc729fef69fea8e96cd5e72344a1aa3e12 | voyeg3r/dotfaster | /algorithm/python/getage.py | 1,075 | 4.375 | 4 | #!/usr/bin/env python3
# # -*- coding: UTF-8 -*-"
# ------------------------------------------------
# Creation Date: 01-03-2017
# Last Change: 2018 jun 01 20:00
# this script aim: Programming in Python pg 37
# author: sergio luiz araujo silva
# site: http://vivaotux.blogspot.com
# ... | true |
d9eddfd175dd379bd8453f908a0d8c5abeef7a29 | bbullek/ProgrammingPractice | /bfs.py | 1,536 | 4.1875 | 4 | ''' Breadth first traversal for binary tree '''
# First, create a Queue class which will hold nodes to be visited
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def isEmpty(self):
return len(self.queue) == 0
... | true |
17f30d9b41e3bac84534424877c3fc81791ef755 | jibachhydv/bloomED | /level1.py | 498 | 4.15625 | 4 | # Get the Number whose index is to be returned
while True:
try:
num = int(input("Get Integer: "))
break
except ValueError:
print("Your Input is not integer")
# List of Number
numbers = [3,6,5,8]
# Function that return index of input number
def returnIndex(listNum, num):
for i in ... | true |
e4a48078d125102f2a154d5c7cf387b0f087b7a8 | ScroogeZhang/Python | /day03字符串/04-字符串相关方法.py | 1,185 | 4.21875 | 4 | # 字符串相关方法的通用格式:字符串.函数()
# 1.capitalize:将字符串的首字母转换成大写字母,并且创建一个新的字符返回
str1 = 'abc'
new_str = str1.capitalize()
print(new_str)
# 2.center(width,fillerchar):将原字符串变成指定长度并且内容居中,剩下的部分使用指定的(字符:长度为1的字符串)填充
new_str = str1.center(7,'!')
print(str1,new_str)
# 3.rjust(width,fillerchar)
new_str = str1.rjust(7,'*')
print(new_str)... | false |
61cc074563240c4e6f6835b1bf6be450b76956a9 | ScroogeZhang/Python | /day04 循环和分支/04-while循环.py | 951 | 4.1875 | 4 | # while循环
'''
while 条件语句:
循环体
其他语句
while:关键字
条件语句: 结果是True,或者False
循环体:重复执行的代码段
执行过程:判断条件语句是否为True,如果为True就执行循环体。
执行完循环体,再判断条件语句是否为True,如果为True就在执行循环体....
直到条件语句的值为False,循环结束,直接执行while循环后面的语句
注意:如果条件语句一直都是True,就会造成死循环。所以在循环体要有让循环可以结束的操作
python 中没有do-while 循环
'''
# 死循环
# while True:
# print('aaa')
flag = ... | false |
79c4584eb2cae10c882162f315f213dcaa734949 | ScroogeZhang/Python | /day03字符串/05-if语句.py | 1,131 | 4.5 | 4 | # if语句
# 结构:
# 1.
# if 条件语句:
# 条件语句为True执行的代码块
#
# 执行过程:先判断条件语句是否为True,
# 如果为True就执行if语句后:后面对应的一个缩进的所有代码块
# 如果为False,就不执行冒号后面的一个缩进中的代码块,直接执行后续的其他语句
#
# 条件语句:可以使任何有值的表达式,但是一般是布尔值
#
#
# if : 关键字
if True:
print('代码1')
print('代码2')
print('代码3')
print('代码4')
# 练习:用一个变量保存时间(50米短跑),如果时间小于8秒,打印及格
time = 7
if time <... | false |
fca406d84960938a40a1d2216983f2c07efa374e | Suraj-S-Patil/Python_Programs | /Simple_Intrst.py | 246 | 4.125 | 4 | #Program to calculate Simple Interest
print("Enter the principal amount, rate and time period: ")
princ=int(input())
rate=float(input())
time=float(input())
si=(princ*rate*time)/100
print(f"The simple interest for given data is: {si}.")
| true |
d552de01cad51b019587300e6cf5b7cbc5d3122f | Cherol08/finance-calculator | /finance_calculators.py | 2,713 | 4.40625 | 4 | import math
#program will ask user if they want to calculate total investment or loan amount
option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n
Investment - to calculate the amount of interest you'll earn on interest
Bond - to calculate the amount you'll have to pay on a home loan\n "... | true |
462321abc830736f71325221f81c4f5075dd46fb | amithjkamath/codesamples | /python/lpthw/ex21.py | 847 | 4.15625 | 4 | # This exercise introduces 'return' from functions, and hence daisy-chaining them.
# Amith, 01/11
def add(a, b):
print "Adding %d + %d" % (a,b)
return a + b
def subtract(a, b):
print "Subtracting %d - %d" % (a,b)
return a - b
def multiply(a,b):
print "Multiplying %d * %d" % (a,b)
return a*b
... | true |
923177e67d9afe32c3bcc738a8726234c5d08ad2 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex6.py | 758 | 4.5 | 4 | # Strings and Text
# This script demonstrates the function of %s, %r operators.
x = "There are %d types of people." % 10
binary = "binary" # saves the string as a variable
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables ()
# here's where we print out our variables ^... | true |
568c69be02b59df5d2c531bb707be680fc5efa77 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex29.py | 1,080 | 4.65625 | 5 | # What If
# The if statements, used in conjunction with the > , < operators will print
# the following text if True.
# In other words, ( if x is True: print "a short story" )
# Indentation is needed for syntax purpouses. if you do not indent you will get
# "IndentationError: expected an indented block".
# If you do no... | true |
46554c75d2000a673d11d628b5921831bec87b74 | CTRL-pour-over/Learn-Python-The-Hard-Way | /ex15.py | 944 | 4.25 | 4 | # Reading Files
# this file is designed to open and read a given file as plain text
# provide ex15.py with an argument (file) and it will read it to you
# then it will as for the filename again, you can also give it a different file.
from sys import argv
# here is how we can give an additional argument when trying to ... | true |
2ca7c4e31ad857f80567942a0934d9399a6da033 | zoeyangyy/algo | /exponent.py | 600 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Time : 2018/8/16 下午10:27
# @Author : Zoe
# @File : exponent.py
# @Description :
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
result = base
if exponent == 0:
return ... | true |
36d281d594ec06a38a84980ca15a5087ccb2436a | connor-giles/Blackjack | /hand.py | 847 | 4.125 | 4 | """This script holds the definition of the Hand class"""
import deck
class Hand:
def __init__(self):
self.cards = [] # A list of the current cards in the user's hand
self.hand_value = 0 # The actual value of the user's hand
self.num_aces = 0 # Keeps track of the number of aces that the ... | true |
6b16f67a76c4951b641d252d40a1931552381975 | by46/geek | /codewars/4kyu/52e864d1ffb6ac25db00017f.py | 2,083 | 4.1875 | 4 | """Infix to Postfix Converter
https://www.codewars.com/kata/infix-to-postfix-converter/train/python
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
Construct a function that, when given a string containing an expression in infix notation,
will return an identical expression in postfix notation.
The op... | true |
81cfaff6e7ed2ac0be013d2439592c4fb8868e63 | apugithub/Python_Self | /negetive_num_check.py | 355 | 4.15625 | 4 |
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0... | true |
8f27badfdef2487c0eb87e659fac64210faa1646 | gaylonalfano/Python-3-Bootcamp | /card.py | 767 | 4.125 | 4 | # Card class from deck of cards exercise. Using for unit testing section
# Tests: __init__ and __repr__ functions
from random import shuffle
class Card:
available_suits = ("Hearts", "Diamonds", "Clubs", "Spades")
available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
def _... | true |
6bcb51fae80c295f98d6004344c5ffec1028f602 | gaylonalfano/Python-3-Bootcamp | /infinite_generators_get_multiples.py | 649 | 4.21875 | 4 | # def get_multiples(number=1, count=10):
# for i in range(1, count+1):
# yield number*i
#
# evens = get_multiples(2, 3)
# print(next(evens))
# print(next(evens))
# print(next(evens))
# print(next(evens))
# GET_UNLIMITED_MULTIPLES EXERCISE:
def get_unlimited_multiples(number=1):
next_num = number
... | true |
c68446d2fa042a3c279654f3937c16d632bf2420 | gaylonalfano/Python-3-Bootcamp | /decorators_logging_wraps_metadata.py | 2,667 | 4.40625 | 4 | """
Typical syntax:
def my_decorator(fn):
def wrapper(*args, **kwargs):
# do stuff with fn(*args, **kwargs)
pass
return wrapper
Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ
from functools import wraps
import logging
logging.basicConfig(filename='example.log', level=lo... | true |
0fa247aef355f85a8a00d44357933f418038c91d | gaylonalfano/Python-3-Bootcamp | /debugging_pdb.py | 1,790 | 4.1875 | 4 | '''
Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line:
def function(params):
import pdb; pdb.set_trace() - Usually added/imported like this inside a function
*Rest of code*
Usually placed right before something starts breaking. Allows you to see a preview of what h... | true |
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316 | gaylonalfano/Python-3-Bootcamp | /sorted.py | 1,583 | 4.5625 | 5 | '''
sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.)
You can also pass it a reverse=True argument.
Key difference between sorted and .sort() is that .sort() is a list-only method and returns the
sorted list in-place. sorted() accepts any type of iterable. Good for sorted on ... | true |
f6c7ea3bf3080757bd268ee0b701e6c29c0d584f | gaylonalfano/Python-3-Bootcamp | /interleaving_strings_zip_join.py | 686 | 4.3125 | 4 | '''
Write a function interleave() that accepts two strings. It should return a new string containing
the two strings interwoven or zipped together. For example:
interleave('hi', 'ha') # 'hhia'
interleave('aaa', 'zzz') # 'azazaz'
interleave('lzr', 'iad') # 'lizard'
'''
def interleave(str1, str2):
return ''.jo... | false |
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3 | gaylonalfano/Python-3-Bootcamp | /polymorphism_OOP.py | 1,806 | 4.3125 | 4 | '''
POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take
on many (poly) forms (morph). Here are two important practical applications:
1. Polymorphism & Inheritance - The same class method works in a similar way for different classes
Cat.speak() # meow
Dog.speak() # woof
Human.speak(... | true |
79c42425fad9a2049934a8208d0b8cf9ca9b0a08 | gaylonalfano/Python-3-Bootcamp | /custom_for_loop_iterator_iterable.py | 1,648 | 4.4375 | 4 | # Custom For Loop
'''
ITERATOR - An object that can be iterated upon. An object which returns data,
ONE element at a time when next() is called on it. Think of it as anything we can
run a for loop on, but behind the scenes there's a method called next() working.
ITERABLE - An object which will return an ITERATOR when... | true |
2e9cde6ddaf45706eb646ec7404d22a851430e3f | gaylonalfano/Python-3-Bootcamp | /dundermethods_namemangling.py | 1,096 | 4.5 | 4 | # _name - Simply a convention. Supposed to be "private" and not used outside of the class
# __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it
# Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes.
# Think of hi... | true |
15dbca45f3fbb904d3f747d4f165e7dbca46c684 | XavierKoen/cp1404_practicals | /prac_01/loops.py | 924 | 4.5 | 4 | """
Programs to display different kinds of lists (numerical and other).
"""
#Basic list of odd numbers between 1 and 20 (inclusive).
for i in range(1, 21, 2):
print(i, end=' ')
print()
#Section a: List counting in 10s from 0 to 100.
for i in range(0, 101, 10):
print(i, end=' ')
print()
#Section b: List count... | true |
e1e5bdeab07475e95a766701d6feb6e14fe83494 | XavierKoen/cp1404_practicals | /prac_02/password_checker.py | 2,067 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be betw... | true |
72a5f79be816896fcdfbab8dd0a54f1588d25551 | jeremyyew/tech-prep-jeremy.io | /code/topics/1-searching-and-sorting/M148-sorted-list.py | 1,589 | 4.125 | 4 | Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
pass
# Iterative mergesort function to
# sort arr[0...n-1]
def mergeSort(self, head):
current_size = 1
left = he... | true |
5ccb88df6a21f7a105c7c08d2551412c4cc307bb | sachin1005singh/complete-python | /python_program/findvowel.py | 218 | 4.28125 | 4 | #vowels program use of for loop
vowel = "aeiouAEIOU"
while True:
v = input("enter a vowel :")
if v in vowel:
break
print("this in not a vowel ! try again !!")
print("thank you")
| true |
74a079f8a0c40df56f5412dd4723cb2368b3759a | kartsridhar/Problem-Solving | /halindrome.py | 1,382 | 4.25 | 4 | """
Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if
AT LEAST one of the following conditions satisfy:
1. S is a palindrome and of length S >= 2
2. S1 is a halindrome
3. S2 is a halindrome
In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1]
Example 1:
input: harshk
ou... | true |
408d751896467c077d7dbc1ac9ffe6239fed474d | kartsridhar/Problem-Solving | /HackerRank/Problem-Solving/Basic-Certification/unexpectedDemand.py | 1,630 | 4.40625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'filledOrders' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY order
# 2. INTEGER k
#
"""
A widget manufacturer is facing unexpectedly high d... | true |
914c7c8db0d3d316d22d899ba6756368ae4eb392 | pythonmite/Daily-Coding-Problem | /problem_6_medium.py | 514 | 4.1875 | 4 | """
Company Name : DropBox
Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6]
secondlargestelement >>> [5]
"""
def findSecondLargestNum(arr:list):
max = arr[0]
for num in arr:
if num > max:
max = num
secondlargest = 0
f... | true |
de1515c2150e80505cca6fbec738b38bc896487f | KarenRdzHdz/Juego-Parabolico | /parabolico.py | 2,756 | 4.34375 | 4 | """Cannon, hitting targets with projectiles.
Exercises
1. Keep score by counting target hits.
2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.
Integrantes:
Karen Lizette Rodríguez Hernández - A01197734
Jorge Eduardo Arias Arias - A01570549
Hernán Salinas Ibarra - A0157... | true |
02a01f7bc44fcdb31cef4c4ae58ea0b1ea573326 | imruljubair/imruljubair.github.io | /_site/teaching/material/Functions_getting_started/16.py | 235 | 4.15625 | 4 | def main():
first_name = input('Enter First Name: ')
last_name = input('Enter Last Name: ')
print('Reverse: ')
reverse_name(first_name, last_name)
def reverse_name(first, last):
print(last, first)
main()
| false |
627a95962abed7b46f673bf813375562b3fa1cd2 | imruljubair/imruljubair.github.io | /teaching/material/List/7.py | 413 | 4.375 | 4 | # append()
# Example 7.1
def main():
name_list = []
again = 'y'
while again == 'y':
name = input("Enter a name : ")
name_list.append(name)
print('Do you want to add another name ?')
again = input('y = yes, anything else = no: ')
print()
print(... | true |
0c110fece3e121665c41b7f1c039c190ed1b7866 | imruljubair/imruljubair.github.io | /teaching/material/List/5.py | 268 | 4.28125 | 4 | # Concating and slicing list
# Example 5.1
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
print(list3)
# Example 5.2
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday']
mid_days = days[2:5]
print(mid_days)
| true |
6399bf8b03d1f6ef5a68bec3b6cc8baa26000edc | imruljubair/imruljubair.github.io | /_site/teaching/material/Functions_getting_started/17.py | 266 | 4.4375 | 4 | def main():
first_name = input('Enter First Name: ')
last_name = input('Enter Last Name: ')
N = reverse_name(first_name, last_name)
print('Reverse: '+str(N))
def reverse_name(first, last):
name = last+' '+ first
return name
main()
| false |
aea3ddf894c253cfe9bcdae7a3878f67bf76a5b7 | softwaresaved/docandcover | /fileListGetter.py | 1,118 | 4.375 | 4 | import os
def fileListGetter(directory):
"""
Function to get list of files and language types
Inputs: directory: Stirng containing path to search for files in.
Outputs: List of Lists. Lists are of format, [filename, language type]
"""
fileLists = []
for root, dirs, files in os.walk(dire... | true |
06371106cc981aac3260a681d2868a4ccf24f5bf | Sergey-Laznenko/Coursera | /Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/2.py | 782 | 4.28125 | 4 | """
Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс.
Если она встречается два и более раз, выведите индекс её первого и последнего появления.
Если буква f в данной строке не встречается, ничего не выводите.
При решении этой задачи нельзя использовать метод count и циклы.
"""
str... | false |
384785ebd3f0e57cc68ac0cd00389f4bcfd8b245 | AffanIndo/python-script | /caesar.py | 702 | 4.21875 | 4 | #!usr/bin/env python
"""
caesar.py
Encrypt or decrypt text based from caesar cipher
Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python
"""
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
... | true |
20ffbd80d572fd4b75db8860c04c034cb6d87ab0 | midephysco/midepython | /exercises2.py | 250 | 4.125 | 4 | #this is a program to enter 2 numbers and output the remainder
n0 = input("enter a number ")
n1 = input("enter another number")
div = int(n0) / int(n1)
remainder = int(n0) % int(n1)
print("the answer is {0} remainder {1}".format(div, remainder)) | true |
19665f62b7fa38f9cbc82e17e02dacd6de092714 | midephysco/midepython | /whileloop2.py | 452 | 4.21875 | 4 | #continous loop
print("Adding until rogue value")
print()
print("This program adds up values until a rogue values is entered ")
print()
print("it then displays the sum of the values entered ")
print()
Value = None
Total = 0
while Value != 0:
print("The total is: {0}.".format(Total))
print()
Value = int(i... | true |
cdfad3f2a3b8d22c82c203195a5c03ec456111e6 | VineethChandha/Cylinder | /loops.py | 987 | 4.125 | 4 | # PY.01.10 introduction to the loops
for a in range(1,11): # a will be valuated from 1 to 10
print("Hi")
print(a)
even_numbers = [x for x in range(1,100) if x%2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1,100) if x%2 != 0]
print(odd_numbers)
words = ["ram","krishna","sai"]
answ... | true |
daf4203e12c8e480fe1b6b0b9f1f3e63b2f292fa | awanisazizan/awanis-kl-oct18 | /birthday.py | 439 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 10:41:07 2018
@author: awanis.azizan
"""
import datetime
#birthday = input("What is your birthday? (dd/mm/yyyy)" )
#birthdate = datetime.datetime.strptime(birthday,"%d/%m/%Y").date()
#print("Your birth month is " +birthdate.strftime('%B'))
nextBirthday = datetime.d... | false |
aaf7a5a0a5195ff1376ef2f0d6e6f84ffc273341 | XxdpavelxX/Python3 | /L3 Iteration in Python/decoder.py | 1,682 | 4.625 | 5 | """Create a Python3_Homework03 project and assign it to your Python3_Homework working set. In the
Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator.
When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it
sho... | true |
0a78c83f9ef57d9b72a23fe657ed93c9761f3e3e | XxdpavelxX/Python3 | /L4 Basic Regular Expressions/find_regex.py | 1,719 | 4.3125 | 4 | """Here are your instructions:
Create a Python3_Homework04 project and assign it to your Python3_Homework working set. In the Python3_Homework04/src
folder, create a program named find_regex.py that takes the following text and finds the start and end positions of the
phrase, "Regular Expressions".
Text to use in ... | true |
ccc8620d0ec8f4dd1fdf13800ce16db8efa218ff | BiancaHofman/python_practice | /ex37_return_and_lambda.py | 744 | 4.3125 | 4 | #1. Normal function that returns the result 36
#And this result is printed
def name():
a = 6
return a * 6
print(name())
#2. Normal function that only prints the result 36
def name():
a = 6
print(a * 6)
name()
#3. Anonymous function that returns the result 36
#And this result is printed
x =... | true |
2cf1813ba0c933c00afef4c26bec91ec7b1494ff | johnsbuck/MapGeneration | /Utilities/norm.py | 1,596 | 4.34375 | 4 | """N-Dimensional Norm
Defines the norm of 2 points in N dimensional space with different norms.
"""
import numpy as np
def norm(a, pow=2):
""" Lp Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,). Defines a point in 2-D space.
pow (float): The norm used for distance (Default: 2... | true |
1040a092ef92aa80822e0cada2d5df026a95b1e2 | snahor/chicharron | /cracking-the-code-interview/02.06.py | 860 | 4.15625 | 4 | from linked_list import Node
def reverse(head):
'''
>>> head = Node(1)
>>> reverse(head)
1
>>> head = Node(1, Node(2, Node(3)))
>>> reverse(head)
3 -> 2 -> 1
>>> reverse(reverse(head))
1 -> 2 -> 3
'''
new_head = None
curr = head
while curr:
new_head = Node(c... | false |
81a1ab2f702bd56d5379540bee0e14044661a958 | Manmohit10/data-analysis-with-python-summer-2021 | /part01-e07_areas_of_shapes/src/areas_of_shapes.py | 864 | 4.21875 | 4 | #!/usr/bin/env python3
import math
def main():
while True:
shape=input("Choose a shape (triangle, rectangle, circle):")
shape=str(shape)
if shape=="":
break
elif shape=='triangle':
base=float(input('Give base of the triangle:'))
height=float(inp... | true |
87b47edb3ac4c944e7498021311d29a683de4873 | mashanivas/python | /scripts/fl.py | 208 | 4.28125 | 4 | #!/usr/bin/python
#Function for powering
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3))
| true |
cc6c58e549f132112a68038f4d71c8c582e63552 | moon-light-night/learn_python | /project.py | 577 | 4.3125 | 4 | #Дэбильный калькулятор
what = input ('Что делаем? (+, -, *, /)')
a = float(input ('Введи первое число: '))
b = float(input ('Введи второе число: '))
if what == '+':
c = a + b
print('Результат:' + str(c))
elif what == '-':
c = a - b
print('Результат:' + str(c))
elif what == '*':
c = a * b
print('... | false |
8570e157445bcbb0d2ff72b5d3c62921d5e084fd | prahaladbelavadi/codecademy | /python/5.making-a-request.py | 1,129 | 4.40625 | 4 | # Making a Request
# You saw a request in the first exercise. Now it's time for you to make your own! (Don't worry, we'll help.)
#
# On line 1, we've imported urlopen from the urllib2 module, which is the Python way of bringing in additional functionality we'll need to make our HTTP request. A module is just a collecti... | true |
ac3a6fcb8237f80f54bd88856cc669d578ea08b5 | kieranmcgregor/Python | /PythonForEverybody/Ch2/Ex2_prime_calc.py | 2,439 | 4.125 | 4 | import sys
def prime_point_calc(numerator, denominator):
# Returns a number if it is a prime number
prime = True
while denominator < numerator:
if (numerator % denominator) == 0:
prime = False
break
else:
denominator += 1
if prime:
return num... | true |
58bfbf28aa758d222f0375e61b4ed2dc95c2c8da | kieranmcgregor/Python | /PythonForEverybody/Ch9/Ex2_Day_Sort.py | 1,767 | 4.15625 | 4 | def quit():
quit = ""
no_answer = True
while no_answer:
answer = input("Would you like to quit? (y/n) ")
try:
quit = answer[0].lower()
no_answer = False
except:
print ("Invalid entry please enter 'y' for yes and 'n' for no.")
continue... | true |
81567c5895ebec2009ffac7000a0dcb7db71387e | mrupesh/US-INR | /USD&INR.py | 523 | 4.3125 | 4 | print("Currency Converter(Only Dollars And Indian Rupees)")
while True:
currency = input("($)Dollars or (R)Rupees:")
if currency == "$":
amount = int(input('Enter the amount:'))
Rupees = amount * 76.50
print(f"${amount} is equal to: ₹{Rupees}")
elif currency.upper() == "R":
a... | false |
86f91d794953d183366e9290564313d1dcaa594e | gmanacce/STUDENT-REGISTERATION | /looping.py | 348 | 4.34375 | 4 | ###### 11 / 05 / 2019
###### Author Geofrey Manacce
###### LOOPING PROGRAM
####CREATE A LIST
months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december']
print(months)
#####using For loop
for month in months:
print(month.title() + "\n")
print("go for n... | true |
4407c72830681d2263c4882d39ab84070af61a77 | Compileworx/Python | /De Cipher Text.py | 348 | 4.34375 | 4 | code = input("Please enter the coded text")
distance = int(input("Please enter the distance value"))
plainText = ''
for ch in code:
ordValue = ord(ch)
cipherValue = ordValue - distance
if(cipherValue < ord('a')):
cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1))
plainText += chr(ci... | false |
d830adc3169ec263a5043079c99d8a8a65cda037 | orrettb/python_fundamental_course | /02_basic_datatypes/2_strings/02_11_slicing.py | 562 | 4.40625 | 4 | '''
Using string slicing, take in the user's name and print out their name translated to pig latin.
For the purpose of this program, we will say that any word or name can be
translated to pig latin by moving the first letter to the end, followed by "ay".
For example: ryan -> yanray, caden -> adencay
'''
#take the us... | true |
482a4ab3e78e3f5e755ea3ff9b66fc48d3e5860f | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /7.10 Problems/5.6-17.py | 367 | 4.1875 | 4 | # Use a for statement to print 10 random numbers.
# Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive.
import random
count = 1 # This keeps track of how many times the for-loop has looped
print("2")
for i in range(10):
number = random.randint(25,35)
print("Loop: ",c... | true |
63d9e51100db4792259157df2e315f920b23f46f | Shashanksingh17/python-functional-program | /LeapYear.py | 227 | 4.125 | 4 | year = int(input("Enter Year"))
if year < 1000 and year > 9999:
print("Wrong Year")
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a Leap Year")
| false |
b5c3a44e099edcc1974e5854b17e4b2475dc6a76 | Appu13/RandomCodes | /DivideandConquer.py | 678 | 4.1875 | 4 |
'''
Given a mixed array of number and string representations of integers,
add up the string integers and subtract this from the total of the non-string integers.
Return as a number.
'''
def div_con(x):
# Variable to hold the string total
strtot = 0
# Variable to hold the digit total
digitot = 0... | true |
7a049ad9b04e1243ad1f440447d89fe112979633 | Mvk122/misc | /CoinCounterInterviewQuestion.py | 948 | 4.15625 | 4 | """
Question: Find the amount of coins required to give the amount of cents given
The second function gets the types of coins whereas the first one only gives the total amount.
"""
def coin_number(cents):
coinlist = [25, 10, 5, 1]
coinlist.sort(reverse=True)
"""
list must be in descending order
... | true |
d25ac7c10ce42fed83f392ed9c5a02a3246eb146 | Svanfridurjulia/FORRITUN-SJS-HR | /Verkefni í tímum/assignment 3 while/assignment3.6.py | 222 | 4.125 | 4 | a0 = int(input("Input a positive int: ")) # Do not change this line
print(a0)
while a0 != 1:
if a0 % 2 == 0:
a0 = a0/2
print(int(a0))
elif a0 % 2 != 0:
a0 = 3*a0+1
print(int(a0))
| false |
8ce075118b7aca2dd2dc8f54eb59146e8c4edaf4 | Svanfridurjulia/FORRITUN-SJS-HR | /Hlutapróf 2/prófdæmi.py | 1,553 | 4.3125 | 4 | def sum_number(n):
'''A function which finds the sum of 1..n and returns it'''
sum_of_range = 0
for num in range (1,n+1):
sum_of_range += num
return sum_of_range
def product(n):
'''A function which finds the product of 1..n and returns it'''
multi = 1
for num in range(1,n+1):
... | true |
7c041a0333ad9a58383c495981485c535f6aa8bd | Svanfridurjulia/FORRITUN-SJS-HR | /æfingapróf/dæmi2.py | 878 | 4.21875 | 4 |
def open_file(filename):
opened_file = open(filename,"r")
return opened_file
def make_list(opened_file):
file_list = []
for lines in opened_file:
split_lines = lines.split()
file_list.append(split_lines)
return file_list
def count_words(file_list):
word_count = 0
punctua... | true |
9be417a8ba86044f1b8717d993f44660adfbf9cd | Svanfridurjulia/FORRITUN-SJS-HR | /æfing.py | 1,056 | 4.3125 | 4 |
def find_and_replace(string,find_string,replace_string):
if find_string in string:
final_string = string.replace(find_string,replace_string)
return final_string
else:
print("Invalid input!")
def remove(string,remove_string):
if remove_string in string:
final2_string = stri... | true |
f0d663cbc1f64b3d08e61927d47f451272dfd746 | Hiradoras/Python-Exercies | /30-May/Valid Parentheses.py | 1,180 | 4.375 | 4 | '''
Write a function that takes a string of parentheses, and determines
if the order of the parentheses is valid. The function should return
true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Con... | true |
cf9270abd93e8b59cdb717deeea731308bf5528d | Hiradoras/Python-Exercies | /29-May-2021/Reverse every other word in the string.py | 895 | 4.25 | 4 | '''
Reverse every other word in a given string, then return the string.
Throw away any leading or trailing whitespace, while ensuring there
is exactly one space between each word. Punctuation marks should be
treated as if they are a part of the word in this kata.
'''
def reverse_alternate(string):
words = string.s... | true |
224160811a676654cbfe88c9d0ba15d89620450f | zhangxinzhou/PythonLearn | /helloworld/chapter04/demo03.02.py | 235 | 4.1875 | 4 | coffeename = ('蓝山', '卡布奇诺', '慢的宁')
for name in coffeename:
print(name, end=" ")
print()
tuple1 = coffeename
print("原元组:", tuple1)
tuple1 = tuple1 + ("哥伦比亚", "麝香猫")
print("新元组:", tuple1)
| false |
dc4cfcc11c9b26f1e27874d1b9ac84291664b33c | susanbruce707/hexatrigesimal-to-decimal-calculator | /dec_to_base36_2.py | 696 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 23:38:34 2018
Decimal to hexatrigesimal calculator.
convert decimal number to base 36 encoding; use of letters with digits.
@author: susan
"""
def dec_to_base36(dec):
"""
converts decimal dec to base36 number.
returns
-------
sign+resu... | true |
58a9223e31c487b45859dd346238ee84bb2f61c8 | ao-kamal/100-days-of-code | /binarytodecimalconverter.py | 1,485 | 4.34375 | 4 | """Binary to Decimal and Back Converter - Develop a converter to convert a decimal number
to binary or a binary number to its decimal equivalent.
"""
import sys
print(
'This program converts a number from Binary to Decimal or from Decimal to Binary.')
def binary_to_decimal(n):
print(int(str(n), 2), '\n')
d... | true |
c296dab78893f00978039d1a8edee17c8d6d6b3d | lillyfae/cse210-tc05 | /puzzle.py | 1,812 | 4.125 | 4 | import random
class Puzzle:
'''The purpose of this class is to randomly select a word from the word list.
Sterotyope:
Game display
Attributes:
word_list (list): a list of words for the puzzle to choose from
chosen_word (string): a random word from the word list
create_... | true |
ca851a63737efa0dbef14a3d542e64797b808cce | prasertcbs/python_tutorial | /src/while_loop.py | 677 | 4.15625 | 4 | def demo1():
i = 1
while i <= 10:
print(i)
i += 1
print("bye")
def demo_for():
for i in range(1, 11):
print(i)
print("bye")
def sum_input():
n = int(input("enter number: "))
total = 0
while n != 0:
total += n
n = int(input("enter... | false |
e105386bcb9851004f3243f42f385ebc39bac8b7 | KAOSAIN-AKBAR/Python-Walkthrough | /casting_Python.py | 404 | 4.25 | 4 | x = 7
# print the value in float
print(float(x))
# print the value in string format
print(str(x))
# print the value in boolean format
print(bool(x)) # *** in BOOLEAN data type, anything apart from 0 is TRUE. Only 0 is considered as FALSE *** #
print(bool(-2))
print(bool(0))
# type casting string to integer
print(i... | true |
f64eb90364c4acd68aac163e8f76c04c86479393 | KAOSAIN-AKBAR/Python-Walkthrough | /calendar_Python.py | 831 | 4.40625 | 4 | import calendar
import time
# printing header of the week, starting from Monday
print(calendar.weekheader(9) + "\n")
# printing calendar for the a particular month of a year along with spacing between each day
print(calendar.month(2020, 4) + "\n")
# printing a particular month in 2-D array mode
print(calendar.monthc... | true |
5af9931029bef4345ffc1528219484cd363fbcfa | shade9795/Cursos | /python/problemas/Condiciones compuestas con operadores lógicos/problema5.py | 257 | 4.125 | 4 | x=int(input("Cordenada X: "))
y=int(input("Cordenada Y: "))
if x==0 or y==0:
print("Las coordenadas deben ser diferentes a 0")
else:
if x>0 and y>0:
print("1º Cuadrante")
else:
if x<0 and y>0:
print("2º Cuadrante") | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.