blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
630afbcab875ba20023877706a42d4e70fd09315 | nileshhadalgi016/python3 | /For loop in python.py | 834 | 4.25 | 4 | """
Python For Loops
- Techie Programmer
A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
"""
# Looping Through a String
for x in "banana":
print(x)
# The break Statement
fruits = ["apple", "banana", "cherry"]
for x... | true |
25b76979d4c22ea67555610bb4f64dc8f713d8f8 | Sevansu/Python-Tasks-Basic-to-Advance | /Task 2/task_2_01_A.py | 1,151 | 4.15625 | 4 | #1. Create two python files. say 'task_2_01_A.py' and 'task_2_01_B.py'. Create a class in the 'task_2_01_A.py' having some attributes and functions and constructor defined in the class. Create a method outside that class in the file 'task_2_01_A.py'. Use that class and its attributes and mehtods and the method that is ... | true |
6d3bbf1614e30f76dcbe63a9091b78e635e6fbc3 | AlexPolGit/Python-Projects | /strings_test.py | 623 | 4.5625 | 5 | #strings_test.py
#Testing out string functions Python
string = "python is a programming language"
print "\nOriginal string:"
print string
print "\nAs a sentence:"
print string.capitalize() + "!"
print "\nLength of string:"
print len(string)
print "\nNumber of g's: "
print string.count("g")
print "\nIs alphabetic?... | true |
015964ff2101192be30278b7e38b9e8e6254c937 | kulvirvirk/Python_Number | /main.py | 770 | 4.125 | 4 | #declare some math variables
x = 6
y = 2.2
print('x = 6 \ny = 2.2\n')
#perform some math functions
sum = x + y;
print('sum is: ' + str(sum))
substraciton = x - y
print('difference is: ' + str(substraciton))
multiplication = x * y
print('multiplication is: {:0.2f}'.format( multiplication))
# output is formated
#... | true |
c23356283979892d890518e937c29992ff6efdde | naughtona/COMP10001 | /Tute-10/fibonacci.py | 964 | 4.46875 | 4 |
def fibonacci_r(n: int) -> int:
''' uses recursion to calculate fibonacci number
`n`: a non-negative integer
returns: the fibonacci number for `n`
'''
# base case #1
if n == 0:
return 1
# base case # 2
elif n == 1:
return 1
# recursive case
els... | false |
cfa75fa7477dcd832853b4a34a13d889c8f708ce | QLGQ/learning-python | /prime.py | 1,139 | 4.21875 | 4 | #-*-coding:utf-8-*-
#Set a condition for exiting the loop
def main(maximum=1000):
pr = primes(maximum)
for n in pr:
if n < maximum:
print(n)
else:
break
#Construct a sequence of odd numbers starting from 3
def _odd_iter(maximum):
n = 1
while n < maximum:
... | true |
9f580eff78dd811bae154193b94535881327d541 | PunjabiTadka/FIT1008_Assignment1 | /29202515_Assessment1/Task4_A.py | 2,469 | 4.375 | 4 | """
@author: Amrita Kaur
@since: 16/3/2018
@modified: 17/3/2018
"""
def populateList(size):
"""
This function takes in the size as an argument,
and accepts 'size' number of inputs from the user, stores them in
a list and returns it
@:param size: The number of inputs to accept fro... | true |
d629ec1ddb5e77cb43a491ab39e285928d659a23 | taarunsinggh/class-work | /33.py | 682 | 4.34375 | 4 | #3-3. Your Own List: Think of your favorite mode of transportation, such as a
#motorcycle or a car, and make a list that stores several examples. Use your list
#to print a series of statements about these items, such as “I would like to own a
#Honda motorcycle.”
transport=['bus','motorcycle','scooter','train','flight... | true |
7f579387832a0fe9dc55fdfa1e0651560d3710d7 | taarunsinggh/class-work | /31.py | 289 | 4.34375 | 4 | #Names: Store the names of a few of your friends in a list called names. Print
#each person’s name by accessing each element in the list, one at a time.
names=['Vibhor','Deven','Mohit','Rajbeer','Swapnil']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
| true |
c7a2dd3611c38269715fd6fce7459bb2e6b46e5b | daniloiiveroy/MyPythonTraining | /02-list_tuple_set/app.py | 2,989 | 4.125 | 4 | # from typing_extensions import TypeVarTuple
courses = ["History", "Math", "Physics", "CompSci"]
print(courses) # List
print(courses[2]) # Specific course via index
print(courses[-1]) # Last item
print(courses[0:2]) # List of items
print(courses[2:]) # List of items
# Append function
courses.append("Art I")
pr... | true |
61e8f246443d5a0213fccd12288967be3e9eb4e9 | daniloiiveroy/MyPythonTraining | /10-input/app.py | 2,111 | 4.28125 | 4 | #### input function
"""
name = input("What is your name?")
print(name)
birth_year = input("Birth year: ")
age = 2021 - int(birth_year)
print(age)
w_lbs = input("What is your weight(in lbs)?")
w_kg = int(w_lbs) * 0.45359237
print(w_kg)
"""
#### input chars validation
"""
name = input("What is your name?")
if len(name... | false |
7d31ad86b378446d2397312cfec27c90e9aebf9f | fadikoubaa19/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 235 | 4.15625 | 4 | #!/usr/bin/python3
""" module that contains the append write"""
def append_write(filename="", text=""):
""" appends a string to end of txt file"""
with open(filename, 'a', encoding='utf-8') as f:
return f.write(text)
| true |
bdc0c9be95f2bc224281624a42fa6347abf4c7ff | MapleDa/Python | /topic13_files_io.py | 1,241 | 4.15625 | 4 | #T13Q1
#The open method returns a file object. Syntax: open(name[, mode]). where mode
#can be 'r' (read), 'w'(write) or 'a'(append). The default mode is 'r'.The
#close method closes an opened file object.
filename = 'tmp.txt'
mode = 'w'
f = open(filename, mode) # open a file
f.write('hello') # write t... | true |
95c8cd2f0e63aab72f9862fc611ca54ed30970ce | dansmyers/IntroToCS | /Examples/2-Conditional_Execution/is_positive.py | 222 | 4.28125 | 4 | """
Test if an input number is positive, negative, or zero
"""
value = int(input('Type a number.'))
if value > 0:
print('Positive.')
elif value < 0:
print('Negative.'
else:
print('Zero.')
print('Done.')
| true |
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03 | alosoft/bank_app | /bank_class.py | 2,453 | 4.3125 | 4 | """Contains all Class methods and functions and their implementation"""
import random
def account_number():
"""generates account number"""
num = '300126'
for _ in range(7):
num += str(random.randint(0, 9))
return int(num)
def make_dict(string, integer):
"""makes a dictionary of Account N... | true |
0faa10eb9f27bfeb219c7330240439dd74392e65 | plazmer/prodb_py | /2018/01/01_Moldobaev.py | 2,918 | 4.15625 | 4 | import re
# Работа со списками
# Написать код для функций ниже
# Проверка производится в функции main()
# 00. Пример. Дан список (list) строк. Вернуть число - количество строк, у которых
# 1. длина строки 2 и больше
# 2. первый и последний символ одинаковые
def func00(words):
count = 0
for w in words:
... | false |
a4d288d865bd0661a99061a385f54229f461be0f | brunorafael96/Calculo_area_retangulo_circulo | /Calculo_Area/Calculo_Area/Calculo_Area.py | 790 | 4.3125 | 4 | print ("Bem-vindo ao programa de calculo da area de Retangulos e Circulos")
print ("-----------------------------------------------")
print ("Programa criado por Bruno Rafael")
print ("================================")
#Menu de escolha do usurio
print ("Escolha a forma que deseja calcular a area:")
print ("Digite a p... | false |
c333d408b37574b13a5f92fb68825e4725ac223e | samdish7/COSC420 | /Notes/Py/pyfuncs.py | 1,104 | 4.25 | 4 | # Python functions are defined with the
# "def" keyword, then the name, list of
# parameters, then a colon.
# note that functions do not have
# return types, and parameters do not
# have types (but you can provide them
# anyway)
# scopes in python are delineated not by
# curly braces (as in c/c++) but by tabs
# you ca... | true |
72f6a15f8adc58899ea401ee378d2e9ddc5367ae | bryyang/unirioja | /TEMA3/secCar.py/palindromo.py | 286 | 4.125 | 4 | # Introducir una cadena de caracteres e indicar si es un palíndromo. Una palabra
# palíndroma es aquella que se lee igual adelante que atrás.
cad = input("Introduce una cadena:")
if cad.lower() == cad[::-1].lower():
print("Es un palíndromo")
else:
print("No es un palíndromo")
| false |
6fd3b644ed043a8b288065be615f638f9436e8b0 | awlange/project_euler | /python/p72.py | 1,834 | 4.1875 | 4 | import time
from p27 import get_primes_up_to
def farey(n):
"""
Thanks for the help Wikipedia!
Python function to print the nth Farey sequence, either ascending or descending.
"""
a, b, c, d = 0, 1, 1, n
print "%d/%d" % (a,b)
while c <= n:
k = int((n + b)/d)
a, b, c, d = c,... | true |
ec3d2376bf613dbc7f9559e3ef2cad2d4b717cb4 | awlange/project_euler | /python/p38.py | 886 | 4.15625 | 4 | # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated
# product of an integer with (1,2, ... , n) where n > 1?
digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
len_digits = len(digits)
len_digits_plus_one = len(digits) + 1
is_pan_range = range(1, len_digits_plus_one)
MAX_P... | false |
f9b7c11118c0e2ccf65dab75f01d0cdb1001532a | nrglll/katasFromCodeWars | /string_example_pigLatin.py | 1,052 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 15:44:33 2020
@author: Nurgul Aygun
"""
# =============================================================================
# Kata explanation:
# Move the first letter of each word to the end of it, then add "ay" to
# the end of the word. Leave punctuation marks untouched... | true |
2fdb8c0b1434cf8ce72e7c6f6840166c8d72ffd5 | azka97/practice1 | /beginner/PrintInput.py | 642 | 4.125 | 4 | #input() will by default as String
#basic math same as other language, which is +,-,/,*
#exponent in python notated by '**'
#There's '//' which is used for devided number but until how many times it will be reach the first number. Was called ' Integer Division'
#Modulus operator notated by '%'. This is the remain n... | true |
b2a2f7598364273be0ca0a62e3339fe7cf4f2695 | LalitGsk/Programming-Exercises | /Leetcode/July-Challenge/prisonAfterNDays.py | 1,700 | 4.125 | 4 | '''
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
We de... | true |
5409e790168cb5f59ad3e1f4ef8dc63914cf2245 | MadhanBathina/python | /odd even count of in between intigers of two numbers.py | 519 | 4.21875 | 4 | Start=int(input('Starting intiger :'))
End=int(input('Ending intiger :'))
if Start < 0 :
print('1 ) The numbers lessthan 0 is not supposed to be count as either odd or even.')
print('2 ) {0} to -1 are not considered as per the above statement.'.format(Start))
Start = 0
oddcount = 0
evencount= 0
for i ... | true |
84b5d6b336751efd0e7f9a6bde1a8ad50e5631f2 | RohiniRG/Daily-Coding | /Day39(Bit_diff).py | 896 | 4.28125 | 4 | # You are given two numbers A and B.
# The task is to count the number of bits needed to be flipped to convert A to B.
# Examples :
# Input : a = 10, b = 20
# Output : 4
# Binary representation of a is 00001010
# Binary representation of b is 00010100
# We need to flip highlighted four bits in a
# to make it b.
# I... | true |
f35713a8ec7b2fbf0a0c957c023e74aa58cd55db | randyarbolaez/codesignal | /daily-challenges/swapCase.py | 232 | 4.25 | 4 | # Change the capitalization of all letters in a given string.
def swapCase(text):
originalLen = len(text)
for i in text:
if i.isupper():
text += i.lower()
else:
text += i.upper()
return text[originalLen:]
| true |
89f316d8298d5ccbdbac841a9a6f3eea5d67d8e4 | randyarbolaez/codesignal | /daily-challenges/CountDigits.py | 259 | 4.1875 | 4 | # Count the number of digits which appear in a string.
def CountDigits(string):
totalNumberOfDigits = 0
for letterOrNumber in string:
if letterOrNumber.isnumeric():
totalNumberOfDigits += 1
else:
continue
return totalNumberOfDigits
| true |
69663c4050dbcfc286850f7182b9769d53fb6305 | eflipe/developer_exercises_python | /simple/simple.py | 2,282 | 4.21875 | 4 | '''
Hacer una función que genere una lista de diccionarios
que contengan id y edad, donde
edad sea un número aleatorio entre 1 y 100 y la longitud de la
lista sea de 10 elementos. Retornar la lista.
Hacer otra función que reciba lo generado en la primer
función y ordenarlo de mayor a menor.
Printear el id de la persona... | false |
d008f4f9d0f64f72bbda7be1909e5ae71f2cf1fc | Fittiboy/recursive_hanoi_solver | /recursive_hanoi.py | 707 | 4.25 | 4 | step = 0
def move(fr, to):
global step
step += 1
print(f"Step {step}:\tMove from {fr} to {to}")
def hanoi(fr, to, via, n):
if n == 0:
pass
else:
hanoi(fr, via, to, n-1)
move(fr, to)
hanoi(via, to, fr, n-1)
n = input("\n\nHow many layers does your tower of Hanoi hav... | true |
34a1160271b9db20ca0eca1839bc991abc0a2351 | coderboom/Sample | /chapter05/slice_test.py | 830 | 4.1875 | 4 | """
切片模式:[start:end:step]
start:切片开始位置,默认为0
end:切片截止位置,但不包括该位置,默认是列表长度
step:切片步长,默认是1个步长,当步长是负数时,表示反向切片,这时候start的数值应该大于end的数值
重点:切片操作返回的是一个新的list,不会改变原list
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[1:9:2])
"""
带点技术的操作
"""
a[:0] = [1, 2] # 在列表头部插入元素
a[3:3] = [5] # 将3这个位置的元素改变成5
a[:3] = [1, 2, 3] # 将前三个元素更改成1,2,3... | false |
7aa978fad9e053f9d0541bb07585ba90027fcd6e | Digit4/django-course | /PYTHON_LEVEL_ONE/Part10_Simple_Game.py | 2,536 | 4.21875 | 4 | ###########################
## PART 10: Simple Game ###
### --- CODEBREAKER --- ###
## --Nope--Close--Match-- ##
###########################
# It's time to actually make a simple command line game so put together everything
# you've learned so far about Python. The game goes like this:
# 1. The computer will think o... | true |
67a64d653913f1c4a706347ec55165f0c57412ac | cesarmarcanove/Remesas | /Codigos/Python/remesa5py3.py | 1,268 | 4.21875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
print("Ingrese monto en dolares a enviar la remesa: $")
env = float(input())
print("Cuantas personas desea enviar: ")
p = float(input())
print("") # no hay forma directa de borrar la pantalla con Python estandar
print(" ")
# Can... | false |
d05dd4b1903d781d594e0b125266c3a58706382b | jon-moreno/learn-python | /ex3.py | 769 | 4.34375 | 4 | print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh that's why... | true |
1edaebb9de5aff4e3aa4e56d610ae3267069df11 | snu-python/pythonbook | /lab/lab8_2.py | 1,538 | 4.15625 | 4 | #!/usr/bin/env python
"""This file is provided for educational purpose and distributed for class use.
Copyright (c) by Jinsoo Park, Seoul National University. All rights reserved.
File name.....: lab8_2.py
Description...: Sample solution for Lab 8-2.
This program demonstrates how to use a nested condit... | false |
cdb1e82b5ef9b5dd5465d8367fbed6bcd791e774 | snu-python/pythonbook | /lab/lab8_4.py | 845 | 4.28125 | 4 | #!/usr/bin/env python
"""This file is provided for educational purpose and distributed for class use.
Copyright (c) by Jinsoo Park, Seoul National University. All rights reserved.
File name.....: lab8_4.py
Description...: Sample solution for Lab 8-4.
This program demonstrates how to use a for statement... | false |
631922ad9ea661de547af2af1a1500fb5ec4c065 | maahokgit/Python-Assignments | /Assigments/Assignment4/AManNamedJed/aManNamedJedi.py | 2,037 | 4.28125 | 4 | """
Student Name: Edward Ma
Student ID: W0057568
Date: November 16, 2016
A Man Named Jedi
Create a program that will read in a file and add line numbers to the beginning of each line.
Along with the line numbers, the program will also pick a random line in the file and convert it to all capital letters.
All ot... | true |
54b3407b8081d12dd367de06980258e6f0e179b1 | rusivann/Rep_Nata_Pyneng | /5_PyBaseScripts/task_5_4.py | 949 | 4.1875 | 4 | #vhodnie dannie - 2 spiska
num_list = [10, 2, 30, 100, 10, 50, 11, 30, 15, 7]
word_list = ['python', 'ruby', 'perl', 'ruby', 'perl', 'python', 'ruby', 'perl']
#zapros parametrov u polzovatelya. te, которые будем искать
numindex = int(input('Vevdite chislo: '))
wordindex = input('Vvedite slovo: ')
#переворачиваем списк... | false |
ef552df18f1f97c7c05ba73ad9b78e3f34cd7481 | wook2124/Python-Challenge | /#1/#1.12 for in.py | 416 | 4.15625 | 4 | # for문
# x라는 변수는 for문이 실행되면서 만들어짐
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
for x in days:
print(x)
for x in [1, 2, 3, 4, 5]:
print(x)
# for loop 중단
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
for x in days:
if x == "Wed":
break
else:
print(x)
# Python에선 str도 배열임
# str, tuple or list를 순차적으로 나타냄
f... | false |
55701fa458fc998a4d3fe5e38afec0808d36e88f | matthewlee1/Codewars | /create_phone_number.py | 484 | 4.125 | 4 | # Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
#Example:
# create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
def create_phone_number(n):
f = "".join(map(str, n[:3]))
s = "".join(ma... | true |
9116283a58b98e8debeea1bb279fc1988d9e0f1a | Ahameed01/tdd_challenge | /weather.py | 1,015 | 4.125 | 4 |
# Assume the attached file port-harcourt-weather.txt contains weather data for
# Port Harcourt in 2016. Download this file and write a program that returns the
# day number (column one) with the smallest temperature spread (the maximum
# temperature is the second column, the minimum the third column).
filename = "p... | true |
225160859f926e7f08af188dbceb46c9c81a35b1 | carrba/python-stuff | /pwsh2python/functions/ex1.py | 369 | 4.125 | 4 | #!/usr/bin/python3.6
def divide (numerator, denominator):
myint = numerator // denominator
myfraction = numerator % denominator
if myfraction == 0:
print("Answer is", myint)
else:
print("Answer is", myint, "remainder", myfraction)
num = int(input("Enter the numerator "))
den = int(i... | true |
ca02219c4ec546314f18f7f2779f815833e13951 | arohigupta/algorithms-interviews | /hs_interview_question.py | 1,794 | 4.21875 | 4 | # def say_hello():
# print 'Hello, World'
# for i in xrange(5):
# say_hello()
#
# Your previous Plain Text content is preserved below:
#
# This is just a simple shared plaintext pad, with no execution capabilities.
#
# When you know what language you'd like to use for your interview,
# simply choose it from ... | true |
b687c97076dba795663606e9dc2c30408cf47d31 | arohigupta/algorithms-interviews | /fizz_buzz_again.py | 673 | 4.1875 | 4 | #!/usr/bin/env python
"""fizz buzz program"""
def fizz_buzz(fizz_num, buzz_num):
"""function to print out all numbers from 1 to 100 and replacing the numbers
completely divisible by the fizz number by 'Fizz', the numbers completely
divisible the buzz number by 'Buzz' and the numbers completely divisible b... | true |
0ddd67e8196a7c21f532dadc2afd69586bc8d228 | marykamau2/katas | /python kata/even_odd/even_odd.py | 221 | 4.34375 | 4 | def even_odd():
num = int(input('Enter number to find whether is even or odd\n'))
if num % 2 ==0:
print(f"{num} is an even number")
else:
print(f"{num} is an odd number")
even_odd() | false |
59df6da3c92f45d1fabcbcc6411cba06e0fe1a82 | yingzk/leetcode_python3 | /LCP1.py | 1,284 | 4.3125 | 4 | """
LCP 1. 猜数字
小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次?
输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。
示例 1:
输入:guess = [1,2,3], answer = [1,2,3]
输出:3
解释:小A 每次都猜对了。
示例 2:
输入:guess = [2,2,3], answer = [3,2,1]
输出:1
解释:小A 只猜对了第... | false |
aa7d509d810a2c2aed89ffbf7ffd63a04a094702 | AmandaCasagrande/Entra21 | /08-10-20 Funções/Exercicio 5.py | 809 | 4.1875 | 4 | #--- Exercício 5 - Funções
#--- Crie uma função para calculo de raiz
#--- A função deve ter uma variável que deternine qual é o indice da raiz(raiz quadrada, raiz cubica...)
#--- Leia um número do console, armazene em uma variável e passe para a função
#--- Realize o calculo da raiz e armazene em uma segunda variável e... | false |
441329bf024a6db66f938d86543d361dba98d2b6 | Moondance-NL/Moondance-NL | /ex1.py | 792 | 4.5 | 4 | print("I will now count my chickens:")
# we are calulating the number of hens and roosters
print("Hens", 25.0 + 30.0 /6.0)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
# we are calculating the number of eggs
print(3.0 + 2.0 + 1-5 + 4 % 2-1 / 4.0 + 6.0)
# we are attemting to find the ... | true |
c73ae82e5ebb3620f75fe89425d294858dc6a4f9 | krishnabojha/Insight_workshopAssignment4 | /Question5.py | 559 | 4.3125 | 4 | ########## sorting the list of tuple
info_tuple=('krishna','ojha',1)
more_tuple=(('jeevan','rai',2),('hari','magar',3),('bikash','khanal',4),('binod','gauli',5))
people=[]
dictionary={0:'first name',1:'last name',2:'age'}
people.append(info_tuple)
for i in more_tuple:
people.append(i)
people.sort()
for num in range... | false |
4733713d4de3ca0f91ff841167162ff8f963c445 | chuymedina96/coding_dojo | /chicago_codes_bootcamp/chicago_codes_python/python_stack/python/fundamentals/practice_strings.py | 2,028 | 4.78125 | 5 | print ("Hello world")
#Concatentaing strings and variables with the print function.
# multiple ways to print a string containing data from variables.
name = "zen"
print("My name is,", name)
name = "zen"
print("My name is " + name)
#F-strings (Literal String Interpolation)
first_name = "zen"
last_name = "Coder"
a... | true |
aa9eb750a1e0c98949015dd27e7d2c5ff2805a75 | MrFichter/RaspSort1 | /main.py | 947 | 4.375 | 4 | #! /usr/bin/python
#sort a file full of film names
#define a function that will return the year a film was made
#split the right side of the line a the first "("
def filmYear(film):
return film.rsplit ('(',1)[1]
#load the file into a list in Python memory
#and then close the file because the content is now in mem... | true |
16476b4d24d16e37cb1d39f2ba7936024c36049c | MrFlava/justforfun | /numerical_methods/lab1.py | 803 | 4.1875 | 4 | """
Лабораторная работа #1
Вариант 9
"""
import math
print("Имеется такое нелинейное уравнение : 2*x^2 - 0.5^x -3 = 0")
a = float(input('Введите левую границу: '))
b = float(input('Введите правую границу: '))
epsi = 0.0001
f = lambda x: 2*math.pow(x,2) - math.pow(0.5, x) - 3
def main(a, b, f):
x = ... | false |
e5e977a9161532cc3edbc877583722fedb5237f2 | habib-zawad/temperature_converter | /Temperature_converter.py | 1,389 | 4.34375 | 4 | type1 = input("What type of temperature you want to convert: ")
type2 = input("What type of temperature you want to convert to: ")
temp1 = int(input("Give any temparature: "))
def celsius() :
celsius_to_kelvin = ((temp1*100)/5) - 273
celsius_to_fahrenheit = ((temp1*9)/5)+32
if type2 == "kelvi... | false |
6f45f96db8842b4d33ac2b175bd374be223586fb | Jatin345Anand/Python | /AdvancePython/Regex/02-EmailValidate.py | 215 | 4.125 | 4 | import re
pattern = '([a-z | 0-9]\w+([.]\w+)|(\w+))([@]\w+([. | -]\w+)+|([.]\w+))'
email_id = input("Enter emailID : ")
if re.match(pattern, email_id):
print("Email Valid")
else:
print("Invalid") | false |
5fa02380f2b135d461422edd160ce54ce6155bfc | Jatin345Anand/Python | /CorePython_Evening/Programs/02-Patterns.py | 299 | 4.1875 | 4 | # for i in range(1,6):
# print("*" * i)
# for i in reversed(range(1,6)):
# print("*" * i)
# for i in range(1,7):
# for j in range(1,i+1):
# print(i, end="")
# print()
for i in range(0,5):
for j in range(1,6):
print(j, end="-----")
print()
| false |
78aa440d42b3f7014e1b789c18f2e7eff465fbce | tanigawahcu/Algorithm-Queue-Python-List-Standard | /my_queue3.py | 1,277 | 4.25 | 4 | # 参考URL
# - https://note.nkmk.me/python-collections-deque/
#
from collections import deque
class MyQueue:
def __init__(self):
self.arr = deque()
# enqueue
def enqueue(self, val):
self.arr.append(val)
# dequeue
def dequeue(self) :
return self.arr.popleft()
# スタックの... | false |
24f0d8e088b03f8cf0f4b9d56b1b60cc46e43475 | zhoubofsy/persistence_calculation | /common.py | 563 | 4.15625 | 4 | #!/usr/bin/env python2.7
# coding:utf-8
#
# 计算阶乘方法
#
def factorial(n, s = 1):
if n <= 1 or n < s :
return 1
return reduce(lambda x,y:x*y, range(s,n+1))
#
# 计算组合方法
#
def combination(up,down):
if up > down:
return -1
result = factorial(down) / (factorial(up) * factorial(down - up))
... | false |
5ddd37de5416a1aca026182914fc7ea873916c5b | NataliaMiroshnik/GeekBrains | /HW3/task4.py | 671 | 4.1875 | 4 | x = float(input('Введите положительное число'))
while x < 0:
x = float(input('Упс. Введено отрицательное число. Введите еще раз положительно число'))
y = int(input('Введите отрицательно число'))
while y > 0:
y = int(input('Упс. Введено положительно число. Введите еще раз отрицательно число'))
# def my_func= lam... | false |
df80aedb4695956eb49f9be9b4954eaa246f951e | PeaWarrior/learn-py | /ex_07/ex_07_02.py | 914 | 4.28125 | 4 | # Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
# X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then comput... | true |
469b980fe77547f9eb561ce3f32765d59fe955b7 | PeaWarrior/learn-py | /ex_12/ex_12_04.py | 716 | 4.125 | 4 | # Exercise 4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved HTML document and display the count of the paragraphs as the output of your program. Do not display the paragraph text, only count them. Test your program on several small web pages as well as some larger web pages.
... | true |
dda3db3cfe5bc83d4fe5e6f2fc0b8390b612d190 | carlosbognar/Estudos | /IF-Aninhamento.py | 234 | 4.1875 | 4 | # Exemplo de ANINHAMENTO de IF
x = int(input("Entre com um numero inteiro: "))
if x < 0:
x = 0
print("Negativo foi alterado para zero")
elif x == 0:
print("Zero")
elif x == 1:
print("Single")
else:
print("More")3
| false |
3a0901237a66a5715908ee743799495d3fb0585a | carlosbognar/Estudos | /Strings-Find-Text.py | 550 | 4.40625 | 4 | #########################################################################
# O método FIND permite encontrar um texto / substring em um string
# FIND retorna a posição em que o texto foi encontrado
# Se o valor não for encontrado, retorna -1
########################################################################
s1 = '... | false |
a26b5cd237a7e7b869ccaca6b95de07006966e8f | carlosbognar/Estudos | /Listas-Pilha.py | 626 | 4.34375 | 4 | # O Objetivo é utilizar uma Lista como Pilha (STACK)
# POP-Lista: Retira um elemento da Pilha (POP)
a = [1, 12, 8, 23, -45, 7, 6, 10, 'Carlos', 'Eduardo']
a.pop() # Retira o elemento 'Eduardo' da Lista - Último
a.pop() # Retira o elemento 'Carlos da Lista - Último
a.pop() # Retira o elemento 10 da Lista - Últ... | false |
b987329024f5b6288fe91e12fc6ca46c605c5440 | carlosbognar/Estudos | /Listas-Append-List.py | 338 | 4.34375 | 4 | # APPEND-Lista: Adiciona uma uma Lista em outra Lista.
# Note que a Lista adicionada é tratada como um único elemento
a = [1, 2, 12, 23, 45, 67, 'Carlos', 'Eduardo']
b = ['x', 'y', 'z']
a.append(b) # Adiciona a lista b na lista a. A lista b é tratada como um único elemento
for x in a:
print(x, end=' ')
print(... | false |
ef208f4362977df250747f5406710b1c60264887 | carlosbognar/Estudos | /Strings-Number-Of-Worlds.py | 374 | 4.15625 | 4 | #########################################################################
# O método LEN combinado com o método SPLIT permite a contagem do número
# de palavras em uma determinada linha
########################################################################
s = input("Entre com uma linha de texto: ")
print("O numero ... | false |
066da0f2759113dc0b1289705f92311fe6abb01e | JamieJ12/Team-23 | /Functions/Function_6.py | 2,655 | 4.15625 | 4 | def word_splitter(df):
"""
The function splits the sentences in a dataframe's column into
a list of the separate words.:
Arguments: The variable 'df' is the pandas input.
Returns: df with the added column named 'Splits Tweets'
Example:
Prerequites:
>>> twitter_url = 'https://raw.gi... | true |
4617883396bfe24d19ab40f77451291f088721ec | yuanxu-li/careercup | /chapter6-math-and-logic-puzzles/6.8.py | 1,714 | 4.28125 | 4 | # 6.8 The Egg Drop Problem: There is a building of 100 floors. If an egg drops
# from the Nth floor or above, it will break. If it's dropped from any floor
# below, it will not break. You're given two eggs. Find N, while minimizing the
# number of drops for the worst case.
# Here I denote floors from 0 to 99
import r... | true |
89b2cab05c4ecf1a2a10c60fa306ef7f8ea79bed | yuanxu-li/careercup | /chapter16-moderate/16.24.py | 845 | 4.15625 | 4 | # 16.24 Pairs with Sum: Design an algorithm to find all pairs of integers within
# an array which sum to a specified value.
from collections import Counter
def pairs_with_sum(arr, k):
"""
put all elements into a Counter (similar to a dict), for each value, search for the complementary value
>>> pairs_with_sum([1, ... | true |
3bf4269c79a0b223fad38ae3a178a5e7c5212fe2 | yuanxu-li/careercup | /chapter10-sorting-and-searching/10.2.py | 966 | 4.46875 | 4 | # 10.2 Group Anagrams: Write a method to sort an array of strings so that all the anagrams are
# next to each other.
from collections import defaultdict
def group_anagrams(strings):
"""
create a dict to map from a sorted string to a list of the original strings, then simply all strings mapped
by the same key will ... | true |
7837501cf9c4e8589734f09883875d0fff5c2062 | yuanxu-li/careercup | /chapter8-recursion-and-dynamic-programming/8.4.py | 1,436 | 4.25 | 4 | # 8.4 Power Set: Write a method to return all subsets of a set.
def power_set(s, memo=None):
""" For a set, each we add it to the final list, and run the algorithm against its one-item-less subset
>>> power_set(set([1,2,3,4,5]))
[{1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}, set(), {4}, {3, 5}, {3}, {3, 4}... | true |
858dd659ac6bb2648fca973c6695abcdccddd951 | yuanxu-li/careercup | /chapter5-bit-manipulation/5.8.py | 1,585 | 4.28125 | 4 | # 5.8 Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels
# to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split
# across rows). The height of the screen, of course, can be derived from the length of the array and ... | true |
81a90ce343ff4d49098ada9f12429821aed4e57b | yuanxu-li/careercup | /chapter16-moderate/16.16.py | 1,330 | 4.125 | 4 | # 16.16 Sub Sort: Given an array of integers, write a method to find inices m and n such
# that if you sorted elements m through n, the entire array would be sorted. Minimize n - m
# (that is, find the smallest such sequence).
# EXAMPLE
# Input: 1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19
# Output: (3, 9)
import pdb
... | true |
b49ddf7666de93c2f767510cc8354e4e556009cb | yuanxu-li/careercup | /chapter8-recursion-and-dynamic-programming/8.10.py | 1,215 | 4.1875 | 4 | # 8.10 Paint Fill: Implement the "paint fill" function that one might see on many image editing programs.
# That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color,
# fill in the surrounding area until the color changes from the original color.
def paint_fill(array, row, co... | true |
d62dee378aee2ad5621da0821e3d26bb801e741b | yuanxu-li/careercup | /chapter4-trees-and-graphs/4.3.py | 1,264 | 4.125 | 4 | # 4.3 List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the
# nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists)
from collections import deque
class Node:
def __init__(self):
self.left = None
self.right = None
def list_of_depths(sel... | true |
905d3e94a6e6ab1bcd68bd26b6839baf5b178bd4 | yuanxu-li/careercup | /chapter1-arrays-and-strings/1.7.py | 1,623 | 4.34375 | 4 | # 1.7 Rotate Matrix: Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate
# the image by 90 degrees. Can you do this in place?
def rotate_matrix(matrix):
""" Take a matrix (list of lists), and rotate the matrix clockwise
>>> rotate_matrix([[1,2,3],[4,5,6],[7... | true |
0db6f0e7aaf5666e4b839fc40d977672988b32cd | yuanxu-li/careercup | /chapter10-sorting-and-searching/10.4.py | 1,487 | 4.15625 | 4 | # 10.4 Sorted Search, No size: You are given an array-like data structure Listy which lacks a size method. It does, however,
# have an elementAt(i) method that returns the element at index i in O(1) time. If i is beyond the bounds of the data structure,
# it returns -1. (For this reason, the data structure only support... | true |
cfe6b37df8a61267c86f0623c3c3cec9b1f495a3 | RenanGouveia/LingProg | /2018 09 18/ativ1.py | 1,069 | 4.28125 | 4 |
"""
Crie a classe Linha que tem dois atributos, coordenada1 e coordenada2.
Cada coordenada é uma tupla que carrega duas coordenadas cartesianas (x,y) que
denotam pontos do segmento de reta. Faça métodos que calculem o comprimento
do segmento de reta e sua inclinação.
"""
class Linha:
def __init__(self, coordena... | false |
594c8696b31b94ca23f15fdb499fa79a08c970fe | Mythologos/Pythonic-Pursuits-Course-Material | /Exercise Answers/Lecture 2 & Bridge 2 - Sample Answers/tenChallenge.py | 718 | 4.125 | 4 | # Lecture 2, Exercise 3:
def when_ten_v2(number):
if number == 10:
print("Done!")
elif number > 10:
print("Too high!")
when_ten_v2(number - 1)
else:
print("Too low!")
when_ten_v2(number + 1)
def when_ten_v3(number):
difference: int = number - 10
if differenc... | false |
7c0e1d9a77cfb59763f5067ce087deb67eeb2181 | w4jbm/Python-Programs | /primetest.py | 1,018 | 4.125 | 4 | #!/usr/bin/python3
# Based on code originally by Will Ness:
# https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621
#
# and updated by Tim Peters.
#
# https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-... | true |
d2dcd6ce2a0e54b4c95acca0dafb9d3aa95c8920 | lxw0109/JavaPractice | /Sort/Bubble/pBubble.py | 1,235 | 4.21875 | 4 | #!/usr/bin/python2.7
#File: pBubble.py
#Author: lxw
#Time: 2014-09-19 #Usage: Bubble sort in Python.
import sys
def bubbleSort(array):
bound = len(array) - 1
while 1:
i = 0
tempBound = 0
swap = False
while i < bound:
if array[i] > array[i+1]:
array[i... | true |
b06883d59473eb92521e61b581674978f79755f5 | TylorAtwood/Hi-Lo-Game | /Hi_Lo_Game.py | 1,455 | 4.34375 | 4 | #!/usr/bin/env python3
#Tylor Atwood
#Hi-Lo Game
#4/14/20
#This is a def to inlcude the guessing game.
def game():
#Immport random library
import random
#Declare varibles. Such as max number, generated random number, and user's number guess
max = int(input("What should the maximum numbe... | true |
4633ab38739af5a13ff2c08c368d59fbb2ad0646 | qianrongping/python_xuexi | /Python_基础/python_数据类型转换.py | 213 | 4.1875 | 4 | # 5. eval() --计算在字符串中的有效Python表达式,并返回一个对象
str2 = '1'
str3 = '1.1'
str4 = '(1000,2000,3000) '
str5 = '[1000,2000,3000]'
print(type(eval(str2)))
print(type(eval(str3)))
| false |
14703a10efdf73974802db15a4d644aa7b9854ea | Garima2997/All_Exercise_Projects | /PrintPattern/pattern.py | 327 | 4.125 | 4 | n = int(input("Enter the number of rows:"))
boolean = input("Enter True or False:")
if bool:
for i in range(0, n):
for j in range(i + 1):
print("*", end=" ")
print("")
else:
for i in range(n, 0, -1):
for j in range(i):
print("*", end=" ")
prin... | true |
2587f2a265238875e932ffcbaaa1b028abbf7929 | Jakksan/Intro-to-Programming-Labs | /Lab8 - neighborhood/pythonDrawingANeighborhood/testingShapes.py | 1,890 | 4.15625 | 4 | from turtle import *
import math
import time
def drawTriangle(x, y, tri_base, tri_height, color):
# Calculate all the measurements and angles needed to draw the triangle
side_length = math.sqrt((0.5*tri_base)**2 + tri_height**2)
base_angle = math.degrees(math.atan(tri_height/(tri_base/2)))
top_angle =... | true |
8d6fb45b0bc9753d718e558815a6e70178db88fd | Vasilic-Maxim/LeetCode-Problems | /problems/494. Target Sum/3 - DFS + Memoization.py | 1,041 | 4.1875 | 4 | class Solution:
"""
Unlike first approach memoization can make the program significantly faster then.
The idea is to store results of computing the path sum for each level in some data
structure and if there is another path with the same sum for specific level than
we already knew the number of path... | true |
5fa3c31eda3e66eeb0fb0de5b7d11f90b03eea6e | notsoseamless/python_training | /algorithmic_thinking/Coding_activities/alg_further_plotting_solution.py | 1,138 | 4.15625 | 4 | """
Soluton for "Plotting a distribution" for Further activities
Desktop solution using matplotlib
"""
import random
import matplotlib.pyplot as plt
def plot_dice_rolls(nrolls):
"""
Plot the distribution of the sum of two dice when they are rolled
nrolls times.
Arguments:
nrolls -... | true |
c2a0a60091658bb900d0fcf3c629c3f284288fa5 | dennisjameslyons/magic_numbers | /15.py | 882 | 4.125 | 4 | import random
#assigns a random number between 1 and 10 to the variable "magic_number"
magic_number = random.randint(1, 10)
def smaller_or_larger():
while True:
try:
x = (int(input("enter a number please: ")))
# y = int(x)
except ValueError:
print("Ever so sorr... | true |
779abded16b15cb8eb80fe3dc0ed36309b9cec59 | MFahey0706/LocalMisc | /N_ary.py | 1,399 | 4.1875 | 4 | # ---------------
# User Instructions
#
# Write a function, n_ary(f), that takes a binary function (a function
# that takes 2 inputs) as input and returns an n_ary function.
def n_ary_A(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x... | true |
4738082f42766a81e204ce364000a790a959fdf1 | JeffreyAsuncion/PythonCodingProjects | /10_mini_projects/p02_GuessTheNumberGame.py | 917 | 4.5 | 4 | """
The main goal of the project is
to create a program that
randomly select a number in a range
then the user has to guess the number.
user has three chances to guess the number
if he guess correct
then a message print saying “you guess right
“otherwise a negative message prints.
Topics: random module, for loo... | true |
5fdfca0bc449b2c504dbba99a02664f760028b5c | gpreviatti/exercicios-python | /MUNDO_01/Aula_09/Ex22.py | 543 | 4.25 | 4 | #crie um programa que leia o nome completo de uma pessoa e mostre:
# o nome com todas as letras maiúsculas
# o nome com todas as letras minúsculas
# quantas letras ao todo (sem considerar espaços)
# quantas letras tem o primeiro nome
nome = input('Digite seu nome completo ')
print('Nome em maiúsculo {}'.format(nome.upp... | false |
38afc6c688dba92012aca122db3c8277b388cd63 | gpreviatti/exercicios-python | /MUNDO_01/Aula_06/Ex04.py | 650 | 4.125 | 4 | #faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas suas informações possiveis
algo = input('Digite algo: ')
print('É um número? {}'.format(algo.isnumeric()))
print('É alfabético? {}'.format(algo.isalpha()))
print('É alfanúmerico? {}'.format(algo.isalnum()))
print('É um caracter d... | false |
c25aef7ae5651beae279649a5d46c483132f5351 | gpreviatti/exercicios-python | /MUNDO_02/Aula_12/Ex36.py | 843 | 4.15625 | 4 | #escreva um programa para aprovar o emprestimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal sabendo que ela não pode exceder 30% do salário ou então o emprestimo será negado
casaVlr = float(inpu... | false |
ff88f375bd9e0ff5d34a60155fac35faaf3c8329 | sec2890/Python | /Python Fundamentals/bike.py | 840 | 4.15625 | 4 | class Bike:
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print("This bike has a price of",self.price,", a maximum speed of",self.max_speed, "and a total of", self.miles, "miles on it.")
... | true |
5c39348a5738894cfffbc2784a86f666d11a4b5b | orlewilson/poo-rcn04s1 | /exemplos/1-classe-objeto/exemplo3.py | 1,029 | 4.34375 | 4 | """
Disciplina: Programação Orientada a Objetos
Turma: RCN04S1
Professor: Orlewilson Bentes Maia
Data: 23/08/2016
Autor: Orlewilson B. Maia
Descrição: Exemplo de criação de classe em Python
"""
#Definindo Classe
class Aluno():
#Definição dos atributos
nome = ""
endereco = ""
dataNascimento = ""
nomeCurso =... | false |
4c6c69d142032702b7fe7772a642d397f7f8fe3b | orlewilson/poo-rcn04s1 | /exercicios/fibonacci.py | 478 | 4.25 | 4 | """
Disciplina: Programação Orientada a Objetos
Professor: Orlewilson B. Maia
Turma: RCN04S1
Autor: Orlewilson B. Maia
Data: 29/11/2016
Descrição: Classe para representar dados de um
Fibonacci
"""
class Fibonacci():
def fib(self,n):
if (n == 1 or n == 2):
return 1
else:
return self.fib(n-2) +... | false |
31a8662d4b9af6881f9237ff5fb57287fd792c28 | CBJNovels/python_study | /venv/Training/P3_Training_list.py | 2,599 | 4.1875 | 4 | # list=['a','b','c']
# #增加及插入
# list.append('d')
# list.insert(4,'e')
# print(list)
#
# #删除及弹出
# del list[4]
# print(list)
# try:
# print(list[4])
# except:
# print('不存在list[4]')
# #注意修改值要记得存入
# print(list.pop())
# print(list)
# list.pop(2)
# print(list)
# #移出相应值
# try:
# list.remove('b')
# print(list)
... | false |
14989dacdda1f7c8cf589f5bdf556c9cbcd6db0e | fhylinjr/Scratch_Python | /learning dictionaries 1.py | 1,196 | 4.1875 | 4 | def display():
list={"ID":"23","Name":"Philip"}
print(list)#prints the whole list
for n in list:
print(n)#prints the keys
print(list.keys())#alternative
print(list["Name"])#prints a specific value
print(list.get("Name"))#alternative
'''list["Name"]="Joe"#change a value in a l... | true |
ef2e6441e658300cd9257daad5b6c31559544330 | fhylinjr/Scratch_Python | /first run.py | 365 | 4.1875 | 4 | Age=int(input("Enter your Age"))
if Age>=0 and Age<=1:
print("You are a baby")
elif Age>1 and Age<=3:
print("You are a toddler")
elif Age>3 and Age<=4:
print("You are a toddler and are in preschool")
elif Age>=5 and Age<10:
print("You are in grade school")
elif Age>=10 and Age<18:
print("You are a t... | false |
4bbadc10900a6ea43dc032411c7d65dca29666e4 | aevri/mel | /mel/lib/math.py | 2,583 | 4.375 | 4 | """Math-related things."""
import math
import numpy
RADS_TO_DEGS = 180 / math.pi
def lerp(origin, target, factor_0_to_1):
towards = target - origin
return origin + (towards * factor_0_to_1)
def distance_sq_2d(a, b):
"""Return the squared distance between two points in two dimensions.
Usage examp... | true |
b25a60e2013b9451ba7eb8db5ead8f56e5a59fcd | Pdshende/-Python-for-Everybody-Specialization-master | /-Python-for-Everybody-Specialization-master/Coursera---Using-Python-to-Access-Web-Data-master/Week-6/Extracting Data from JSON.py | 1,695 | 4.1875 | 4 | '''
In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.