blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3a482094354b75a69d62f9ab36561e81596b8847 | sme1d1/UMKC_DeepLearning2021 | /ICP/ICP2/source/icp2_3.py | 1,635 | 4.34375 | 4 | """
Write a python program to find the wordcount in a file for each line and then
print the output.Finally store the output back to the file.
Input:a file includes two line
Python Course
Deep Learning Course
Output:
Python: 1
Course: 2
Deep: 1
Learning: 1
Note: Your program should work for any number of lines
"""
# Scott McElfresh sme1d1 1/26/2021
with open('words.txt') as reader:
# open our text file to read and close it when we exit
bigstring = '' # create a string to add out file text to
wordcount = [] # create a list to store the word count
countlist = [] # create a list to store the words concatenated with the word count
for x in reader:
bigstring += x # add text to our string
wordlist = bigstring.split() # build a list by splitting our string
# debug print(wordlist)
for words in wordlist:
# go through each word in our our world list, count them, and add the count to our wordcount list
wordcount.append((wordlist.count(words)))
i = 0
for words in wordlist:
countlist.append(wordlist[i] + ": " + str(wordcount[i])) # build our concatenated list of words and counts
i += 1
countlist = list(dict.fromkeys(countlist)) # remove duplicates from the list by dictionary conversion
i = 0
output = "\n" # create a blank line string to append on our text file
for words in countlist:
s = str(countlist[i])
print(s)
output += "\n" + s # add the program output to our output string
i += 1
with open('words.txt', 'a') as writer:
writer.write(output) # append the file with the output string
| true |
4508f1a8dbcc480a2e06f7a04239acb2bd174f11 | aumit210780/Practice-Python | /Taking user input.py | 379 | 4.21875 | 4 | name = input("Enter your name: ")
print(name)
age = input("Enter your Age: ") #Input is always by default string
print(type(age))
print(name,age,sep="\n") #Here \n gives new line
print("You have to typecast for getting right data type...",sep="\n")
name1 = input("Enter your friend name here: ")
age1 = int(input("Enter your friend age: "))
print(name1,age1,sep="\n") | true |
cd20f8f06f7bc4dbb7e34f5c74468359900b7471 | aumit210780/Practice-Python | /Sort and Sorted in list.py | 513 | 4.5 | 4 | lis1 = [11,7,5,15,-9]
print(lis1)
lis1.sort() #It manipulate the original data and sort it into ascending order
print(lis1)
lis1.sort(reverse=True) #It manipulate the original data and sort it into descending order
print(lis1)
lis1.sort(reverse=False) #It manipulate the original data and sort it into ascending order
print(lis1)
#Now if you don't want to manipulate original list but want to sort then follow this in below:
lis2 = [11,5,6,45,55,98,90]
lis3 = sorted(lis2)
print(lis2)
print(lis3) | true |
a1d42b601bdea7b0d63814f5f3ecfa1925f0440e | saurav278/tathastu_week_of_code | /day3/program3.py | 231 | 4.28125 | 4 | def dup(string):
dupString = ""
for x in string:
if x not in dupString:
dupString += x
return dupString
string = input("Enter the string: ")
print("After removing the duplicates is:", dup(string))
| true |
0031adc0bc402f4d848cc031d30441e5353e5434 | saurav278/tathastu_week_of_code | /mini project/Hangman.py | 2,500 | 4.15625 | 4 | import random
import sys
# lets set some variables
wordList = [
"lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop",
"laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat"
]
guess_word = []
secretWord = random.choice(wordList) # lets randomize single word from the list
length_word = len(secretWord)
alphabet = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []
def beginning():
print("Hello Mate!\n")
while True:
name = input("Please enter Your name\n").strip()
if name == '':
print("You can't do that! No blank lines")
else:
break
beginning()
def newFunc():
print("Well, that's perfect moment to play some Hangman!\n")
while True:
gameChoice = input("Would You?\n").upper()
if gameChoice == "YES" or gameChoice == "Y":
break
elif gameChoice == "NO" or gameChoice == "N":
sys.exit("That's a shame! Have a nice day")
else:
print("Please Answer only Yes or No")
continue
newFunc()
def change():
for character in secretWord: # printing blanks for each letter in secret word
guess_word.append("-")
print("Ok, so the word You need to guess has", length_word, "characters")
print("Be aware that You can enter only 1 letter from a-z\n\n")
print(guess_word)
def guessing():
guess_taken = 1
while guess_taken < 10:
guess = input("Pick a letter\n").lower()
if not guess in alphabet: #checking input
print("Enter a letter from a-z alphabet")
elif guess in letter_storage: #checking if letter has been already used
print("You have already guessed that letter!")
else:
letter_storage.append(guess)
if guess in secretWord:
print("You guessed correctly!")
for x in range(0, length_word): #This Part I just don't get it
if secretWord[x] == guess:
guess_word[x] = guess
print(guess_word)
if not '-' in guess_word:
print("You won!")
break
else:
print("The letter is not in the word. Try Again!")
guess_taken += 1
if guess_taken == 10:
print(" Sorry Mate, You lost :<! The secret word was", secretWord)
change()
guessing()
print("Game Over!")
| true |
156fef686252f1273d7fe64cdd1aa94897df47fc | A-Gulati/Recursion-Fibonacci-Numbers | /Recursion-Fibonacci Numbers.py | 213 | 4.15625 | 4 | #Recursion: Fibonacci Numbers
def fibonacci(n):
# Write your code here.
if n==0: return 0
elif n==1: return 1
else: return fibonacci(n-1)+fibonacci(n-2)
n = int(raw_input())
print(fibonacci(n))
| false |
bb4bdfe4e582883c94dffb376aa62dadd8dcfdc7 | aarontwillcock/frc-tc-curricula | /debugging/debugging.py | 735 | 4.15625 | 4 | #Debugging practice!
#Practicing step-over, watch, and expressions
a = 1 #Breakpoint 1
b = 2
c = a + b
#Practicing step into
m = 6 #Breakpoint 2
n = 7
p = multiply(m,n)
#Practicing step out of
#Purpose:
# Multiply two numbers, x and y
def multiply(x,y):
product = x * y #Breakpoint 3
return product
#Purpose:
# Compute factorial of n using recursion
#Description:
# We know that n! = n * (n-1)! = n * (n-1) * (n-2)!
# Instead of a for loop, we can use recursion!
# We know that 0! is 1 and n = n * (n-1)!
# So...
def factorial(n):
#If n is 0...
if(n==0):
#return 1 (since 0! is 1)
return 1
else: #if n is not 0...
#return n*(n-1)!
return n*factorial(n-1) | true |
858d7f94ee577bb40b6e8ce742959dafc1fcdecd | aristanov/stepik | /Курс - программирование на Python/Циклы.Строки.Списки/6.Задачи по материалам недели/task_1.py | 1,099 | 4.15625 | 4 | '''
Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел.
Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать не нужно.
В примере мы считываем числа 1, -3, 5, -6, -10, 13; в этот момент замечаем, что сумма этих чисел равна нулю и выводим сумму их квадратов, не обращая внимания на то, что остались ещё не прочитанные значения.
'''
s = int(input())
result = [s]
r = 0
while(s != 0):
temp = int(input())
result.append(temp)
s += temp
for i in result:
r += i ** 2
print(r) | false |
6f32e2c8038845ed3d943f7016ef864b81d26e36 | camillalyons/first-homework-python | /introduction.py | 947 | 4.1875 | 4 | ##Say "Hello, World!" With Python
if __name__ == '__main__':
print("Hello, World!")
##Python If-Else
if __name__ == '__main__':
n = int(input())
if 6<=n<=20 or n%2==1:
print ('Weird')
else:
print ('Not Weird')
##Arithmetic Operators
if __name__ == '__main__':
a = int(input())
b = int(input())
print (a+b)
print (a-b)
print (a*b)
##Python: Division
if __name__ == '__main__':
a = int(input())
b = int(input())
print (a//b)
print (a/b)
##Loops
if __name__ == '__main__':
n = int(input())
for num in range(n):
print (num**2)
##Write a function
def is_leap(year):
leap = False
if year%4 == 0:
leap = True
if year%100 == 0:
leap = False
if year% 400 == 0:
leap = True
return (leap)
##Print Functionif __name__ == '__main__':
n = int(input())
for el in range(1,n+1):
print (el, end='') | false |
63793ed5eecd80f8a5df430bbe7a75227465fe36 | thejohnjensen/data-structures | /src/merge_sort.py | 1,236 | 4.25 | 4 | """Module for merge sort."""
import timeit
def merge_sort(l):
"""Merge sort takes an a list and divides them into smaller lists and then.
sort the sublists.
"""
if not isinstance(l, (list, tuple)):
raise TypeError('Please input a list or tuple.')
mid = int(len(l) / 2)
if len(l) > 1:
a = merge_sort(l[:mid])
b = merge_sort(l[mid:])
return merge(a, b)
else:
return l
def merge(a, b):
"""
Helper function that sorts each of the smaller arrays from merge_sort.
Help from:
https://codereview.stackexchange.com/questions/154135/recursive-merge-sort-in-python.
"""
merged = []
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
merged.append(a[i])
i += 1
else:
merged.append(b[j])
j += 1
merged += a[i:]
merged += b[j:]
return merged
if __name__ == '__main__':
user_input = input('Input comma seperated numbers: ')
input_list = user_input.split(',')
numbers = [int(i) for i in input_list]
print(merge_sort(numbers))
print('Time: {}'.format(timeit.timeit("merge_sort(numbers)", setup="from __main__ import merge_sort, numbers"))) | true |
38ccb2680d609b537bcca2512687d40cee21d25d | phlergm/ICS4U | /ICS4U/Recursion/SumDigits/iterativeSumDigits.py | 785 | 4.25 | 4 | #-----------------------------------------------------------------------------
# Name: Humza Anwar
# Purpose: To find the sum of the digits of a given number
#
# References:
#
# Author: Humza Anwar
# Created: 20/09/18
# Updated: 25/09/18
#-----------------------------------------------------------------------------
number = input("What p o s i t i v e number u wanna do \n")
number_length = len(number)
sum_of_digits = 0
number = int(number)
print ("--length = " + str(number_length))
while number_length > 0:
print(number)
if number < 0:
sum_of_digits = -1
if len(str(number)) == 1:
sum_of_digits += number
else:
sum_of_digits += (number % 10)
number_length -= 1
number = int(number/10)
print("sum of digits is " + str(sum_of_digits))
| false |
36e89762182d5b55b6653b8fe4f02d23b90f9b1e | Colinek/Codebreaking | /EncryptDecrypt.py | 1,182 | 4.34375 | 4 | ## Encryption/Decryption
choice=True
while choice:
print("""
1.Encrypt
2.Decrypt
3.Exit/Quit
""")
choice=int(input("What would you like to do? "))
if choice==1: ## Encrypt a word/phrase
print("Encryption")
orig = input("Please enter your text (lower case only): ")
shift = input("How many digits to shift? ")
encrypt = ""
for c in orig:
if c >= 'a' and c <= 'z':
encrypt += chr(((ord(c) + int(shift)) - ord('a')) % 26 + ord('a'))
else:
encrypt += c
print(encrypt)
elif choice==2: ## Decrypt a word/phrase
print("Decryption")
orig = input("Please enter your text (lower case only): ")
shift = input("How many digits to shift? ")
decrypt = ""
for c in orig:
if c >= 'a' and c <= 'z':
decrypt += chr(((ord(c) - int(shift)) - ord('a')) % 26 + ord('a'))
else:
decrypt += c
print(decrypt)
elif choice==3:
print("\n Goodbye")
choice = None
else:
print("\n Not Valid Choice Try again")
| false |
ba24604890fced3fe314870608c44accad3aa681 | FlyingMedusa/Elective3 | /STRING_01startswith_endswith.py | 446 | 4.1875 | 4 | all_names = ['Marta', 'Amber', 'Philip', 'Veronica', 'Alex', 'Alice', 'Nicolas', 'Anastasia', 'Noelle', 'Jamie', 'Joe', 'Angellica']
# startswith() endswith()
for name in all_names:
if name.startswith('A') and name.endswith('a'):
print(name, 'starts with an "A" and ends with an "a"')
elif name.startswith('A'):
print(name, 'starts with an "A"')
elif name.endswith('a'):
print(name, 'ends with an "a"')
| true |
3ab4a47204840fcc153d2c2baa5d39d4d0b309cc | lpython2006e/python-samples | /Unit 08 Loops/01 Loops/For Loops/12-For your A.py | 207 | 4.21875 | 4 | phrase = "A bird in the hand..."
# Add your for loop
for char in phrase:
if char == 'A' or char == 'a':
print('X', )
else:
print(char, )
# Don't delete this print(statement!)
print
| true |
edc580e409800496e9ea843395944216236609cc | iamsjn/CodeKata | /hackerrank/fibonacci_modified.py | 214 | 4.15625 | 4 | import math
def fibonacciModified(t1, t2, n):
t3 = t1 + t2 ** 2
if n <= 3:
return t3
return fibonacciModified(t2, t3, n - 1)
if __name__ == "__main__":
print(fibonacciModified(0, 1, 5))
| false |
2db90186e442d6c4531a82400ffff30e8b9ff4a6 | balakrish2001/Basics | /prob sheet 1/Check Leap Year.py | 204 | 4.3125 | 4 | year=int(input("Enter a year to check for leap year:"))
if(((year%4==0)and(year%100!=0))or(year%400==0)):
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
| false |
fef6c083c94e2a93b755dded36ec3dee3cd32676 | gavin66/python-study-notes | /source/magic_methods_properties_iterators/generators.py | 457 | 4.125 | 4 | # 普通生成器
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
nested = [[1, 2], [3, 4], [5]]
for num in flatten(nested):
print(num)
# 递归生成器
def flatten2(nested):
try:
for sublist in nested:
for element in flatten2(sublist):
yield element
except TypeError:
yield nested
print(list(flatten2([[[1], 2], 3, 4, [5, [6, 7]], 8])))
| false |
e53eae6e05a237532560a7b179f5dae5dc6be2ae | ted801008/Practice | /leetcode/mergeTwoSortedList.py | 1,019 | 4.1875 | 4 | class ListNode(object):
def __init__(self,x):
self.data = x
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def add(self,x):
node = self.head
if(self.head == None):
self.head = ListNode(x)
else:
while(node.next):
node = node.next
node.next = ListNode(x)
def printlist(self):
node = self.head
while(node):
print(node.data)
node = node.next
def mergeTwoSortedList(x,y):
xnode = x.head
ynode = y.head
newlist = LinkedList()
while xnode and ynode:
if xnode.data>ynode.data:
newlist.add(ynode.data)
ynode = ynode.next
else:
newlist.add(xnode.data)
xnode = xnode.next
if xnode:
while(xnode):
newlist.add(xnode.data)
xnode = xnode.next
else:
while(ynode):
newlist.add(xnode.data)
ynode = ynode.next
return newlist
l1 = LinkedList()
l1.add(2)
l1.add(5)
l1.add(7)
l2 = LinkedList()
l2.add(1)
l2.add(4)
l2.add(6)
l1.printlist()
print("*"*10)
l2.printlist()
print("*"*10)
l3 = mergeTwoSortedList(l1,l2)
l3.printlist()
| false |
48af7c580a83eb3155f645fcb52c9eb39d166376 | Vocco/numberplay | /numberplay/utils/digits.py | 1,732 | 4.3125 | 4 | """
Functions for number digit manipulation.
"""
import math
from typing import Generator
def is_single_digit(number: int) -> bool:
"""
Determine if a number consists of just one digit.
Parameters
----------
number : integer
The integer to check.
Returns
-------
boolean
True when `number` is a single digit, False otherwise.
"""
return number // 10 in [0, -1] and number != -10
def digit_split(number: int) -> Generator[int, None, None]:
"""
Split a number into its digits.
Parameters
----------
number : integer
A positive integer.
Returns
-------
generator(integer, None, None)
A generator of the digits of `number`, ordered from left to right.
"""
if is_single_digit(number):
yield number
else:
for power in range(math.ceil(math.log(number, 10)) - 1, -1, -1):
yield (number // (10 ** power)) % 10
def lowest_n_digit_number(num_digits: int) -> int:
"""
Get the lowest number consisting of `num_digits`.
Parameters
----------
num_digits : integer
The number of digits the result should have.
Returns
-------
integer
The lowest number with `num_digits` digits, in base 10.
"""
if num_digits == 1:
return 0
return 10 ** (num_digits - 1)
def highest_n_digit_number(num_digits: int) -> int:
"""
Get the highest number consisting of `num_digits`.
Parameters
----------
num_digits : integer
The number of digits the result should have.
Returns
-------
integer
The highest number with `num_digits` digits, in base 10.
"""
return 10 ** (num_digits) - 1
| true |
dbf94bf3a1aad41197663c9747dd68b7a0949c2a | ezequielhenrique/exercicios-python | /ExerciciosPython/ex022.py | 768 | 4.1875 | 4 | # Crie um programa que leia o nome completo de uma pessoa e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras ao todo (sem considerar espaços).
nome = str(input('Digite seu nome completo: ')).strip()
print('Nome em maiúsculas: {}'.format(nome.upper()))
print('Nome em minúsculas: {}'.format(nome.lower()))
qespacos = nome.count(' ') # Conta a quantidade de espaços
caracteres = len(nome) # Conta a quantidade de caracteres
qletras = caracteres - qespacos
print('O nome possui {} letras'.format(qletras))
div = nome.split() # Divide o nome em palavras
qletras1 = len(div[0]) # Mostra o número de letras do primeiro nome
print('Nº de letras do primeiro nome: {}'.format(qletras1))
| false |
a4fe0c74daf424e433065b1cdae824918543249f | dcribb19/bitesofpy | /code_challenges/157/accents.py | 242 | 4.40625 | 4 | from string import printable
def filter_accents(text):
"""Return a sequence of accented characters found in
the passed in lowercased text string
"""
return sorted([char.lower() for char in text if char not in printable])
| true |
6f7a435c7ca56018cbd76f4c810fa46cdc7e5b73 | dcribb19/bitesofpy | /code_challenges/316/movie_budget.py | 1,261 | 4.21875 | 4 | from collections import defaultdict
from datetime import date
from typing import Dict, List, Sequence, NamedTuple
class MovieRented(NamedTuple):
title: str
price: int
date: date
RentingHistory = Sequence[MovieRented]
STREAMING_COST_PER_MONTH = 12
STREAM, RENT = 'stream', 'rent'
def rent_or_stream(
renting_history: RentingHistory,
streaming_cost_per_month: int = STREAMING_COST_PER_MONTH
) -> Dict[str, str]:
"""Function that calculates if renting movies one by one is
cheaper than streaming movies by months.
Determine this PER MONTH for the movies in renting_history.
Return a dict of:
keys = months (YYYY-MM)
values = 'rent' or 'stream' based on what is cheaper
Check out the tests for examples.
"""
monthly_rent: Dict[str, List[int]] = defaultdict(list)
# Group rent prices by month
for movie in renting_history:
month = movie.date.strftime('%Y-%m')
monthly_rent[month].append(movie.price)
r_or_s: Dict[str, str] = {}
for month, rent in monthly_rent.items():
total_rent = sum(rent)
if total_rent > streaming_cost_per_month:
r_or_s[month] = STREAM
else:
r_or_s[month] = RENT
return r_or_s
| true |
7645c64b5daaf733f42c2258d1636ce262a514f8 | dcribb19/bitesofpy | /code_challenges/122/anagram.py | 579 | 4.34375 | 4 | def is_anagram(word1: str, word2: str):
"""Receives two words and returns True/False (boolean) if word2 is
an anagram of word1, ignore case and spacing.
About anagrams: https://en.wikipedia.org/wiki/Anagram"""
word1 = word1.lower().replace(' ', '')
word2 = word2.lower().replace(' ', '')
chars_1 = [char for char in word1]
chars_2 = [char for char in word2]
if (all(char in word2 for char in chars_1) and
all(char in word1 for char in chars_2) and
len(word1) == len(word2)):
return True
else:
return False
| true |
0d3685327150e7301742397b42d1d1f0d0db9ff6 | omnidark/python-project-lvl1 | /brain_games/games/progression.py | 1,525 | 4.1875 | 4 | """Progression game."""
from random import randrange
game_message = 'What number is missing in the progression?'
def get_progression(progression_len, progression_step, progression_start):
"""Return random progression and hide one random number.
Args:
progression_len (int): Len of pregression.
progression_step (int): Step between two numbers in progression.
progression_start (int): The number at which the progression starts.
Returns:
list: The random progression
int: Hided random number
"""
index = 0
progression = ['']
progression[index] = progression_start
target_number_index = randrange(0, progression_len)
while progression_len > index:
progression.insert(index + 1, progression[index] + progression_step)
if index == target_number_index:
target_number = progression[index]
progression[index] = '..'
index += 1
return progression, target_number
def progression_game():
"""Return progression game question and answer.
Returns:
str: Question - random pregression with customized params
str: Hided random number
"""
progression_limit = 11
p_len = randrange(5, progression_limit)
p_step = randrange(2, progression_limit)
progression = get_progression(p_len, p_step, randrange(1, 100))
question = ''
for element in progression[0]:
question = '{0} {1}'.format(question, element)
return question[1:], str(progression[1])
| true |
341e8c057ea09f71a3177a3861776deab7695ee6 | EunSe-o/Python | /practice 3/string_handling_function_1.py | 1,021 | 4.1875 | 4 | python = "Python is Amazing"
# lower() 전부 소문자 출력
print(python.lower())
# upper() 전부 대문자 출력
print(python.upper())
# isupper() 해당 문자가 대문자인지 출력
print(python[0].isupper())
# len(변수) 해당 변수 전체 문자열의 길이 출력
print(len(python))
# replace("찾고 싶은 문자", "바꿀 문자")
print(python.replace("Python", "Java"))
# index("문자") 해당 문자가 몇 번째에 있는지 출력
index = python.index("n")
print(index)
index = python.index("n", index + 1)
# 앞에서 찾은 위치의 다음(6)부터 찾음
print(index)
# find("문자") 해당 문자가 몇 번째에 있는지 출력
print(python.find("n"))
''' find 과 index 의 차이점
: find는 해당 문자가 변수에 없으면 -1 출력
print(python.find("Java")) # -1
: index는 해당 문자가 변수에 없으면 오류
print(python.index("Java")) # 오류
'''
# count("문자") 해당 문자가 변수 안에 몇 번 등장하는지 출력
print(python.count("n")) | false |
52eb69f8600ae925e889497678050d71112d0da0 | carlosramir991/HTML-and-CSS-Projects | /circumference.py | 401 | 4.4375 | 4 | def circumv():
radius = input("Please enter a numeric value for your radius:")
pi = 3.141
circumcalc(radius,pi)
def circumcalc(radius,pi):
try:
c = pi * 2 * int(radius)
print("The Circumference of your circle is: {}.".format(c))
except:
print("You need to enter a numeric value my dude.")
if __name__ == "__main__":
circumv()
| true |
1607803fde58883304aefc2879499b9a9bfcfe76 | carlosramir991/HTML-and-CSS-Projects | /AssignmentTA1.py | 1,034 | 4.25 | 4 | B = "Let's do some math!"
print(B)
X = 10
print("X=10")
print("X plus 5 equals:")
print(X+5)
A = 5
print("A=5")
print("A minus X equals:")
print(A-X)
print("X times A equals:")
print(X*A)
print("X divided by A equals:")
print(X/A)
print("Is X larger than A?:")
print(X>A)
print("Is X less than A?:")
print(X<A)
print("Are X and A equal?:")
print(X==A)
if X>A:
print("X (being 10) is large than A (which is 5)")
name = 'BILLY'
print(name)
print("Now it is time to print BILLY in all lower case letter: "+name.lower())
list_names=['Billy','Sally','Johnny','Raphael']
print("Here's the list we created: ")
print(list_names)
print("Here's the third name from the list we wrote in all caps " +list_names[2].upper())
date="July/14th/1987"
print("Here's the date we created: "+date)
split_date=date.split('/')
print("Here's the date we entered split apart:")
print(split_date)
another_name= 'DiAnE'
print("We chose the name: " +another_name)
print("Here's " + another_name+ " written with the cases swapped: " + another_name.swapcase())
| true |
607f965acb7408eb7b0c5b378ee87df48ed02101 | Lyu-lyu/lesson3 | /datah.py | 1,696 | 4.125 | 4 | # Напечатайте в консоль даты: вчера, сегодня, месяц назад
# Превратите строку "01/01/17 12:10:03.234567" в объект datetime
from datetime import datetime
from datetime import date, timedelta
from datetime import time
def month_days_amount(year, month):
# list of the days in months
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# to get index in list we minus 1
month_index = month - 1
month_days_for_counting = month_days[month_index]
# finding how many days february lasts
if month_index == 1:
# checking if it is a leap-year
if not (year % 4 != 0 or (year % 100 == 0 and year % 400 != 0)):
month_days_for_counting += 1
# returning 28 if it isn't a leap-year
return month_days_for_counting
now = datetime.now()
# this_month_days = number of days in current month
this_month_days = month_days_amount(now.year, now.month)
print('This month has {0} days'.format(this_month_days))
amount_of_days_delta = timedelta(days = this_month_days)
date_n_days_ago = now - amount_of_days_delta
print('Today is {0} month ago it was: {1}'.format(now, date_n_days_ago))
date_string = '01/01/17 12:10:03.234567'
# the second strftime defines the format date output
date_dt = (datetime.strptime(date_string, '%d/%m/%y %H:%M:%S.%f'))
print ('this date is {0}'.format(date_dt))
days_delta = timedelta(days = 1)
today = date.today()
yesterday = (today - days_delta)
day_ago = str(yesterday)
print('Today is {0}'.format(today))
day_ago = datetime.strptime(day_ago, '%Y-%m-%d')
print('yesterday was: {0}'.format(day_ago))
if name == "__main__" :
main()
| true |
2386f43dfc2de40bc5172c27e07ee832379407e5 | pmacinec/transactions-fraud-detection | /src/helpers.py | 461 | 4.28125 | 4 | def split_pascal_case_string(input_str):
"""
Split the string which is formatted in "PascalCase" to "Pascal Case"
:param input_str: a string to be splitted
:return: new string
"""
output_str = ""
for index, char in enumerate(input_str):
low_char = char.lower()
if low_char == char or not index:
output_str += char
else:
output_str += f" {char}"
return output_str | true |
302f91285ecf0509e423c1f235adf6e395dd4727 | vtsartas/ejpython | /ejpy/cursopildoras/practica_strings.py | 1,306 | 4.1875 | 4 | nomusu=input("Introduce tu nombre de usuario: ")
print("El nombre es: ", nomusu.upper())
print("El nombre es: ", nomusu.capitalize())
print("El nombre es: ", nomusu.lower())
edad=input("Introduce la edad: ")
while(edad.isdigit()==False):
edad=input("Introduce la edad: ")
if (int(edad)<18):
print("Menor de edad")
else:
print("Mayor de edad")
# hacer el ejercicio del vídeo 33
# Crea un programa que pida introducir una dirección de email por teclado.
# El programa debe imprimir en consola si la dirección de email es correcta o no
# en función de si esta tiene el símbolo ‘@’. Si tiene una ‘@’ la dirección será correcta.
# Si tiene más de una o ninguna ‘@’ la dirección será errónea. Si la ‘@’ está al comienzo
# de la dirección de email o al final, la dirección también será errónea,
# http://pyspanishdoc.sourceforge.net/lib/string-methods.html"""
correcto=False
while(correcto==False):
email=input("\nIntroduce tu email: ")
if (email.startswith("@")==False):
if (email.endswith("@")==False):
if (email.count("@")==1):
correcto=True
print("Tu email",email," es correcto")
break
print("La dirección introducida (",email,") no es correcta\nIntroduce otra.")
| false |
9c99be131da76a8c1c673b93f3d9387a3420119e | vtsartas/ejpython | /ejpy/ejercicios2/ejs/ejercicio3.py | 1,109 | 4.15625 | 4 | # 3. Programa que diga cuál es el mayor de tres enteros
def ejercicio3():
# iniciamos 'otro3' para que entre en el while
otro3="s"
while (otro3=="s"):
# pedimos el primer número
num1=int(input("Introduce el primer número: "))
num2=int(input("Introduce el segundo número: "))
while(num2==num1):
num2=int(input("ERROR: El número introducido es igual al primero. Introduce otro: "))
num3=int(input("Introduce el tercer número: "))
while(num3==num1 or num3==num2):
num3=int(input("ERROR: El número introducido es igual a uno de los anteriores. Introduce otro: "))
if (num1>num2 and num1>num3):
print("El primer número(",num1,") es mayor que",num2,"y",num3)
elif (num2>num3):
print("El segundo número(",num2,") es mayor que",num1,"y",num3)
else:
print("El tercer número(",num3,") es mayor que",num1,"y",num2)
# preguntamos si queremos comprobar otros tres números
otro3=str(input("¿Deseas comprobar otros tres números (s/n)? ")) | false |
ba677e65211827bf563b5793188e1173c980065f | gjoe344/python-learning | /variables.py | 1,939 | 4.53125 | 5 | # 1. comments - done by hashtags
"""
this is
a
multiline comment
"""
# 2. Printing
# String
print('My String')
# Integer
print(32)
# Float
print(1.111)
# Nesting functions
my_number = 10
values = type(my_number)
print(values)
# 3. Variables
# Integers, strings, booleans, Floats, Lists(array), Tuples, Objects
my_int = 20
print(type(my_int))
my_float = 20.222
print(type(my_float))
my_string = 'Jose is learning Python!'
print(type(my_string))
my_boolean = True # or False
print(my_boolean)
print(type(my_boolean))
my_list = [1,2,3,4,5]
my_list = [2, 3.44, 'Hey', True, [1,2,3]] #Dynamic, can contain a different variables
print(my_list)
print(type(my_list))
#Adding something into the list
variable = 'ME'
my_list.append(variable)
print(my_list)
print(type(my_list))
#Checking for length of an array
print(len(my_list))
#Indexing - retrieve Hey
print(my_list[2])
#Removing values from list
#Delete by indexing
my_list.pop(1)
print(my_list)
#Delete by value
my_list.remove('Hey')
print(my_list)
'''
Other things you can do with an array
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
'''
#Tuples
my_tuple = ('apple', 'orange', 'blueberry', 1, 1.22)
print(type(my_tuple))
print(my_tuple)
#check lenth of tuple
print(len(my_tuple))
#cannot add anything anymore after being defined
#Objects
#car = Car()
#print(type(car))
#my_list.append(car)
# End of Lesson | true |
05a91c8d89237cf94cf8d8ecc58e0d21f7e0bca2 | abhinavgunwant/hackerrank-solutions | /Domains/Python/12 - Python Functionals/Map and Lambda Function/solution.py | 338 | 4.15625 | 4 | cube = lambda x: x**3 # complete the lambda function
def fibonacci(n):
if n == 0:
return []
fib = []
fib.append(0)
num = 1
for i in range(n-1):
fib.append(num)
num += fib[-2]
return fib
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) | false |
ad73fd5255b27067e29a155b0a0ec47b99371abe | Geekfest-2021-Hackathon/chaos-engineering | /samples/hypothesis/functions.py | 921 | 4.125 | 4 | import math
import hypothesis
def get_sum_then_square_root(x: int, y: int):
"""
Performs the sum of x and y, then calculates the square root of the result
:param x: first int
:param y: second int
:return: None
"""
add = x + y
# --- Uncomment this block to fix the error hypothesis detects ---
# if add < 0:
# return None
result = math.sqrt(add)
return result
def not_kirby(s: str):
"""Returns True as long as the given text is not 'kirby'"""
# This will get printed only if Hypothesis finds a problem or is running in verbose
hypothesis.note(f"String received: {s}")
if len(s) < 5:
return True
if s[0] == "k":
if s[1] == "i":
if s[2] == "r":
if s[3] == "b":
if s[4] == "y":
raise ValueError("Kirby is not accepted by this function.")
return True
| true |
6a283ca5a998d71a2bf921d2996830a02a5c3b3b | Sputniza/sorting_algorithms | /sorting.py | 2,255 | 4.125 | 4 | # quick sort
def quicksort(items):
# set pivot to mid for minimizing encounter of worst case in partly sorted lists
if len(items) > 1:
pivot_index = len(items)/2
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
larger_items.append(val)
quicksort(smaller_items)
quicksort(larger_items)
items[:] = smaller_items + [items[pivot_index]] + larger_items
# merge sort
def mergesort(items):
if len(items) > 1:
# split lists
mid = len(items)/2
left = items [0:mid]
right = items [mid:]
# sort parts of list in place
mergesort(left)
mergesort(right)
# merging left and right list
l, r = 0, 0
for i in range(len(items)):
lval = left[l] if l < len(left) else None
rval = right[r] if r < len(right) else None
if (lval is not None and lval < rval) or rval is None:
items[i] = lval
l += 1
elif (rval is not None and lval >= rval) or lval is None:
items[i] = rval
r += 1
else:
raise Exception('Could not merge, sub arrays sizes do not match the main array')
# bubble sort
def bubblesort(items):
# implementation of bubble sort
for i in range(len(items)):
for j in range(len(items)-i-1):
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1],items[j] # swap items
return items
# insertion sort
def insertionsort(items):
for i in range(1, len(items)):
val = items[i]
j = i
while j > 0 and val < items[j-1]:
# swap
items[j], items[j-1] = items[j-1], items[j]
j -= 1
| true |
1898e349c6306e53399bfa690b511b354bca95ca | rt-jmoors/codewars | /moving_zeros_to_end.py | 824 | 4.34375 | 4 | """
Description:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
move_zeros([false,1,0,1,2,0,1,3,"a"]) # returns[false,1,1,2,1,3,"a",0,0]
"""
def move_zeros(array):
# your code here
zeroes = [x for x in array if x == 0 and x is not False]
non_zeroes = [x for x in array if x != 0 or x is False]
return non_zeroes + zeroes
def kata_move_zeros(arr):
# only extracts values that aren't 0, or are Boolean values (to keep the 'False' values)
l = [i for i in arr if isinstance(i, bool) or i != 0]
# returns everything removed, and appends a list of 0's to match the missing amounts removed
return l + [0] * (len(arr) - len(l))
move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"]) # should return [False,1,1,2,1,3,"a",0,0]
| true |
3db756251e7b3ef1569b1b7d83ce269161e80f8c | Miss-3278/learnPython3 | /ex19.py | 994 | 4.15625 | 4 | #! /urs/bin/env python
# coding=utf-8
# 可以直接给函数传递数字、变量、数学表达式,甚至数学表达式和变量合起来用
def cheeses_and_crackers(cheese_count, boxes_of_crackers):
print("You have %d cheeses!" % cheese_count)
print("You have %d boxes of crackers!" % boxes_of_crackers)
print("Man that's enough for a party!")
print("Get a blank.\n")
print("We can just give the function numbers directly:")
cheeses_and_crackers(20, 30) # 给变量的参数赋值,并且调用函数
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheeses_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheeses_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
cheeses_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
# 一个物件可以用=对其命名,通常也可以将其作为参数传递给一个函数
| true |
3054bfb67fd9baa35ac284d6b35bdfd1683b1ca6 | cs-fullstack-2019-spring/python-review3-cw-cierravereen24 | /classwork.py | 1,246 | 4.21875 | 4 | # Point of entry. The main function calls the problem functions within its scope.
def main():
problem1()
# problem2()
# problem3()
# Given a number n, return ```True``` if n is in the range 1..10, inclusive.
# Unless outside_mode is ```True```, in which case return True
# if the number is less or equal to 1, or greater or equal to 10.
# Print the result returned from your function
def problem1():
value = input("Enter a number")
print(in1to10(value, False))
print(in1to10(value, True))
print(in1to10(value, False))
def in1to10(n, galaxy):
for numbers in range(1,11):
if galaxy:
return n not in numbers
else:
return n in numbers
# Create a function that has a loop that quits with the equal sign.
# If the user doesn't enter the equal sign, ask them to input another string.
# Once the user enters the equal sign to quit,
# print all the strings that were entered as one line with each word separated by a comma and space.
def problem2():
exit = ""
# Given a non-negative number "num", return ```True``` if num is within ```2``` of a *multiple of 10*.
# Print the result from your function.
def problem3():
hjsj= ("")
if __name__ == '__main__':
main() | true |
89db912115232c3b513f77315d0bdd0e02980aa6 | educa2ucv/Guia-Rapida-Python | /Ejercicio-6.py | 591 | 4.125 | 4 | """
Ejercicio #6:
Escribir una función que calcule el área de un círculo
y otra que calcule el volumen de un cilindro usando
la primera función.
Área de un círculo: Ac = Pi * (radio**2)
Volumen de un cilindro: Aci = Pi * (radio**2) * h
"""
pi = 3.1416
def area_circulo(radio):
area = pi * (radio**2)
return area
def volumen_cilindro(radio, h):
volumen = area_circulo(radio) * h
return volumen
resultado_circulo = area_circulo(5)
resultado_cilindro = volumen_cilindro(10, 15)
print(resultado_circulo, resultado_cilindro)
| false |
a5e5a693c9a9c367c0ce3ad6d804d671e1fd61bc | Prasanna0708/forloop-task | /for.py | 665 | 4.8125 | 5 | # By using for loop how to print (0,10) values
#example1:
for x in range(0,10):
print(x)
#By using for loop print lists values
#example2:
print("By using for loop print lists values")
list_1 = [1,2,3,4,"prasanna","python",10.6,1,11]
for x in list_1:
print(x)
print("printing tuple values by using for loop")
tuples_1 = (1,2,3,"prasanna",5,6)
for x in tuples_1:
print(x)
print("printing sets by using For loop")
sets_1 = {1,2,3,4,5,6,7,7,8,9,10,10.5}
for x in sets_1:
print(x)
print("printing dictionaries by using for loop")
dictionary_1 = {1:"one",2:'Two',3:'Three',4:'Four'}
for x in dictionary_1:
print(x)
| true |
9a8cc95ed8b2e90153371d1f5c880069df9bbccf | riley-martine/projecteuler | /euler1-9/euler4.py | 399 | 4.125 | 4 | #!/usr/bin/env python
"""finds largest palindrome made of products of 2 3 digit numbers."""
def ispalindrome(num):
"""check if number is a palindrome."""
if str(num)[::-1] == str(num):
return True
return False
LARGEST = 0
for i in range(100, 999):
for n in range(100, 999):
if ispalindrome(n * i) and (n * i) > LARGEST:
LARGEST = (n * i)
print LARGEST
| false |
f617b369827a59bf0d1de6e51dba15589551d802 | charlyhackr/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 752 | 4.1875 | 4 | #!/usr/bin/python3
"""
Check if a set of integers are valid utf-8 format
data = [1,2,3 ..., n]
return True if all integers in list are valid utf-8 format
Otherwise False
"""
def validUTF8(data):
"""Check if a set of integers are valid utf-8 format"""
num_bytes = 0
for char_d in data:
byte = char_d & 0xff
if num_bytes:
if (byte >> 6 == 1 or byte >> 6 == 3):
return False
num_bytes -= 1
continue
while 7 - num_bytes and byte & (1 << (7 - num_bytes)):
num_bytes += 1
if num_bytes == 1 or num_bytes > 4:
return False
num_bytes = max(num_bytes - 1, 0)
if num_bytes:
return False
return True
| true |
f3a3eb114961bcbe9cb9ae8d361241965d3b2e70 | janobile/python-sql-exercises | /regex.py | 1,437 | 4.1875 | 4 | import re
str_list = [
"This is a technical test for applying to backend position. The solution must be developed in Java and published to a GitHub repository",
"What data structures and algorithms can be used for storing and filtering by pattern (or regex) a set of strings? Write the code using Java 8 functions and Stream API",
"Write a function that returns the count of distinct case-insensitive alphabetic characters and numeric digits occurring more than once in an input string. Example",
"Given the entity relationship diagram below, code SQL sentences for",
"Get all buses for 'Concessionaire 1'",
"Get all NVR devices for buses with type equal to 'Bi-articulado'",
"Summarize the quantity of devices by status (Active / Inactive) and bus motor(Diesel / Gas / Electric / Hybrid)",
"Design and code an API REST for accessing the resources in the above database",
"What HTTP endpoints and methods would you enable for creation, reading, modification and deletion?",
"hooHow can be a hierarchical access to enable the front-end for querying devices belonging to a specific bus?o",
"hTest the API REST and attach the evidence. Postman is suggested.ooo"]
# Search uppercase words
regex = r"\s([A-Z]*)\s"
def run(str_list=str_list, regex=regex ):
r = re.compile(regex)
filter_list = list(filter(r.search, str_list))
print(filter_list)
if __name__ == "__main__":
run() | true |
e7af189c62b87e15af6ee99b56d377998f6cecac | davelund750/sample_code | /get_divisors.py | 1,466 | 4.53125 | 5 | """
Accept a positive integer input and output divisors.
Usage:
Command line:
python question_two.py #int#
Importing to other modules:
from question_two import divisors
divisors(#int#)
Prompt:
Write a function that takes a single positive integer, and returns a
collection / sequence (e.g. array) of integers. The return value should
contain those integers that are positive divisors of the input integer.
Sample inputs Sample Outputs
============= ===============================================
60 {1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60}
42 {1, 2, 3, 6, 7, 14, 21, 42}
"""
import sys
def divisors(multiple):
"""Accept positive integer and return all positive divisors."""
multiple = eval_input(multiple)
divisors_list = list()
for divisor in range(1, multiple+1):
if not multiple % divisor:
divisors_list.append(divisor)
return divisors_list
def eval_input(multiple):
"""Evaluate the variable supplied."""
try:
multiple = int(multiple)
except ValueError:
multiple = 0
if multiple < 1:
raise AttributeError(
'Suppplied value is not an integer or is less than 1')
return multiple
def main(multiple):
"""Call divisors function."""
divisors_list = divisors(multiple)
print(divisors_list)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv[1])
| true |
fb1840c24a13b2c5a547dbc398cabdb74c888b48 | Ernest-Macharia/python | /exceptionhandling.py | 650 | 4.375 | 4 | #example 1
try:
x = 4/0
except Exception as e:
print(e)
#example 2
try:
sum = 0
file = open("numbers.txt","r")
for number in file:
sum = sum + 1/int(number)
print(sum)
except ZeroDivisionError:
print("number in file is equal to zero")
except IOError:
print("The file does not exist")
#throwing exceptions
a = 1
def RaiseError(a):
if type(a) != type("a"):
raise ValueError("This is not a string")
try:
RaiseError(a)
except ValueError as e:
print(e)
#using assert
def TestCase(a, b):
assert a < b, "a is greater than b"
try:
TestCase(3, 1)
except AssertionError as e:
print(e) | true |
e989089d5e3cfff0b1df86f31e4639b1f9997b2e | Michael-Zagon/ICS3U-Assignment-06-Python | /assignment6.py | 807 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Michael Zagon
# Created on: Oct 2021
# This program finds the perimeter of a hexagon
def perimeter_calculation(length):
# This function calculates the perimeter of a hexagon
perimeter = length * 6
return perimeter
def main():
# This function gets length from the user
length = input("Enter the length of one of the hexagons sides (cm): ")
try:
length = int(length)
# Call function
final_perimeter = perimeter_calculation(length)
print(
"\nThe perimeter of a hexagon with the side lengths of {0} cm is {1} cm.".format(
length, final_perimeter
)
)
except Exception:
print("\nInvalid Input.")
print("\nDone.")
if __name__ == "__main__":
main()
| true |
cae6658442f2a7d33f6d6878720d4c16be29eb64 | Callulis/PythonStuff | /GroupMaker/cryptoClasswork.py | 287 | 4.34375 | 4 | plaintext = raw_input("Enter a message!")
cipher = ""
pointer = len(plaintext)-1
#We iterate through ever character
#Of "plaintext" backwards and append
#Those characters to "cipher"
while(pointer >= 0):
cipher = cipher + plaintext[pointer]
pointer = pointer - 1
print cipher
| true |
4461304b6006b6664b14a4651ab8caec22a1f342 | Soyoung-Yoon/for_Python | /function_enumerate_ex1.py | 404 | 4.125 | 4 | # a에 enumerate를 적용하여 결과를 관찰하라
a = ['Korea', 'Maxico', 'USA']
b = list(enumerate(a))
print(b)
for idx, value in enumerate(a):
print(idx, value)
# name을 사용하여 다음과 같은 dict를 생성하라
# {100:'Kim', 101:'Park', 102:'Choi', 103:'Lee', 104:'Ann'}
name = ['Kim', 'Park', 'Choi', 'Lee', 'Ann']
b = dict(enumerate(name,100))
print(b)
| false |
043f4a35bcb80f35ebe70d56f860cfeefc35e047 | ksuarz/hundred-days | /text/piglatin.py | 815 | 4.21875 | 4 | #!/usr/bin/env python
'''
Converts words to pig latin. This is a very naive implementation. All
non-alphanumeric, non-whitespace characters are treated as part of a word.
'''
import sys
if len(sys.argv) < 2:
print 'Usage: piglatin.py [TEXT]'
else:
# First, build up our vowels and consonants
start, end = ord('a'), ord('z') + 1
vowels = 'aeiou'
consonants = [chr(i) for i in range(start, end) if chr(i) not in vowels]
# Now, do some text manipulation
text = ' '.join(sys.argv[1:]).lower().strip()
result = []
for word in text.split():
c = word[0]
if c in consonants:
result.append(word[1:] + '-' + c + 'ay')
elif c in vowels:
result.append(word + 'way')
else:
result.append(word)
print ' '.join(result)
| true |
2250896066eab0e44eebeff949c47ed99ca53744 | mkenane/Code_Guild_Labs | /lab_11_anagramdetector.py | 335 | 4.125 | 4 |
def anagramdetect(word1, word2):
letterSplit1 = sorted(list(word1.replace(' ', '').lower()))
letterSplit2 = sorted(list(word2.replace(' ', '').lower()))
if letterSplit1 == letterSplit2:
return ("these words are anagrams")
else:
return "words are not anagrams"
print(anagramdetect("Madam", "Radium came"))
| true |
d6d87c6e32ae36ec092a30389b1571e0e5885dbc | Sargazi77/Capstone_Project1 | /Week1.py | 1,467 | 4.3125 | 4 | from datetime import date
def main():
name = input('What is your name?')
name = name.upper() #converts the name to all uppercase
month = input('What is your birthday month?(type it in full format)')
new_month = month.title() # converts the month to first charector upper case to make the program not so user can enter all lower case
classes = input('what classes are you taking this semester? (seprate them by using ",") ')
splited = classes.split(',')
classes_list = []
for i in splited:
classes_list.append(i)
calculate = calculateMonth(name, new_month) # calls the calculateMonth function
print('You are taking these classes:')
for j in classes_list :
print(j)
def calculateMonth(name, new_month):
now = date.today()
text_month = now.strftime('%B') # %B gives the month of the full today date format
# converts the month to lower case to make the program not to be case sensetive
print('Welcome '+ name)
print('There are ' + str(len(name)) + ' letters in your name') # len() counts the number of letter and since python cannot put int and strings together we have to use str() function to convert the int to string
print('new month is '+ new_month)
print('new text month is '+ text_month)
if new_month == text_month:
print('Happy Birthday month!')
else:
print("Your birthday is in "+ new_month)
return text_month
main()
| true |
b4560177e5af728b18b343c271c59576eaef33ec | kimoba/Code-in-Place-2021 | /Extra Work/03 Parameters and Returning/Parameters/Print multiple/print_multiple.py | 423 | 4.3125 | 4 | def print_multiple(message, repeats):
# delete the pass statement below and write your code here!
# message to print that repeats x number of times
for i in range (repeats):
print(message)
def main():
message = input("Please type a message: ")
repeats = int(input("Enter a number of times to repeat your message: "))
print_multiple(message, repeats)
if __name__ == "__main__":
main()
| true |
de7460e39c2ea232bea2b572712d127e843ac183 | kimoba/Code-in-Place-2021 | /Section/Section 2 Welcome to Python/marsweight.py | 336 | 4.28125 | 4 | """
Prompts the user for a weight on Earth
and prints the equivalent weight on Mars.
"""
MARS_WEIGHT_MULTIPLER = 0.378
def main():
# asks user for their weight
weight = float(input("How much do you weigh? "))
print("You would weigh " + str(weight * MARS_WEIGHT_MULTIPLER) + " on Mars!")
if __name__ == "__main__":
main()
| false |
42c0c639cdaad954cc593232038aaf4fe71a7051 | kimoba/Code-in-Place-2021 | /Extra Work/03 Welcome to Python/Control flow (loops, expressions)/Tall enough to ride/tall_enough.py | 653 | 4.21875 | 4 | # define constant
MIN_HEIGHT = 50
def main():
# get user input for their height
user_height = input("How tall are you? ")
while user_height != "": # if the user enters 'nothing' the string will be empty, "" and the program will be done
user_height = float(user_height)
if user_height >= MIN_HEIGHT: # height check
print("You're tall enough to ride!") # if user height is >= min height
else:
print("Sorry, you're not tall enough to ride!") # if user height is < min height
user_height = input("How tall are you? ") # asks the question again
if __name__ == "__main__":
main()
| true |
f30c819e74f2682fb0aef124aa655f9daf5a6154 | kimoba/Code-in-Place-2021 | /Extra Work/03 Welcome to Python/Arithmetic operators, casting/Remainder division/remainder.py | 588 | 4.25 | 4 | def main():
# get number to be divided by from the user
dividend = int(input("Please enter an integer to be divided: "))
# get number to divide by from the user
divisor = (int(input("Please enter an integer to divide by: ")))
quotient = int(dividend / divisor)
remainder = dividend % divisor
# output
print("The result of this division is " + str(quotient) + " with a remainder of " + str(remainder))
# alternative output
# print(f"The result of this division is {quotient} with a remainder of {remainder}")
if __name__ == "__main__":
main()
| true |
de35f021cd6e7f8f2e3565b6f86bd25940da1d94 | kimoba/Code-in-Place-2021 | /Extra Work/03 Parameters and Returning/Return/Is even/is_even.py | 328 | 4.125 | 4 | def is_even(num):
# delete the pass statement below and write your code here!
if num % 2 == 0:
return True
def main():
num = int(input("Enter a number: "))
if is_even(num):
print("That number is even!")
else:
print("That number is not even!")
if __name__ == "__main__":
main()
| true |
6eaecf18af30f6d8ea0d415bfe5d24220ac800a9 | Athenian-ComputerScience-Fall2020/functions-practice-21lsparks | /multiplier.py | 814 | 4.375 | 4 | '''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the variable containing the result returned from the function.
'''
def multiplier(num1, num2):
return num1 * num2
if __name__ == '__main__':
num1 = 0
num2 = 0
while num1 == 0 or num2 == 0:
try:
num1 = int(input('Enter a number or live.'))
except:
print("Hahaha, sucka.")
try:
num2 = int(input("Enter a number or your dog will fart"))
except:
print("You are dumb.")
print(multiplier(num1, num2))
| true |
85dc75edfabed2882409f3b01abb8fc927248d8d | manncodes/automate-practical-files | /practicals/practical 2/p2_2.py | 242 | 4.3125 | 4 | # function that takes a list and prints number greater than 5
def print_greater_than_5(l):
for i in l:
if i > 5:
print(i, end=" ")
if __name__ == "__main__":
print_greater_than_5([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
| false |
442c014ad7f3c55e69d3225cd02a8ba90fca637f | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/050 Функция map/01 Что делает функция map.py | 545 | 4.15625 | 4 | # Функуия map применяется ко всем итерируемым обьектам в списке
# map (func , iterables) ---> map object
a =[-2,-3,-4,5]
b = map(abs,a)
# map object
print(b) # map object
b = list(map(abs,a))
print(b)
print('Циклом for')
a =[-2,-3,-4,5]
for i in a:
i =abs(i)
print(i,end=" ")
print()
print('Генератором')
# Генератор
a =[-2,-3,-4,5]
c =[abs(i) for i in a]
print(c)
# список превратили в строку
print('-'.join([str(i) for i in c])) | false |
cf8a19e2805c20ace0f9bf622da8370dd6c244e6 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/010 Строки Индексы и Срезы/Lesson 01 Строки Индексы и Срезы.py | 1,447 | 4.34375 | 4 | # ИНДЕКСЫ
d = 'hello world'
print(d)
print(d*2) # Задублировать символ, 3 Строки можно умножать на цыфры
print('Длинна строки',len(d),'Нулевой индексd',d[0],' последний',d[-1])
# Если нужно то с конца строки идут индексы итд -3-2-1 <---
print(d[-2])
# СРЕЗЫ
print(d[0:5]) # от начала до 5
print(d[0:]) # от начала до последнего
print(d[:4]) # до 4
print(d[1]) # второй индекс
print(d[:]) # Полностью всю строку
print(d[::2]) # Если хотим через один шаг равен 2
print(d[1::2])
print(d[::-1]) # НАОБОРОТ
print(d[2:8:3]) # Начало Конец и шаг 3 (hello world l пробел и до 7 потому что 8 не берем шаг 3
n = 'nikita chudnovskiy'
print(n[::-1])
print('{}, {:_^35}'.format(n, d)) # Объеденили методом format
n = 'Andrey'
print(n[0:])
print(n[-1])
print(len(n))
print(n[0:6])
# Изменить строку взять уже имеющийся срез и к нему добавить O b и берем уже срез с 1:6
n = 'Andrey'
n = n[0:0]+'Opana'+n[6:6] # На что меняем тут можно потренироватся поигратся значениями
print(n)
s='Hasta la vista, baby'
print(s[1::2])
print(s[1:8:3])
print(s[::-1])
| false |
f273c5bf9e7735e865cc8fe048993eb607aee947 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/039 Передача Аргументов/02 передача аргументов.py | 937 | 4.15625 | 4 | def f(a,b,c):
print(a,b,c, 'local')
# Варианты вызова этой функции
# 1 Позиционный
f(1,5,7)
# 2 По имени
f(b =10,c =20,a =5) # Не можем присваивать свои имена name =5
# 3 Комбинированный
f(2,b=10,c =20)
# Значение по умолчанию
def f(a='hi',b='Hello',c='Не известно'):
print(a,b,c,'local')
f() # Можем вызывать 0 параметров Значения присвоются по умолчанию
f(1) # Можем вызывать 1 параметр
f(2,3) # Можем вызывать 2 параметра
f(2,3,4) # Можем вызывать 3 параметра
print(max(1,2,3,4,99)) # Существует не огранич фунция
# key
#f(key =1,b=2,c=3) # Нельзя присваивать произвольные имена( в след занятии) | false |
2f3ab3d7082ada171108c6ffed4f1b74ccd12e51 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/035 Функции (def)/01 sayHello.py | 1,065 | 4.1875 | 4 |
# Функция это многократное используемые фрагменты программы
# Определение Функции всегда пишем вверху файла
def sayHello():
print('hi')
print('all')
print('World')
def square(x): # Сколько параметров передали столько и вводим в данном случае 1
print('Квадрат числа',x,'=',x**2)
def multiplay(a,b):
print('Результат умножения',a*b)
def even(a):
if a % 2 == 0:
print(a,'четное')
else:
print(a,'Не четное')
if 5 >1:
def primer():
print('hello')
else:
def primer():
print('HELLO')
#Главная программа
square(5)
square(10)
# В цикле for каждое число от 1 до 3 возводится в квадарат путем вызова square(i) со значением i - перебором
for i in range(1,10):
square(i)
for i in range(20,30):
even(i)
primer()
| false |
073640b74c5ea3cffe4440ad0880adc6ac45a994 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/Zadachi/06 Вывод/08 77 Лет.py | 598 | 4.125 | 4 | # Напишите программу, которая запрашивает имя пользователя и его возраст.
# Программа должна вывести на экран сообщение, содержащее имя пользователя и год,
# когда ему исполниться 77 лет.
#1 Геннадий
#1990
#Геннадий, вам исполнится 77 лет в 2067
name = input('Как Вас зовут ')
age= int(input('Какого года вы рождения '))
y = age+77
print("%s, Вам исполнится 77 лет в %s" %(name,y))
| false |
a83362701e4d377de14af7b33076bd4092083e65 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/03 Лекция Знакомство с Обьектами числа и Опрации над ними/02 Встроенные математические функии.py | 1,597 | 4.28125 | 4 | # ВСТРОЕННЫЕ МАТЕМАТИЧЕСКИЕ ФУНКЦИИ ПО РАБОТЕ С ЦЕЛЫМИ ЧИСЛАМИ
import math
from math import sqrt
print(abs(-7)) # отбрасывает знак
print(abs(-5 * 2)) # вначале выполнится действие потом отбросится знак
print(min(1, 2, 3, 4, 5))
print(max(1, 2, 3, 4, 5))
print(pow(2, 3)) # принимает 2 значения и возводит первое в степень второго
print(round(3.4)) # Округление по ум до целого числа
print(round(3.5))
print(round(3.456, 2)) # если хотим округлить по сотые то указываем 2
print(round(3.456, 1)) # по десятые , 1 число после ,
print(round(456, -1)) # Округление к 10
print(round(456, -2)) # Округление к 100
# Округление # math.ceil(),match.floor(), в большую и в меньшую
print(math.pi) # Точнность ограничивается вещественным числом в PYTHON
f = 25
print(sqrt(f), 'Корень')
print(math.factorial(f))
# ОПЕРАЦИИ НА МЕСТЕ
x = 2
x += 3;
print(x) # / - * / % Возможно с другими операциями
x *= 3;
print(x)
x **= 3;
print(x) # 15 в 3 степени
# Операции на месте могут применяться и к другим типам данных, например к строкам
x = 'spamm'
print(x)
x += 'egg'
print(x)
print(len(x)) # len() узнать длинну строки #
| false |
54f7559acb4167d56ffcb56749c1c9f785d62bb9 | marceloigor/ifpi-ads-algoritmos2020 | /Fabio02_condicional_B/7 aumento de salario.py | 1,642 | 4.28125 | 4 | """
7. As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe
contrataram para desenvolver o programa que calculará os reajustes. Escreva um algoritmo que leia o
salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
o salários até R$ 280,00 (incluindo) : aumento de 20%
o salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
o salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
o salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
· o salário antes do reajuste;
· o percentual de aumento aplicado;
· o valor do aumento;
· o novo salário, após o aumento.
"""
def main():
mensagem()
def mensagem():
salario = float(input('Digite seu salário: R$ '))
reajuste(salario)
def reajuste(salario):
if salario >= 1500.00:
porc = 5
elif salario >= 700.00:
porc = 10
elif salario >= 280.00:
porc = 15
elif salario > 0:
porc = 20
else:
print('Valor inválido!')
return mensagem()
aumento = calcular_porcento(salario, porc)
novo_salario = salario + aumento
print(f'\nValor do salário antes do reajuste: R$ {salario:.2f}')
print(f'Valor do percentual de aumento aplicado: {porc} %')
print(f'Valor do valor do aumento: R$ {aumento:.2f}')
print(f'Valor do novo salário, após o aumento: R$ {novo_salario:.2f}')
def calcular_porcento(salario, porc):
porcentual = porc / 100 * salario
return porcentual
main() | false |
e339ee6eaf221911d85ae4a56a1c8588380a1701 | marceloigor/ifpi-ads-algoritmos2020 | /Fabio02_condicional_A/20 quadrante.py | 712 | 4.34375 | 4 | """
20. Leia a medida de um ângulo (entre 0 e 360°) e escreva o quadrante (primeiro, segundo, terceiro ou
quarto) em que o ângulo se localiza.
"""
def main():
mensagem()
def quadrante(angulo):
if angulo >= 0 and angulo <= 90:
print('Primeiro quadrante')
elif angulo > 90 and angulo <= 180:
print('Segundo quadrante')
elif angulo > 180 and angulo <= 270:
print('Terceiro quadrante')
else:
print('Quarto quadrante')
def mensagem():
angulo = int(input('Digite o ângulo: '))
validar(angulo)
def validar(angulo):
if angulo >= 0 and angulo <= 360:
quadrante(angulo)
else:
mensagem()
main()
| false |
b2f261e26e035d3e08bcd841a5af32e67924137f | marceloigor/ifpi-ads-algoritmos2020 | /Fabio02_condicional_A/17 resto da divisao.py | 1,567 | 4.1875 | 4 | """
17. Leia valores inteiros em duas variáveis distintas e
se o resto da divisão da primeira pela segunda for 1 escreva a soma dessas variáveis mais o resto da divisão;
se for 2 escreva se o primeiro e o segundo valor são pares ou ímpares;
se for igual a 3 multiplique a soma dos valores lidos pelo primeiro;
se for igual a 4 divida a soma dos números lidos pelo segundo, se este for diferente de zero.
Em qualquer outra situação escreva o quadrado dos números lidos.
"""
def main():
valor_1 = int(input('Digite o 1º valor: '))
valor_2 = int(input('Digite o 2º valor: '))
soma = valor_1 + valor_2
resto = valor_1 % valor_2
print(f'Resto = {resto}')
if resto == 1:
print(f'A soma dessas variáveis mais o resto da divisão = {soma + resto}')
elif resto == 2:
impar_par(valor_1)
impar_par(valor_2)
elif resto == 3:
print(f'multiplicação da soma dos valores lidos pelo primeiro = {soma * valor_1}')
elif resto == 4:
divi = soma / valor_2
if divi == 0:
print(f'divisão da soma dos números lidos pelo segundo = {divi}')
else:
quadrado(valor_1)
quadrado(valor_2)
else:
quadrado(valor_1)
quadrado(valor_2)
def impar_par(numero):
if numero % 2 == 0:
print(f'{numero}É par')
else:
print(f'{numero}É impar')
def quadrado(valor):
quadrado_num = valor ** 2
print(f'O quadrado dos números lidos = {quadrado_num}')
main()
| false |
8bcf75a3885b6d0392d01f205cf61e80e656baeb | Rajasekharkonduru/python_assignments | /word_revers.py | 311 | 4.1875 | 4 | def rev(inpt):
s = inpt.split(" ") # spilts when " " found
s = s[::-1] # for reversing the words
s = " ".join(s) # joins the words
print(inpt)
print(s)
inpt = input("Enter a string:")
rev(inpt) # passing string as an argument
| true |
3810bd77afd472ca77a17b5ac6daa2d82c508933 | BrunoCodeman/tf2_keras_course | /numpy_arrays_index_selection.py | 1,066 | 4.1875 | 4 | import numpy as np
# Numpy arrays derived from other arrays
# are pointers to the original array
arr = np.arange(0,11)
# If it was a python normal list,
# arr and arr2 would be two different
# objects in memory. Here arr2 is a pointer to arr.
arr2 = arr[:]
# This is how we actually copy a numpy array to
# another object without pointing to the original one.
arr3 = arr.copy()
# These are broadcastings, also not possible with
# normal python arrays. Broadcast will obviously
# affect all the variables pointing to the array
arr[0:5] = 100
arr2[2:5] = 99
print(arr)
print(arr2)
print(arr3)
l1, l2, l3 = [1, 2, 3], [4, 5, 6], [7, 8, 9]
arr2d = np.array([ l1, l2, l3 ])
# The same as arr2d[1][2]
print(arr2d)
print(arr2d[1,2])
# gets all rows starting from row ONE of
# all columns up to (but not including) TWO
print(arr2d[:2,1:])
# returns an array with values True of False for
# each of the values in arr, according to the condition
bool_arr = arr < 99
# gets all the elements in arr
# that satisfy the conditions of bool_arr
print(arr[bool_arr])
| true |
815732da1c5ef3f0a19299f576b143dce73388c7 | rashmiiiiii/python-ws | /M4_Q/q1.py | 1,747 | 4.15625 | 4 | #single * for list
#duble ** for dictionary
'''1. Write a program to read the stock_price.csv file and perform the following operations:
• Convert Price to a numeric value (example: 1.02K = 1020)
• Display the names of the two companies – one whose stock value is maximum and the other whose stock value is minimum.
• Display the names of the companies whose stock value is within the price range that is input by the user.
'''
import csv
class Stock:
def __init__(self,name,symbol,exchange,price):
self.name = name
self.symbol = symbol
self.exchange = exchange
self.price = price
def __str__(self):
return f"{self.name} ,{self.symbol},{self.exchange},{self.price}"
def clean_init_get_stocks():
stock_lst = []
try:
with open("stock_price.csv","r") as f:
data = csv.reader(f,delimiter = ",")
h = True
for d in data:
if h:
h = False
continue
stock_lst.append(Stock(*d))
for s in stock_lst:
if "K" in s.price:
s.price = float(s.price.strip().replace("K"," "))* 1000
else:
s.price = float(s.price.strip())
except Exception as e:
print('{},val {!r}.format(e.args[0],e)')
return stock_lst
def show_stock_by_price(price):
st_lst = clean_init_get_stocks()
#logic find stock less tha n given price
f = filter(lambda x:x.price <= price,st_lst)
if f:
show_stock_info(list(f))
else:
print("no stock find for given price:{price}")
def show_stock_info(lst):
for s in lst:
print(s)
def max_min_stock_price():
st_lst = clean_init_get_stocks | true |
6ff686bf1e45a799b168b1cf980ec9d0870e8e81 | rashmiiiiii/python-ws | /M3_Q/car.py | 1,424 | 4.21875 | 4 | #object oriented concepts
#in pytho every superclass is object class
#self -keyword indicating the current object
class Car:
def __init__(self,regno,no_gears): #def __init__() constructor
self.regno = regno #instance variables
self.no_gears = no_gears
self.is_started = False
self.c_gear = 0
def start(self):
if self.is_started:
print(f"car with {self.regno} already started")
else:
print(f"car with {self.regno} started")
self.is_started = True
def stop(self):
if self.is_started:
print(f"car with regno:{self.regno} stopped")
self.is_started = False
else:
print(f"car with regno:{self.regno} stopped already")
def change_gear(self):
if self.is_started:
if self.c_gear < self.no_gears:
self.c_gear += 1
print(f"car with reg no:{self.regno} changed gear {self.c_gear} ")
else:
print(f"car with regno:{self.regno} already in top gear {self.c_gear} you can't change ")
else:
print(f"car with regno:{self.regno} already change the gear")
def showInfo(self):
print(f"the car {self.regno} is started:{self.is_started} no of gears:{self.no_gears} gear status:{self.c_gear}")
'''bmw = Car("KA013060",5)
bmw.start()
bmw.change_gear()'''
| true |
1a92f2d038288c7ae296f47fbfda2993e31597f7 | rashmiiiiii/python-ws | /M1_Q/fibonacci.py | 414 | 4.1875 | 4 | '''5. Write a program to print the Fibonacci series up to the number 34.
(Example: 0, 1, 1, 2, 3, 5, 8, 13, … The Fibonacci Series always starts with 0 and 1, the numbers that follow are arrived at by adding the 2 previous numbers.)'''
fib = 0
fib1 = 1
print(fib)
print(fib1)
for i in range (3,35):
fib3 = fib + fib1
fib = fib1
fib1 = fib3
print(fib3)
if fib3 == 34:
break
| true |
ae4eb77b75d125b17b5b666b24edb4122af4caf9 | rashmiiiiii/python-ws | /M1_Q/series2.py | 317 | 4.1875 | 4 | '''4. Write a program to accept a number “n” from the user; then display the sum of the following series:
1/23 + 1/33 + 1/43 + …… + 1/n3'''
'''program to print the series 1+1/2+....+1/n'''
n = int(input("enter the number:"))
sum = 0
for i in range (2, n+1):
sum = sum + (1/pow(i,3))
print(f"sum = {sum}")
| true |
b53678402ef6503883e5b77ffff14026130d0a8a | rakshsain20/ifelse | /raksha.py/manu.py | 558 | 4.125 | 4 | day=input("enter the day")
manu=input("enter the manu")
if day=="monday":
if manu=="breakfast":
print("pasta")
elif manu=="lunch":
print("roti sbji")
else:
print("dal chawal")
elif day=="tuseday":
if manu=="breakfast":
print("poha")
elif manu=="lunch":
print("dal bati churma")
else:
("fried rice")
elif day=="friday":
if manu=="breakfast":
print("uthpum")
elif manu=="lunch":
print("rice")
else:
print("roti sabji")
else:
print("roti sabji")
| false |
8c7cad2977c487969ca2ab5dea72257e6743b502 | rakshsain20/ifelse | /raksha.py/number.py | 223 | 4.125 | 4 | num=int(input("enter the number"))
if num=="1,2,34,45":
print("it is a string")
elif num=="1,2,45,67,78":
print("it is a int")
elif num=="34.9,3.4,12.7":
print("it is a float")
else:
print("it is a complex") | true |
0fc8f20eec0ef33df8e5f322f2a9c477aa70a0e9 | rakshsain20/ifelse | /raksha.py/smallest.py | 254 | 4.1875 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the number"))
if num1> num2 and num3>num2:
print("smallest",num2)
elif num2>num1 and num3>num1:
print("smallest",num1)
else:
print("smallest",num3) | false |
6ff8a9d32a29d2dce715c30776b0dfd0ab083e8b | zevgenia/Python_shultais | /Course/p_types/example_7.py | 497 | 4.125 | 4 | # TODO: временный файл - удалить
s = "программа"
s2 = 'продукт'
print(s)
print(s2)
# Использование служебных спецсимволов.
print("Программа 1\nПрограмма 2\nПрограмма 3\n\tЧасть 1\n\tЧасть 2")
print(len("12345\n"))
print("""Программа 1
Программа 2
Программа 3
Часть 1
Часть 2""")
print(r"Программа 1\nПрограмма 2") | false |
f0a7ad4c0ac69443ba8157b9c78d9174d956288c | pedrosimoes-programmer/exercicios-python | /exercicios-Python/ex017.py | 549 | 4.125 | 4 | #O quadrado da hipotenusa é igual a soma dos quadrados dos catetos
#forma 1
#from math import sqrt
#catOpos = float(input('Comprimento do cateto oposto: '))
#catAdja = float(input('Comprimento do cateto adjacente: '))
#hipotenusa = (catOpos**2) + (catAdja**2)
#print('A hipotenusa vai medir: {:.2f}'.format(sqrt(hipotenusa)))
#forma 2
from math import hypot
catOpos = float(input('Comprimento do cateto oposto: '))
catAdja = float(input('Comprimento do cateto adjacente: '))
print('A hipotenusa medirá: {:.2f}'.format(hypot(catOpos, catAdja)))
| false |
d2039a545d5310a21e6e99de5efe06195c655298 | vfiorucci/codewars | /square_number.py | 309 | 4.125 | 4 | """This application takes a number, breaks it down and squares each."""
def square(number):
"""Square a number."""
num_list = [number]
print(num_list)
for i in int(len(num_list)):
print(i)
print(num_list)
num = number**2
return num
number = square(22)
print(number)
| true |
949f11f322a00aee8fef8419ae28fee853e4acf0 | samuel-x/COMP30024-Watch-Your-Back | /Part B/Enums/PlayerColor.py | 949 | 4.15625 | 4 | from enum import Enum
class PlayerColor(Enum):
"""
Used to represent a player.
"""
_WHITE_REPRESENTATION = 'W'
_BLACK_REPRESENTATION = 'B'
# White player.
WHITE = 0
# Black player.
BLACK = 1
def get_representation(self):
"""
Returns the string representation for the piece. Expected use would be
for printing the board that the square (which has this piece) is a part
of.
"""
if (self == PlayerColor.WHITE):
return PlayerColor._WHITE_REPRESENTATION.value
if (self == PlayerColor.BLACK):
return PlayerColor._BLACK_REPRESENTATION.value
def opposite(self):
"""
Returns the opposite of the calling enum.
"""
if (self == PlayerColor.WHITE):
return PlayerColor.BLACK
elif (self == PlayerColor.BLACK):
return PlayerColor.WHITE
| true |
e4d41ffeb7e8c47cb80bcbcf672b5cda8531acf3 | alf808/python-labs | /07_classes_objects_methods/07_01_car.py | 849 | 4.5 | 4 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and demonstrate
changing the objects attributes.
'''
class Car:
"""class that models a car object"""
def __init__(self, model, year, max_speed):
self.model = model
self.year = year
self.max_speed = max_speed
def __str__(self):
return f"The car {self.year} {self.model} has max speed {self.max_speed}."
def accelerate(self):
"""increases speed by 5"""
self.max_speed += 5
toy = Car('Toyota', 1975, '45 mph')
maz = Car('Mazda', 2020, '37.2 mph')
print(toy)
print(maz)
| true |
a9cf373296018fc05fafed2554b981a21d298bac | alf808/python-labs | /03_more_datatypes/2_lists/03_11_split.py | 620 | 4.5 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
most_frequent_count = 0
most_frequent_word = ""
print("This application will give you the most frequent word in a string.")
temp = input("Please enter string: ")
string_list = temp.split()
for word in string_list:
temp_count = string_list.count(word)
if temp_count > most_frequent_count:
most_frequent_count = temp_count
most_frequent_word = word
print(f"The word with most occurences is \'{most_frequent_word}\'") | true |
e08cebbd002e68676720dff666b96c19558bcc8c | alf808/python-labs | /02_basic_datatypes/2_strings/02_09_vowel.py | 519 | 4.34375 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
print("This application will count the number of vowels.")
words = input("Please enter a string of words: ")
words = words.lower()
print(f"a: {words.count('a')}, e: {words.count('e')}, i: {words.count('i')}, o: {words.count('o')}, u: {words.count('u')}")
| true |
08dbe25d8be69d6773561ca21a2a66f13287e464 | saifhamdare/100daysofcodeinpython | /100daysofcodingchallege/day 1/day2.py | 514 | 4.1875 | 4 | # 🚨 Don't change the code below 👇
print("welcome to tip calculator")
bill = input("enter bill amount: ")
bill=float(bill)
# 🚨 Don't change the code above 👆
tip=input("enter the amount you want to tip 10 12 15: ")
tip=int(tip)
people=input("enter the no of people need to split in: ")
people=int(people)
####################################
#Write your code below this line 👇
tip=tip/100
tbill=bill*tip
bill=tbill+bill
lastbill=bill/people
lastbill=round(lastbill,2)
print(lastbill)
| true |
ad413395d485f249b1bc4db2aa0ba57713f33907 | mukund7296/Python-basic-to-advanced | /dict.py | 560 | 4.3125 | 4 | # Python Dictionary - Example Program
dictionary1 = {}
dictionary1['one'] = "This is one"
dictionary1[2] = "This is two"
smalldictionary = {'name': 'Devraj','id':9388, 'branch': 'cs'}
print(dictionary1[2]) # this will print the values for 2 key
print(dictionary1['one']) # this will print the value for 'one' key
print(smalldictionary) # this will print the complete dictionary
print(smalldictionary.keys()) # this will print all the keys
print(smalldictionary.values()) # this will print all the values | true |
68d81c2b757e33a0e689a3d60e38f9082206358a | ForsythT/School-Projects | /CS 160 - Computer Science Orientation/assign/assign3.py | 1,772 | 4.34375 | 4 | while True:
operation = input("Enter an operation you would like to use (+, -, *, /, //, %, **): ");
if str(operation) == "+" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to add to "+str(num1)+": "));
print(num1+num2);
elif str(operation) == "-" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to subtract from "+str(num1)+": "));
print(num1-num2);
elif str(operation) == "*" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to multiple "+str(num1)+" by: "));
print(num1*num2);
elif str(operation) == "/" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to divide "+str(num1)+" by: "));
print(num1/num2);
elif str(operation) == "//" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to divide "+str(num1)+" by: "));
print(num1//num2);
elif str(operation) == "%" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the number you would like to divide "+str(num1)+" by to find the remainder: "));
print(num1%num2);
elif str(operation) == "**" :
num1 = int(input("Enter your first number: "));
num2 = int(input("Enter the exponent: "));
print(num1**num2);
else :
print("Invalid operation. Please try again.");
continue
while True :
answer = input("Would you like to use the calculator again? Yes - y or No - n: ");
if answer in ("y", "n"):
break
print("Please enter 'y' for Yes or 'n' for No (case sensitive).");
if str(answer) == "y" :
continue
else :
print("Thanks for using this calculator. Good bye.");
break
| true |
23a21f5f51ee75a03fa9bcf30f316dc6ad2aa7b0 | L200170026/prak_asd_a | /mod2.no6.py | 1,245 | 4.1875 | 4 | ##NO.6
##Membuat kelas baru dengan nama Siswa
class Manusia(object):
"""class 'Manusia' dengan inisiasi 'nama'"""
keadaan = "lapar"
def __init__(self, nama):
self.nama = nama
def ucapkanSalam(self):
print("Salam, namaku ",self.nama)
def makan(self, s):
print("Saya baru saja makan ", s)
self.keadaan = 'kenyang'
def olahraga(self, k):
print("Saya baru saja latihan ", k)
self.keadaan = 'lapar'
def mengalikanDenganDua(self, n):
return n * 2
class Siswa(Manusia):
"""Class Siswa yang dibangun dari class Manusia"""
def __init__(self,nama,Nisn,kelas,alamat):
self.nama = nama
self.no = Nisn
self.kelas = kelas
self.alamat = alamat
def __str__(self):
a = "Nama : "+self.nama+'\n'+"No Induk : "+str(self.no)+'\n'+"Tinggal di : "+self.alamat+'\n'+"Kelas : "+str(self.kelas)
print (a)
def ambilNama(self):
print (self.nama)
def ambilNisn(self):
print (self.no)
def ambilKelas(self):
print (self.kelas)
def ambilAlamat(self):
print (self.alamat)
##Eksekusi program
a = Siswa("Jessica",10345 ,12 ,"Solo")
| false |
c63a1d5df63710ec4c7320a83dc82424022f7b86 | Helldragon666/curso-de-python | /09-listas -(arreglos)/metodos-predefinidos.py | 1,017 | 4.21875 | 4 |
cantantes = ['Drake', 'Bad Bunny', 'Rihanna', 'Shakira']
numeros = [1, 2, 5, 8, 3, 4]
# Ordenar
print(numeros)
numeros.sort()
print(numeros)
# Agregar elementos
cantantes.append('Juan Gabriel')
print(cantantes)
cantantes.insert(1, 'Julieta Venegas') # 'Drake', 'Julieta Venegas', 'Bad Bunny', 'Rihanna', 'Shakira', 'Juan Gabriel'
print(cantantes)
# Eliminar elementos
cantantes.pop(1) # 'Drake', 'Bad Bunny', 'Rihanna', 'Shakira', 'Juan Gabriel'
print(cantantes)
cantantes.remove('Drake') # 'Bad Bunny', 'Rihanna', 'Shakira', 'Juan Gabriel'
print(cantantes)
# Invertir lista
cantantes.reverse() # 'Juan Gabriel', 'Shakira', 'Rihanna', 'Bad Bunny'
print(cantantes)
# Buscar dentro de una lista
print('Juan Gabriel' in cantantes) # True
# Contar elementos
print(f'{str(len(cantantes))} cantantes') # 4
# Cuantas veces aparece un elemento en la lista
print(numeros.count(8)) # 1
# Obtener el índice de un elemento
print(cantantes.index('Bad Bunny')) # 3
# Unir listas
cantantes.extend(numeros) # 'Juan Gabriel', 'Shakira', 'Rihanna', 'Bad Bunny', 1, 2, 3, 4, 5, 8
print(cantantes) | false |
e91efa0187d47dfa14c0630f69e98abf0d57f1cc | lvolkmann/couch-to-coder-python-exercises | /Functions/shape_functions_FIXME.py | 686 | 4.125 | 4 | """
Write a program to calculate the circumference and area of a circle
Get input from the user defining the range of the values to calculate circumference and area for
Within function definitions:
Validate the input
Output the data for each int in that range in the following form
Shape: {}, Circumference: {} Area: {}
Shape: {}, Circumference: {} Area: {}
Output the number of function calls
Ask the user if they’d like to run the program again
"""
# imports
import math
# define functions
# define variables outside loop
run = True
aff_input = ["YEAH", "YES", "YEP", "Y"]
function_calls = 0
# main loop
while run:
pass # Delete this line when you fill in the main loop | true |
0912b622e8488cde9ee04f97ba2fd3b4dde772ee | lvolkmann/couch-to-coder-python-exercises | /Dictionaries/ballot_dict_practice_FIXME.py | 456 | 4.28125 | 4 | """
The program below randomly generates a list of votes.
You are tasked with counting these votes.
Create a dictionary to represent the election results {name: vote_count}
"""
import random
names = ["Tim from accounting", "David Schwimmer", "Colonel Sanders", "Colonel Mustard", "Santa Clause", "Mrs. Pacman", "Ruth"]
candidates = []
for name in names:
for x in range(random.randint(1,15)):
candidates.append(name)
random.shuffle(candidates)
votes = {}
# Your code here
print(votes)
| true |
f860b2aafd9d4eef959ccb14f7ff3ee7e46517f3 | lvolkmann/couch-to-coder-python-exercises | /Basic Input & Output/output_quiz_FIXME.py | 516 | 4.21875 | 4 | """
Print the following using the function print()
1. A single newline
2. 2 newlines using a single statement
3. The values "cat" and "dog" separated by a space
4. The values "cat" and "dog" without a space
5. The value "hello" that doesn't end in a newline
6. The value "hello" that ends with a "!" via the print()
7. The value "Now that's Italian" using single ticks
8. The integer 9 and the value "lives" separated by a space
9. The value found in the variable name
"""
# Test name for question 9
name = "Gregory" | true |
aa29916989cd1a07d989271e399545f20665ec63 | nsimms25/algorithmic_solutions_python | /compare_numbers.py | 505 | 4.21875 | 4 | '''
Two numbers entered by the user to compare.
print a statement depending on the comparison.
"The first number is larger"
"The second number is larger"
"Thw two numbers are equal"
'''
# Example input() statement
number = int(input('Please enter a number: '))
number2 = int(input('Please enter a number: '))
if(number > number2):
print('The first number is larger.')
if(number < number2):
print('The second number is larger.')
if (number == number2):
print('The two numbers are equal.')
| true |
2476965c57c4c3f70181fd19e609817c58702405 | nsimms25/algorithmic_solutions_python | /even_letter_capitalize.py | 432 | 4.34375 | 4 | '''
Capitalize the even numbered letters in a string given by a user.
Print the new capitalized string.
'''
# Get the string
s = input('Please enter a string: ')
s = str.lower(s)
new_s = ''
new_s = new_s + s[0]
for i in range(1,len(s)):
if(i % 2 == 1):
letter = s[i]
uppercase = str.upper(letter)
new_s = new_s + uppercase
else:
letter = s[i]
new_s = new_s + letter
print(new_s)
| true |
ceeea66a7d85506df66f6353761083ece1fbdc08 | HersheyChocode/Python---Summer-2018 | /translate.py | 2,269 | 4.34375 | 4 | def translate():#Defines Function
'''translate() -> None
Prompts user to enter dictionary files and input and output files
Changes words in input file according to the dictionary file
Write translation in output file'''
dictFileName = input('Enter name of dictionary: ')#Input name of dictionary
textFileName = input('Enter name of text file to translate: ')#Input name of text file
outputFileName = input('Enter name of output file: ' )#Input name of output file
translations = open(dictFileName,'r')#Opens, reads and saves dictFileName to variable "translations"
dictionary = {}#Makes an empty dictionary
for line in translations:#For each line in translations
line = line.replace('|', ' ')#Replace the vertical line with a space
line = line.split()#Split the line into different words
while len(line)>2:#While the line is longer than two words
line[1] = line[1]+' '+line[2]#The third word gets added to the second word
line.pop(2)#The third word gets removed
dictionary[line[0]] = line[1]#Dictionary adds a key(first word in line) and value(second word in line)
text = open(textFileName,'r')#Opens, reads, and saves textFileName to variable "text"
translatedText = open(outputFileName,'w')#Opens, reads, and saves outputFileName to variable "translatedText"
for line in text:#For each line in text
line = line.lower()#Convert everything to lowercase
line = line.split()#Split the line into words
for word in line:#For each word in the line
if word in dictionary:#If the word is in our dictionary
word = dictionary[word]#Changes word to the value of the word(in dictionary)
translatedText.write(word+' ')#Writes this word to translatedText, followed by a space for the next word
translatedText.write('\n')#Writes in a new line after finished with translating the current line
translatedText.close()#Closes the translatedText file
translations.close()#Closes the translations file
text.close()#Closes the text file
translate()#Calls the function
| true |
cc7658a876fca2ab0813c0cf28448df0a0e5a915 | HersheyChocode/Python---Summer-2018 | /printfibonacci.py | 397 | 4.34375 | 4 | # print the first n Fibonacci numbers
n = int(input("Enter a positive integer n: "))
firstNumber = 1
secondNumber = 1
print('1 1',end=' ')
for i in range(3,n+1):
currentNumber = firstNumber + secondNumber # computes the newest Fibonacci number
print(str(currentNumber),end=' ')
# move the two numbers one down the list
firstNumber = secondNumber
secondNumber = currentNumber
| true |
0ba1e957dd22ee3b7d51ead968558ef00c385b8b | yoelkana/Calculate-Bricks-Using-python | /main.py | 246 | 4.15625 | 4 | blocks = int(input("Enter the number of blocks: "))
number = 0
height = 0
while blocks > number:
blocks -= number
number += 1
if blocks < number:
break
else:
height += 1
print("The height of the pyramid:", height)
| true |
12fdc59ef7265db3c93cdc88182bb9d86f2f76af | gsarti/newscrapy | /newscrapy/run.py | 2,989 | 4.25 | 4 | """ Allows for quick article extraction in console """
import sys
from extractor import ExtractorException, LaRepubblicaExtractor
def choose_extractor(newspaper_name):
"""Factory method for choosing the right extractor.
Factory design pattern used to choose the correct extractor
to be used given the newspaper name.
Supported names in alphabetic order:
LaRepubblica (La Repubblica)
Parameters
----------
newspaper_name: str
The name of the newspaper from which we want to extract articles.
"""
if newspaper_name == 'LaRepubblica':
return LaRepubblicaExtractor()
return None
def run():
""" Script to perform article extraction """
arg_len = len(sys.argv)
if arg_len not in [6, 7, 9]:
print(
"""
Error: Insufficient number of arguments: %d.\n
Use one of the following syntaxes:
* To extract all articles from a newspaper for a specific day:
>> run.py filename newspaper_name day month year
* To extract all article in a specific archive page
of a newspaper for a specific day:
>> run.py filename newspaper_name day month year page_num
* To extract all articles from a newspaper between two dates:
>> run.py filename newspaper_name day month year day_end month_end year_end
With parameters:
* filename: The name of the file in which extracted articles will be saved.
* newspaper_name: The name of the newspaper.
Now supported: 'LaRepubblica'
* day: The day of extraction.
* month: The month of extraction.
* year: The year of extraction.
* page_num: The number of archive page.
* day_end: The last day of extraction.
* month_end: The last month of extraction.
* year: The last year of extraction.
""" % arg_len)
return
filename = sys.argv[1]
newspaper = sys.argv[2]
extractor = choose_extractor(newspaper)
if extractor is None:
raise ExtractorException('ExtractorException: Selected newspaper'
'is not supported (yet!)')
day = int(sys.argv[3])
month = int(sys.argv[4])
year = int(sys.argv[5])
if arg_len == 6:
extractor.extract_articles(day, month, year)
elif arg_len == 7:
page_num = int(sys.argv[6])
extractor.extract_articles(day, month, year, page_num=page_num)
elif arg_len == 9:
day_end = int(sys.argv[6])
month_end = int(sys.argv[7])
year_end = int(sys.argv[8])
extractor.extract_articles(day, month, year,
day_end=day_end, month_end=month_end, year_end=year_end)
extractor.articles_to_csv(filename)
print("The request was completed.")
if __name__ == '__main__':
run()
| true |
d028979aabb6a538203546641b94d8e969824083 | jorgerance/devops | /python/boo_cond.py | 899 | 4.125 | 4 | # Boolean conditional
# if True:
# print("True means do something")
# else:
# print("Not True means do something else")
# hot_tea = False
#
# if hot_tea:
# print("enjoy some hot tea!")
# else:
# print("enjoy some tea, and perhaps try hot tea next time.")
# someone_i_know = False
# if someone_i_know:
# print("how have you been?")
# else:
# # use pass if there is no need to execute code
# pass
# changed the value of someone_i_know
# someone_i_know = True
# if someone_i_know:
# print("how have you been?")
# else:
# pass
# sunny_today = True
# # [ ] test if it is sunny_today and give proper responses using if and else
# if sunny_today:
# print("Its sunny today!")
# else:
# pass
sunny_today = False
# [ ] use code you created above and test sunny_today = False
if sunny_today:
print("Its sunny today")
else:
print("Its cloudy today!")
| true |
5218385a7856b738dcb9fffe82d90b56ac5a6051 | jorgerance/devops | /python/bookstore.py | 1,198 | 4.125 | 4 | #
# [ ] get user input with prompt "what is the title?"
# [ ] call title_it() using input for the string argument
# [ ] define title_it_rtn() which returns a titled string instead of printing
# [ ] call title_it_rtn() using input for the string argument and print the result
#
# bookstore() takes 2 string arguments: book & price
# bookstore returns a string in sentence form
# bookstore() should call title_it_rtn() with book parameter
# gather input for book_entry and price_entry to use in calling bookstore()
# print the return value of bookstore()
# example of output:Title: The Adventures Of Sherlock Holmes, costs $12.99
#
# # [ ] create, call and test bookstore() function
def title_it_rtn(msg):
return msg.title()
def bookstore(book, price):
return "Title: " + title_it_rtn(book) + ", costs $" + price
# def short_rhyme():
# print("La la la!!")
# print("Do Re Mi")
# def title_it(msg):
# print(msg.title())
book_entry = input("Enter book name ")
price_entry = input("Enter price ")
x = bookstore(book_entry, price_entry)
print(x)
# user_in = input("what is the title ?")
#
# x = title_it_rtn(user_in)
#
# print(x)
# title_it(user_in)
#
# short_rhyme()
| true |
17ec644b00411e43a62be271f12fc3cf92894397 | krissielski/PythonClass | /Lessons/Lesson5.py | 1,088 | 4.28125 | 4 | #Lesson5 - Classes
#Visual Studio Code
#------------------
# Download from Ninite.com
# Extentions: Install Python
# Should ask to install PyLint: YES!
#
#Options: Ctrl-Shift-P
#WHY use classes?
# Code Organization
# Modularity
# Breaking down problem into simpiest form.
# Advanced Topics: NOT THIS COURSE
# Inheritance
# Polymorphism
class Time:
def __init__(self):
#Attributes
self.hour = 0
self.minute = 0
self.second = 0
#Class Method
def SetTime(self, h,m,s ):
self.hour = h
self.second = s
self.minute = m
def PrintTime(self):
print("The time is: ", self.hour,":", self.minute,":",self.second )
##### MAIN ######
timer1 = Time()
timer2 = Time()
timer1.SetTime(1,2,3)
timer2.SetTime(5,6,7)
timer1.PrintTime()
timer2.PrintTime()
#Homework:
# Write a Class "Student" with Attributes of Name, Grade, GPA
# Instanciate objects for each student in this class, assign values to attribues ("Setter Function")
# Then print each student object to console
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.