blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
660848ae5488cb9326331d9aa4ac4aab71d73632 | Kpsmile/Learn-Python | /Basic_Programming/ListsComprehension_basics.py | 951 | 4.125 | 4 | sentence='My Name is Kp Singh'
def eg_lc(sentence):
vowel='a,e,i,o,u'
return''.join(l for l in sentence if l not in vowel)
print"List comprehension is" + eg_lc(sentence)
"""square of only even numbers in the list
def square_map(arr):
return map(lambda x: x**2, arr)
print ["List comprehension i... | false |
832de19c8b9ab75f412d3f0ebc57f6791bc0d15f | Kpsmile/Learn-Python | /Basic_Programming/Collections.py | 1,580 | 4.53125 | 5 | a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that return... | true |
50febd52f27da540cc858944a37969ed932090c6 | surya-lights/Python_Cracks | /math.py | 293 | 4.15625 | 4 | # To find the highest or lowest value in an iteration
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
# To get the positive value of specified number using abs() function
x = abs(-98.3)
print(x)
# Return the value of 5 to the power of 4 is (same as 5*5*5*5):
x = pow(5, 4)
print(x)
| true |
f8bbfd6363010700b233934b7392629138d29e66 | sanazjamloo/algorithms | /mergeSort.py | 1,395 | 4.4375 | 4 | def merge_sort(list):
"""
Sorts a list in ascending order
Returns a new sorted List
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time... | true |
73631147ca4cc0322de2a68a36290502ee230907 | ytgeng99/algorithms | /Pythonfundamentals/FooAndBar.py | 1,040 | 4.25 | 4 | '''Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000.
For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither prin... | true |
44a002f5ed28792f31033331f79f49b24d6bc3ef | ytgeng99/algorithms | /Pythonfundamentals/TypeList.py | 1,320 | 4.375 | 4 | '''Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At t... | true |
c8bc084cc06c30404dbb8d5cd6653dd74d007405 | KatePavlovska/python-laboratory | /laboratory1&2update/Lab2_Task2_calculation_pavlovska_km_93.py | 640 | 4.25 | 4 | print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool... | true |
21a2fbe709284990b8d486f7aabd79ddc269d4bf | AlexChesser/CIT590 | /04-travellingsalesman/cities.py | 2,041 | 4.28125 | 4 | def read_cities(file_name)
"""Read in the cities from the given file_name, and return them as a list
of four-tuples: [(state, city, latitude, longitude), ...] Use this as your
initial road_map, that is, the cycle Alabama → Alaska → Arizona → ... → Wyoming → Alabama."""
pass
def print_cities(road_map... | true |
40db83e086d8857643c10447811873e55740797b | kajalubale/PythonTutorial | /While loop in python.py | 535 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
#... | true |
a991a9d07955fe00dad9a2b46fd32503121249e8 | kajalubale/PythonTutorial | /For loop in python.py | 1,891 | 4.71875 | 5 |
################### For Loop Tutorial ###############
# A List
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
# To print all elements in list
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can do same thing easily using for loop
# for ... | true |
2a3ca27dd93b4c29a43526fa2894f79f38280b82 | kajalubale/PythonTutorial | /41.join function.py | 971 | 4.34375 | 4 | # What is the join method in Python?
# "Join is a function in Python, that returns a string by joining the elements of an iterable,
# using a string or character of our choice."
# In the case of join function, the iterable can be a list, dictionary, set, tuple, or even a string itself.
# The string that separates... | true |
767fc168ca7b5c78be91f3aa94302fc009d73e49 | kajalubale/PythonTutorial | /35.Recursion.py | 1,457 | 4.5625 | 5 | # Recursion: Using Function inside the function, is known as recursion
def print_2(str):
print("This is",str)
print_2("kajal")
# output: This is kajal
# but if i used print_2("str") inside the function it shows Recursion error.
# def print_2(str):
# print_2(str)
# print("This is",str)
# print_2... | false |
060eb25956088487b27ab6fe31077f73b6691857 | mondler/leetcode | /codes_python/0006_ZigZag_Conversion.py | 1,866 | 4.15625 | 4 | # 6. ZigZag Conversion
# Medium
#
# 2362
#
# 5830
#
# Add to List
#
# Share
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by... | true |
4decf52cae21f429395dbb079c3bada56f7bf326 | basu-sanjana1619/python_projects | /gender_predictor.py | 683 | 4.21875 | 4 | #It is a fun program which will tell a user whether she is having a girl or a boy.
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate abov... | true |
9d77a0ee4b5f9d90d48c67fcc19a686f6cb3b508 | cookcodeblog/python_work | /ch07/visit_poll.py | 543 | 4.125 | 4 | # 7-10 Visit Poll
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place # It is like map.put(key, value)
repeat = input("Would you like to let another perso... | true |
2e1679facc189bf53edfc0c74160c0cecaa5b194 | cookcodeblog/python_work | /ch06/river.py | 316 | 4.25 | 4 | # 6-5 River
rivers = {
'Nile': 'Egypt',
'Changjiang': 'China',
'Ganges River': 'India'
}
for river, location in rivers.items():
print("The " + river + " runs through " + location + ".\n")
for river in rivers.keys():
print(river)
print()
for location in rivers.values():
print(location)
| false |
bdeab6a046d4236f6dd006dd5c44bdcdf62bf029 | amigojapan/amigojapan.github.io | /8_basics_of_programming/fruits.py | 580 | 4.71875 | 5 | fruits=["banana","apple","peach","pear"] # create a list
print(fruits[0]) # print first element of list
print(fruits[3]) # print last element
print("now reprinting all fruits")
for fruit in fruits: # loops thru the fruits list and assigns each values to th>
print(fruit) # prints current "iteration" of the fruit
pri... | true |
c087789647cad25fc983acd3bfceee19ab0a507f | Narfin/test_push | /controlFlows.py | 636 | 4.28125 | 4 | # if, elif, else
def pos_neg(n):
"""Prints whether int n is positive, negative, or zero."""
if n < 0:
print("Your number is Negative... But you already knew that.")
elif n > 0:
print("Your number is super positive! How nice.")
else:
print("Zero? Really? How boring.")
my_num =... | true |
e80688442c643ed05976d0b872cffb33b1c3c054 | Minashi/COP2510 | /Chapter 5/howMuchInsurance.py | 301 | 4.15625 | 4 | insurance_Factor = 0.80
def insurance_Calculator(cost):
insuranceCost = cost * insurance_Factor
return insuranceCost
print("What is the replacement cost of the building?")
replacementCost = float(input())
print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
| true |
0c404764a7b2a2921d926824e0a89883b560ab49 | cajimon04/Primer-Proyecto | /comer_helado.py | 1,403 | 4.28125 | 4 |
apetece_helado_input = input("¿Te apetece un helado? ¿Si/No?: ").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
apetece_helado = False
tienes_dinero_... | false |
039b84d58b8410e1017b71395ac44082e19323ec | milolou/pyscript | /stripMethod.py | 1,756 | 4.65625 | 5 | # Strip function.
'''import re
print('You can strip some characters by strip method,\n
just put the characters you want to strip in the parenthese\n
followed function strip')
print('Please input the text you wanna strip.')
text = input()
print('Please use the strip function.')
def strip(string):
preWhiteSpace = ... | true |
3a9572bd678ccbb324d12d945f3d19f4ae64619b | BenjiKCF/Codewars | /day197.py | 403 | 4.15625 | 4 | def valid_parentheses(string):
new_bracket = []
for i in string:
if i.isalpha():
pass
else:
new_bracket.append(i)
new_bracket = ''.join(new_bracket)
while '()' in new_bracket:
new_bracket = new_bracket.replace('()', '')
return new_bracket==''
print v... | false |
d00c5dd8c996aaed2784a30a925122bee2a4ac9d | rafaeljordaojardim/python- | /basics/exceptions.py | 1,891 | 4.25 | 4 | # try / Except / Else / Finally
for i in range(5):
try:
print(i / 0)
except ZeroDivisionError as e:
print(e, "---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 0)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is no... | true |
7521cbf4b76c785fe8d0b78e837fba5cdf41cce1 | evanlihou/msu-cse231 | /clock.py | 1,436 | 4.4375 | 4 | """
A clock class.
"""
class Time():
"""
A class to represent time
"""
def __init__(self, __hour=0, __min=0, __sec=0):
"""Constructs the time class.
Keyword Arguments:
__hour {int} -- hours of the time (default: {0})
__min {int} -- minutes of the time... | true |
f5d77a708522b6febacc4c1e43704d1c63a2d07d | evanlihou/msu-cse231 | /proj01.py | 1,123 | 4.3125 | 4 | ###########################################################
# Project #1
#
# Algorithm
# Prompt for rods (float)
# Run conversions to other units
# Print those conversions
###########################################################
# Constants
ROD = 5.0292 # meters
FURLONG = 40 # rods
MILE = 1609.34 # me... | true |
4fc1e7a055c830baa4ea154de82a4568a60b3bdf | alicevillar/python-lab-challenges | /conditionals/conditionals_exercise1.py | 1,058 | 4.46875 | 4 |
#######################################################################################################
# Conditionals - Lab Exercise 1
#
# Use the variable x as you write this program. x will represent a positive integer.
# Write a program that determines if x is between 0 and 25 or ... | true |
56870e9f3f322e09042d9e10312ed054fa033fa2 | rghosh96/projecteuler | /evenfib.py | 527 | 4.15625 | 4 |
#Define set of numbers to perform calculations on
userRange = input("Hello, how many numbers would you like to enter? ")
numbers = [0] * int(userRange)
#print(numbers)
numbers[0] = 0
numbers[1] = 1
x = numbers[0]
y = numbers[1]
i = 0
range = int(userRange)
#perform fibonacci, & use only even values; add sums
sum ... | true |
f87bafd4dbf5b69b9eda0f1baa5a87543b881998 | biniama/python-tutorial | /lesson4_list_tuple_dictionary/dictionary.py | 953 | 4.375 | 4 | def main():
# dictionary has a key and a value and use colon (:) in between
# this is a very powerful and useful data type
dictionary = {"Book": "is something to read"}
print(dictionary)
biniam_data = {
"name": "Biniam",
"age": 32,
"profession": "Senior Software Engineer",
... | false |
3c21bd12834e39d8fd1c53bb5d9885c2cc75a360 | biniama/python-tutorial | /lesson6_empty_checks_and_logical_operators/logical_operators.py | 490 | 4.1875 | 4 | def main():
students = ["Kidu", "Hareg"]
name = input("What is your name? ")
if name not in students:
print("You are not a student")
else:
print("You are a student")
# if name in students:
# print("You are a student")
# else:
# print("You are not a student")
... | true |
bac2a9c57de523788893acc83ddfb37a2e10ce0d | biniama/python-tutorial | /lesson2_comment_and_conditional_statements/conditional_if_example.py | 1,186 | 4.34375 | 4 | def main():
# Conditional Statements( if)
# Example:
# if kidu picks up her phone, then talk to her
# otherwise( else ) send her text message
# Can be written in Python as:
# if username is ‘kiduhareg’ and password is 123456, then go to home screen.
# else show error message
# Conditio... | true |
62ac86c00c6afcbb16dcc58a1a12bc426070001a | aiperi2021/pythonProject | /day_4/if_statement.py | 860 | 4.5 | 4 | # Using true vs false
is_Tuesday = True
is_Friday = True
is_Monday = False
is_Evening = True
is_Morning = False
if is_Monday:
print("I have python class")
else:
print("I dont have python class")
# try multiple condition
if is_Friday or is_Monday:
print("I have python class")
else:
print("I dont have p... | true |
f6c60e2110d21c44f230ec710f3b74631b772195 | aiperi2021/pythonProject | /day_7/dictionar.py | 298 | 4.3125 | 4 | # Mapping type
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
#create dict
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
for key in dict:
print(key, '->', dict[key]) | true |
00e3304a1b6216c18d5cd8fc9ea5c266ed72149e | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Project_pillow_tesseract_and_opencv_Mod5/Week2_Tesseract/ipywidgets_stuff.py | 2,172 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 19:49:51 2020
@author: Vasilis
"""
# In this brief lecture I want to introduce you to one of the more advanced features of the
# Jupyter notebook development environment called widgets. Sometimes you want
# to interact with a function you have created and call it mul... | true |
0229eae841f5fec0563ad643a508650a3b1b235c | nadiiia/cs-python | /extracting data with regex.py | 863 | 4.15625 | 4 | #Finding Numbers in a Haystack
#In this assignment you will read through and parse a file with text and numbers.
#You will extract all the numbers in the file and compute the sum of the numbers.
#Data Format
#The file contains much of the text from the introduction of the textbook except that random numbers are inser... | true |
59bb55684bffde3abd337b0617af2117a9e4abb4 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/FindAllAnagramsinaString.py | 2,464 | 4.1875 | 4 | # 438. Find All Anagrams in a String
# Easy
# 1221
# 90
# Favorite
# Share
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
# The order of output... | true |
795cbf40f98ad3a775af177e11913ce831752854 | MenacingManatee/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 504 | 4.21875 | 4 | #!/usr/bin/python3
'''Prints a string, adding two newlines after each of the following:
'.', '?', and ':'
Text must be a string'''
def text_indentation(text):
'''Usage: text_indentation(text)'''
if not isinstance(text, str):
raise TypeError('text must be a string')
flag = 0
for char in text:
... | true |
1ee074079729475b25368a84a39006e5306aec28 | MenacingManatee/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 571 | 4.375 | 4 | #!/usr/bin/python3
'''Adds two integers
If floats are sent, casts to int before adding'''
def add_integer(a, b=98):
'''Usage: add_integer(a, b=98)'''
if (a == float("inf") or (not isinstance(a, int) and not
isinstance(a, float)) or a != a):
raise TypeError('a must be a... | false |
d5d557f24d2e74375e95cf22f7df5d2ed5587e8c | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 321 | 4.3125 | 4 | #!/usr/bin/python3
'''Defines a function that appends a string to a text file (UTF8)
and returns the number of characters written:'''
def append_write(filename="", text=""):
'''Usage: append_write(filename="", text="")'''
with open(filename, "a") as f:
f.write(text)
f.close()
return len(text)... | true |
d91f8e862b939ab0131fab2bf97c96681fba005a | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 595 | 4.1875 | 4 | #!/usr/bin/python3
'''Defines a function that inserts a line of text to a file,
after each line containing a specific string'''
def append_after(filename="", search_string="", new_string=""):
'''Usage: append_after(filename="", search_string="", new_string="")'''
with open(filename, "r") as f:
res = ... | true |
faefe53c66424e822ce06109fc4d095f013e64c0 | MenacingManatee/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 1,442 | 4.40625 | 4 | #!/usr/bin/python3
'''Square class'''
class Square:
'''Defines a square class with logical operators available based on area,
as well as size and area'''
__size = 0
def area(self):
'''area getter'''
return (self.__size ** 2)
def __init__(self, size=0):
'''Initializes size'''... | true |
61a293256dff4c87004e8627f0afadd9a9d202ca | shea7073/More_Algorithm_Practice | /2stack_queue.py | 1,658 | 4.15625 | 4 | # Create queue using 2 stacks
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def pop(self):
return self.items.pop()
def push(self, item):
self.it... | true |
29436d6802295d6eb8992d2f510427219d29f35b | Mark9Mbugua/Genesis | /chatapp/server.py | 1,892 | 4.125 | 4 | import socket #helps us do stuff related to networking
import sys
import time
#end of imports ###
#initialization section
s = socket.socket()
host = socket.gethostname() #gets the local hostname of the device
print("Server will start on host:", host) #gets the name of my desktop/host of the whole connectio... | true |
80192a8c2357a805072936ccb99b9dabc8e27778 | GANESH0080/Python-WorkPlace | /ReadFilePractice/ReadDataOne.py | 291 | 4.25 | 4 | # Created an File
file = open("ReadFile.txt" ,"w+")
# Enter string into the file and stored into variable
file.write("Ganesh Salunkhe")
# Open the for for reading
file = open("ReadFile.txt" ,"r")
# Reading the file and store file date into variable
re= file.read()
# Printing file data
print(re)
| true |
de3cf5eec6681b391cddf58e4f48676b8e84e727 | KapsonLabs/CorePythonPlayGround | /Decorators/instances_as_decorators.py | 660 | 4.28125 | 4 | """
1. Python calls an instance's __call__()
when it's used as a decorator
2. __call__()'s return value is used as the
new function
3. Creates groups of callables that you can
dynamically control as a group
"""
class Trace:
def __init__(self):
self.enabled = True
def __call__(self, f):
def wr... | true |
ee9cf22dae8560c6ee899431805231a107b8f0e6 | smalbec/CSE115 | /conditionals.py | 1,110 | 4.4375 | 4 | # a and b is true if both a is true and b is true. Otherwise, it is false.
# a or b is true if either a is true or b is true. Otherwise, it is false.
#
# if morning and workday:
# wakeup()
#
# elif is when you need another conditional inside an if statement
def higher_lower(x):
if x<24:
... | true |
4c403bd4174b1b71461812f9926e6dac87df2610 | JasmanPall/Python-Projects | /lrgest of 3.py | 376 | 4.46875 | 4 | # This program finds the largest of 3 numbers
num1 = float(input(" ENTER NUMBER 1: "))
num2 = float(input(" ENTER NUMBER 2: "))
num3 = float(input(" ENTER NUMBER 3: "))
if num1>num2 and num1>num3:
print(" NUMBER 1 is the greatest")
elif num2>num1 and num2>num3:
print(" NUMBER 2 is the greates... | true |
c8b69c1728f104b4f308647cc72791e49d84e472 | JasmanPall/Python-Projects | /factors.py | 370 | 4.21875 | 4 | # This program prints the factors of user input number
num = int(input(" ENTER NUMBER: "))
print(" The factors of",num,"are: ")
def factors(num):
if num == 0:
print(" Zero has no factors")
else:
for loop in range(1,num+1):
if num % loop == 0:
factor = l... | true |
9718066d59cdbd0df8e277d5256fd4d7bb10d90c | JasmanPall/Python-Projects | /Swap variables.py | 290 | 4.25 | 4 | # This program swaps values of variables.
a=0
b=1
a=int(input("Enter a: "))
print(" Value of a is: ",a)
b=int(input("Enter b: "))
print(" Value of b is: ",b)
# Swap variable without temp variable
a,b=b,a
print(" \n Now Value of a is:",a)
print(" and Now Value of b is:",b) | true |
87dfe7f1d78920760c7e1b7131f1dd941e284e5a | JasmanPall/Python-Projects | /odd even + - 0.py | 557 | 4.375 | 4 | # This program checks whether number is positive or negative or zero
number=float(input(" Enter the variable u wanna check: "))
if number < 0:
print("THIS IS A NEGATIVE NUMBER")
elif number == 0:
print(" THE NUMBER IS ZERO")
else:
print(" THIS IS A POSITIVE NUMBER")
if number%2... | true |
17739c9ef743a4eea06fc2de43261bfc72c21678 | elijahwigmore/professional-workshop-project-include | /python/session-2/stringfunct.py | 1,612 | 4.21875 | 4 | string = "Hello World!"
#can extract individual characters using dereferencing (string[index])
#prints "H"
print string[0]
#prints "e"
print string[1]
#print string[2]
#Slicing
#of form foo[num1:num2] - extract all elements from and including num1, up to num2 (but not including element at num2)
... | true |
2244fcdea5ed252a02782ef5fb873fbb5c91b411 | lohitbadiger/interview_questions_python | /3_prime_number.py | 403 | 4.25 | 4 | # given number is prime or not
def prime_num_or_not(n):
if n>1:
for i in range(2,n):
if (n%i)==0:
print('given number is not prime')
print(i,"times",n//i,"is",n)
break
else:
print('given number is prime')
else:
print... | false |
84f0b4335f058c440ac748f165fd7e87ef1e08b2 | lohitbadiger/interview_questions_python | /6_letter_reverse.py | 724 | 4.1875 | 4 | #letters reverse in strings
def reverse_letters(string):
if len(string)==1:
return string
return reverse_letters(string[1:]) + (string[0])
# string=input('enter string')
string='lohit badiger'
print(reverse_letters(string))
print('----------------------------')
def reverse_letter2(string):
... | false |
50a3e1da1482569c0831227e0e4b5ead75433d43 | PatrickKalkman/pirplepython | /homework01/main.py | 1,872 | 4.59375 | 5 | """
Python Is Easy course @Pirple.com
Homework Assignment #1: Variables
Patrick Kalkman / patrick@simpletechture.nl
Details:
What's your favorite song?
Think of all the attributes that you could use to describe that song. That is:
all of it's details or "meta-data". These are attributes like "Artist",
"Year Released"... | true |
b884cc6e8e590ef59a9c3d69cad3b5d574368916 | Ardrake/PlayingWithPython | /string_revisited.py | 1,674 | 4.21875 | 4 | str1 = 'this is a sample string.'
print('original string>>', str1,'\n\n')
print('atfer usig capitalising>>',str1.capitalize())
#this prints two instances of 'is' because is in this as well
print('using count method for "is" in the given string>>', str1.count('is'))
print('\n\n')
print('looking fo specfic string lit... | true |
93f34502472cddeb27d9d3404fb0f4f5269bb920 | ladipoore/PythonClass | /hass4.py | 1,239 | 4.34375 | 4 | """ I won the grant for being the most awesome. This is how my reward is calculated.
My earnings start at $1 and can be doubled or tripled every month.
Doubling the amount can be applied every month and tripling the amount can be applied every other month.
Write a program to maximize payments given the number of month... | true |
0f7c3ae3ca9f584cdeb424c04b1f6b2a9a8317d5 | gitStudyToY/PythonStudy | / name_cases.py | 736 | 4.21875 | 4 | message = "Eric"
print("Hello " + message + ", would you like to learn some Python today?" )
print(message.title())
print(message.upper())
print(message.lower())
message = "Albert Einstein once said, 'A person who never made a mistake never tried anything new.'"
print(message)
famous_person = "Albert Einstein"
famou... | false |
aaf077c666e7c6d687e953d9b3e7d35596e7f430 | dxab/SOWP | /ex2_9.py | 427 | 4.5 | 4 | #Write a program that converts Celsius temperatures to Fahrenheit temp.
#The formula is as follows: f = 9 / 5 * C + 32
#This program should ask the user to enter a temp in Celsius and then
#display the temp converted to Fahrenheit
celsius = float(input('Please enter todays temperature (in celsius): '))
fahr = 9 / 5 *... | true |
fe0ed51cf0cdab74d7d87b9f8317e18776d0c27d | ostanleigh/csvSwissArmyTools | /dynamicDictionariesFromCSV.py | 2,363 | 4.25 | 4 | import csv
import json
from os import path
print("This script is designed to create a list of dictionaries from a CSV File.")
print("This script assumes you can meet the following requirements to run:")
print(" 1) The file you are working with has clearly defined headers.")
print(" 2) You can review the headers ('.h... | true |
89ec0897f99163edb014c185425b3054332f6dbe | RamyaRaj14/assignment5 | /max1.py | 258 | 4.25 | 4 | #function to find max of 2 numbers
def maximum(num1, num2):
if num1 >= num2:
return num1
else:
return num2
n1 = int(input("Enter the number:"))
n2 = int(input("Enter the number:"))
print(maximum(n1,n2)) | true |
f8ec2566b82d611fe6e8ae0ecff036978de9a002 | ayaabdraboh/python | /lap1/shapearea.py | 454 | 4.125 | 4 | def calculate(a,c,b=0):
if c=='t':
area=0.5*a*b
elif c=='c':
area=3.14*a*a
elif c=='s':
area=a*a
elif c=='r':
area=a*b
return area
if __name__ == '__main__':
print("if you want to calculate area of shape input char from below")
... | true |
ef3f6373867dbacee7aae3af141d9fcd1edbd311 | PabloG6/COMSCI00 | /Lab4/get_next_date_extra_credit.py | 884 | 4.28125 | 4 | from datetime import datetime
from datetime import timedelta
'''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward)
would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because
28 is not a month.
'''
def GetNextDate(day, month, year, num_days_forward):
num_days_forward = int... | true |
af817ff14fbc1b00968c49da3f427ddb3d75622d | PabloG6/COMSCI00 | /Lab2/moon_earths_moon.py | 279 | 4.125 | 4 | first_name = input("What is your first name?")
last_name = input("What is your last name?")
weight = int(input("What is your weight?"))
moon_gravity= 0.17
moon_weight = weight*moon_gravity
print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon") | true |
683ce144348dbb8d1f15f38ada690d70e9b1a22f | joeschweitzer/board-game-buddy | /src/python/bgb/move/move.py | 827 | 4.3125 | 4 |
class Move:
"""A single move in a game
Attributes:
player -- Player making the move
piece -- Piece being moved
space -- Space to which piece is being moved
"""
def __init__(self, player, piece, space):
self.player = player
self.piece = piece
self.space =... | true |
2b0293a0bd0452e9e94a7c6aea0d13a803cc9dbd | Demesaikiran/MyCaptainAI | /Fibonacci.py | 480 | 4.21875 | 4 | def fibonacci(r, a, b):
if r == 0:
return
else:
print("{0} {1}".format(a, b), end = ' ')
r -= 1
fibonacci(r, a+b, a+ 2*b)
return
if __name__ == "__main__":
num = int(input("Enter the number of fibonacci series you want: "))
if num =... | true |
bb50b8feabc4e027222ed347042d5cefdf0e64da | abtripathi/data_structures_and_algorithms | /problems_and_solutions/arrays/Duplicate-Number_solution.py | 1,449 | 4.15625 | 4 | # Solution
'''
Notice carefully that
1. All the elements of the array are always non-negative
2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2)
3. There is only SINGLE element which is present twice.
Therefore let's find the sum of all elements (current_sum) of... | true |
26d6e211c524aae3668176e7f54638f589b9226c | nicholasrokosz/python-crash-course | /Ch. 15/random_walk.py | 945 | 4.25 | 4 | from random import choice
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
self.num_points = num_points
# Walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in a walk.""... | true |
6405fb18f932d4ef96807f2dc65b04401f32e5be | nicholasrokosz/python-crash-course | /Ch. 10/favorite_number.py | 467 | 4.125 | 4 | import json
def get_fav_num():
"""Asks a user for their favorite number and stores the value in a .json file."""
fav_num = input("What is your favorite number? ")
filename = 'fav_num.json'
with open(filename, 'w') as f:
json.dump(fav_num, f)
def print_fav_num():
"""Retrieves user's favoite number and prints ... | true |
da5a646c0a2caecadb60485bf3d02d8c0661960b | nicholasrokosz/python-crash-course | /Ch. 8/user_albums.py | 572 | 4.25 | 4 | def make_album(artist, album, no_of_songs=None):
album_info = {'artist': artist, 'album': album}
if no_of_songs:
album_info['no_of_songs'] = no_of_songs
return album_info
while True:
artist_name = input("Enter the artist's name: ")
album_title = input("Enter the album title: ")
no_of_songs = input("Enter the n... | true |
af5ab9aad7b047b9e9d061e22ab7afe7e64a4b01 | mumarkhan999/UdacityPythonCoursePracticeFiles | /9_exponestial.py | 347 | 4.5 | 4 | #claculating power of a number
#this can be done easily by using ** operator
#for example 2 ** 3 = 8
print("Assuming that both number and power will be +ve\n")
num = int(input("Enter a number:\n"))
power = int(input("Enter power:\n"))
result = num
for i in range(1,power):
result = result * num
print(result)
input("... | true |
a6fc7a95a15f7c98ff59850c70a05fdb028a784f | mumarkhan999/UdacityPythonCoursePracticeFiles | /8_multi_mulTable.py | 208 | 4.25 | 4 | #printing multiple multiplication table
num = int(input("Enter a number:\n"))
for i in range (1, (num+1)):
print("Multiplication Table of",i)
for j in range(1,11):
print(i,"x",j,"=",i*j)
| true |
162b0739cda0d6fba65049b474bc72fecf547f3d | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week4/assignment/problem_4.py | 2,492 | 4.21875 | 4 | # Uses python3
"""How close a data is to being sorted
An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n
such that ai < aj. The number of inversion of a sequence in some sense measures
how close the sequence is to being sorted. For example, a sorted (in non-decreasing
order) sequence contains n... | true |
8c41e6813d5e137bf3acbe883b08d269d9cb7d7b | Smellly/weighted_training | /BinaryTree.py | 1,813 | 4.25 | 4 | # simple binary tree
# in this implementation, a node is inserted between an existing node and the root
import sys
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(s... | true |
a5f8cf2de38a252d3e9c9510368419e5a763cf74 | TheFibonacciEffect/interviewer-hell | /squares/odds.py | 1,215 | 4.28125 | 4 | """
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them,... | true |
959fc6191262d8026e7825e50d80eddb08d6a609 | OliValur/Forritunar-fangi-1 | /20agust.py | 2,173 | 4.28125 | 4 | import math
# m_str = input('Input m: ') # do not change this line
# # change m_str to a float
# # remember you need c
# # e =
# m_float = float(m_str)
# c = 300000000**2
# e = m_float*c
# print("e =", e) # do not change this line)
# Einstein's famous equation states that the energy in an object at rest equals i... | true |
0837151d119a5496b00d63ae431b891e405d11cb | Shubham1744/Python_Basics_To_Advance | /Divide/Prog1.py | 249 | 4.15625 | 4 | #Program to divide two numbers
def Divide(No1,No2):
if No2 == 0 :
return -1
return No1/No2;
No1 = float(input("Enter First Number :"))
No2 = float(input("Enter Second Number :"))
iAns = Divide(No1,No2)
print("Division is :",iAns);
| true |
b57b724347cc8429c3178723de6182e741940b16 | DarioDistaso/senai | /logica_de_programação/sa4etapa1.py | 1,614 | 4.15625 | 4 | #Disciplina: [Logica de Programacao]
#Professor: Lucas Naspolini Ribeiro
#Descricao: SA 4 - Etapa 1: PILHA
#Autor: Dario Distaso
#Data atual: 06/03/2021
pilha = []
def empilhar(): # opção 1
if len(pilha) < 20:
produto = str(input("Digite o produto: ")).strip()
pilha.append(produto)
print(... | false |
c35d93f5359f710db0bb6d3db7f4c8af1724b1e9 | umberahmed/hangman- | /index.py | 586 | 4.25 | 4 | # This program will run the game hangman
# random module will be used to generate random word from words list
import random
# list of words to use in game
list_of_words = ["chicken", "apple", "juice", "carrot", "hangman", "program", "success", "hackbright"]
# display dashes for player to see how many letters are in... | true |
191b74137d4b0636cbf401c865279f8c33ef69b0 | zyavuz610/learnPython_inKTU | /python-100/104_numbers_casting.py | 1,147 | 4.46875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Python 100 - Python ile programlamaya giriş
Python 101 - Python ile Ekrana Çıktı Yazmak, print() fonksiyonu
Python 102 - Değişkenler ve Veri Türleri
Python 103 - Aritmetik operatörler ve not ortalaması bulma örneği
Python 104 - Sayılar, bool ifadeler ve tür dönüşüm... | false |
d9dd950f5a7dd35e1def63114c2f65ad6c2fb3da | zyavuz610/learnPython_inKTU | /python-100/113_while-loop.py | 1,322 | 4.28125 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
python-113: while döngüsü, 1-10 arası çift sayılar, döngü içinde console programı yazmak
Döngüler, programlamada tekrarlı ifadeleri oluşturmak için kullanılır.
türleri
for
while
döngülerin bileşenleri: 4 adet döngü bileşeni
1. başlangıç
2. bitiş (döngüye devam... | false |
db985b8f58b3c1ba64a29f48c8b1c1620a22629f | zyavuz610/learnPython_inKTU | /python-100/131_set-intro.py | 1,266 | 4.21875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
döngüler: for, while, iç içe döngüler
fonksiyonlar, modüller
veri yapıları:
string,
list,
tuple
...
set *
dict
Python - 131 : Set (Küme) Veri Yapısı
Set(s... | false |
a462d5adc2feb9f2658701a8c2035c231595f81e | kristinejosami/first-git-project | /python/numberguessing_challenge.py | 911 | 4.3125 | 4 | '''
Create a program that:
Chooses a number between 1 to 100
Takes a users guess and tells them if they are correct or not
Bonus: Tell the user if their guess was lower or higher than the computer's number
'''
print('Number Guessing Challenge')
guess=int(input('This is a number guessing Challenge. Please enter your ... | true |
c1fe260237f4a694c49c6191271a3d5870241e6f | pawan9489/PythonTraining | /Chapter-3/3.Scopes_1.py | 1,353 | 4.625 | 5 | # Local and Global Scope
# Global variable - Variables declared outside of Every Function
# Local variable - Variables declared inside of a Function
g = 0 # Global Variable
def func():
i = 30 # Local Variable
print("From Inside Func() - i = ", i)
print("From Inside Func() - g = ", g)
print('---- Global Var... | false |
b9310befbc4a399a8c239f22a1bc06f7286fedee | pawan9489/PythonTraining | /Chapter-2/4.Sets.py | 1,504 | 4.375 | 4 | # Set is a collection which is unordered and unindexed. No duplicate members.
fruits = {'apple', 'banana', 'apple', 'cherry'}
print(type(fruits))
print(fruits)
print()
# Set Constructor
# set() - empty set
# set(iterable) - New set initialized with iterable items
s = set([1,2,3,2,1])
print(s)
print()
# No Indexing - ... | true |
ea4f3b0a569bcc2fd312286f4d44383a2ef6729a | pawan9489/PythonTraining | /Chapter-4/1.Classes_Objects.py | 1,641 | 4.21875 | 4 | '''
Class Like Structures in Functional Style:
Tuple
Dictionary
Named Tuple
Classes
'''
d = dict(
name = 'John',
age = 29
)
print('- Normal Dictionary -')
print(d)
# Class Analogy
def createPerson(_name, _age):
return dict(
name = _name,
age = _age
)
pr... | false |
ca7b96d6389b50e8637507cce32274991e792144 | SK7here/learning-challenge-season-2 | /Kailash_Work/Other_Programs/Sets.py | 1,360 | 4.25 | 4 | #Sets remove duplicates
Text = input("Enter a statement(with some redundant words of same case)")
#Splitting the statement into individual words and removing redundant words
Text = (set(Text.split()))
print(Text)
#Creating 2 sets
print("\nCreating 2 sets")
a = set(["Jake", "John", "Eric"])
print("Set 1 ... | true |
0164661e3480ce4df1f2140c07034b3bb75a6c3b | SK7here/learning-challenge-season-2 | /Kailash_Work/Arithmetic/Calculator.py | 1,779 | 4.125 | 4 | #This function adds two numbers
def add(x , y):
return x + y
#This function subtracts two numbers
def sub(x , y):
return x - y
#This function multiplies two numbers
def mul(x , y):
return x * y
#This function divides two numbers
def div(x , y):
return x / y
#Flag variable used for ca... | true |
7337c033becfb2c6c22daa18f54df4141ff804ac | kittytian/learningfishcpy3 | /33.3.py | 1,904 | 4.5 | 4 | '''
2. 尝试一个新的函数 int_input(),当用户输入整数的时候正常返回,否则提示出错并要求重新输入。%
程序实现如图:
请教1:
int_input("请输入一个整数:") 这一句括号里的即是一个形参又是一个输入?为什么?
这一句的括号里不是形参,是实参,传递给了int_input函数
它并不是一个输入,能够作为输入是因为int_input函数中调用了input函数,才有了输入的功能
请教2:
def int_input(prompt=''): 这里的我用(prompt)和(prompt='')的结果是一样的,他们有区别吗?如果是(prompt='')的话是什么意思?
第一种(prompt)并... | false |
bb253f977f19bc69c71741e10e2d9f6be1191eea | kittytian/learningfishcpy3 | /16.4.py | 642 | 4.21875 | 4 | '''
哎呀呀,现在的小屁孩太调皮了,邻居家的孩子淘气,把小甲鱼刚写好的代码画了个图案,
麻烦各位鱼油恢复下啊,另外这家伙画的是神马吗?怎么那么眼熟啊!??
自己写的时候注意点 循环 还有判断!!一定要细心 会写
'''
name = input('请输入待查找的用户名:')
score = [['米兔', 85], ['黑夜', 80], ['小布丁', 65], ['娃娃', 95], ['意境', 90]]
flag = False
for each in score:#遍历
if name in each:
print(name + '的得分是:', each[1])
flag = ... | false |
33d0681848619697f3236def10951be9751c43ce | kittytian/learningfishcpy3 | /17.0.py | 498 | 4.53125 | 5 | '''
编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值
递归(22课课后题0))和非递归法
def power(x, y):
return x ** y
print(power(2,3))
看了答案发现 人家的意思是不用**幂函数
'''
'''
def power(x, y):
result = 1
for i in range(y):
result *= x
return result
print(power(2, 3))
'''
def power(x,y):
if y:
ret... | false |
4e8b2c18ebf0d7793c7be7dc2830842f26535ab1 | githubfun/LPTHW | /PythonTheHardWay/ex14-ec.py | 1,061 | 4.25 | 4 | # Modified for Exercise 14 Extra Credit:
# - Change the 'prompt' to something else.
# - Add another argument and use it.
from sys import argv
script, user_name, company_name = argv
prompt = 'Please answer: '
print "Hi %s from %s! I'm the %s script." % (user_name, company_name, script)
print "I'd like to ask you a few... | true |
c8176ae9af68ecc082863620472e9fe440300668 | githubfun/LPTHW | /PythonTheHardWay/ex03.py | 1,688 | 4.1875 | 4 | # The first line of executable code prints a statment (the stuff contained between the quotes) to the screen.
print "I will now count my chickens:"
# Next we print the word "Hens" followed by a space, then the result of the formula, which is analyzed 25 + (30 / 6)
print "Hens", 25 + 30 / 6
# Line 7 prints right below ... | true |
e12728b653a685aba01bf66f0b89f2d31f8b0c6d | Flor91/Data-Science | /Code/3-numpy/np_vectorizacion.py | 1,143 | 4.25 | 4 | """
1) Generemos un array de 1 dimension con 1000 elementos con distribución normal de media 5 y desvío 2, inicialicemos la semilla en el valor 4703.
2) Usando algunas de las funciones de Numpy listadas en Métodos matemáticos y estadísticos, calculemos la media y el desvío de los elementos del array que construimos en... | false |
b549c9db156fd82a945a101f713d0c66a14c64f8 | abrosen/classroom | /itp/spring2020/roman.py | 1,147 | 4.125 | 4 | roman = input("Enter a Roman Numeral:\n")
value = {"I" :1, "V":5, "X":10, "L":50,"C":100,"D":500,"M":1000}
def validate(roman):
count = {"I" :0, "V":0, "X":0, "L":0,"C":0,"D":0,"M":0}
for letter in roman:
if letter not in count:
return False
for letter in roman:
count[letter... | false |
6db17e91e654e5229ccad28166264478673839d9 | abrosen/classroom | /itp/spring2020/booleanExpressions.py | 427 | 4.1875 | 4 | print(3 > 7)
print(6 == 6)
print(6 != 6)
weather = "sunny"
temperature = 91
haveBoots = False
goingToTheBeach = True
if weather == "raining":
print("Bring an umbrella")
print(weather == "raining" and temperature < 60)
if weather == "raining" and temperature < 60:
print("Bring a raincoat")
if (weather == "rain... | true |
0c9567b722911116f27ed17fbc1129e8d900342f | berkercaner/pythonTraining | /Chap08/dict.py | 1,565 | 4.25 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# it's like hash map in C
# each pair seperated by ',' and left of the pair is 'key'
# right of the pair is 'value'
def main():
#one way of creating dictionary
animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': ... | false |
8f4b21a601c7e3a2da6c26971c7c7bb982d4a242 | hashncrash/IS211_Assignment13 | /recursion.py | 2,230 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 14 Assignment - Recursion"""
def fibonnaci(n):
"""Returns the nth element in the Fibonnaci sequence.
Args:
n (int): Number representing the nth element in a sequence.
Returns:
int: The number that is the given nth element in the fibonna... | true |
7e50120d6e273dc64b440c847a7bfb4b2f8599da | PyladiesSthlm/study-group | /string_processing/elisabeth_anna.py | 1,377 | 4.34375 | 4 | #!/usr/bin/env python
import sys
import argparse
def palindrome_check(string_to_check):
letters_to_check = len(string_to_check)
if letters_to_check % 2 == 0:
letters_to_check = letters_to_check/2
else:
letters_to_check = (letters_to_check -1)/2
print letters_to_check
samma = 0
... | false |
8d1de591706470db3bbcf26374ff958f393e85f7 | tungnc2012/learning-python | /if-else-elif.py | 275 | 4.21875 | 4 | name = input("Please enter your username ")
if len(name) <= 5:
print("Your name is too short.")
elif len(name) == 8:
# print("Your name is 8 characters.")
pass
elif len(name) >= 8:
print("Your name is 8 or more characters.")
else:
print("Your name is short.") | true |
7de4e99e276c3e0ba73fc82112b55f7ee8190d5c | ayazzy/Plotter | /searches.py | 1,673 | 4.1875 | 4 | '''
This module has two functions.
Linear Search --> does a linear search when given a collection and a target.
Binary Search --> does a binary search when given a collection and a target.
output for both functions are two element tuples.
Written by: Ayaz Vural
Student Number: 20105817
Date: March 22nd 2019
'''
def lin... | true |
a4b22a4a32ffa1afb1508d232388d6bc759e0485 | avi651/PythonBasics | /ProgrammeWorkFlow/Tabs.py | 233 | 4.125 | 4 | name = input("Please enter your name: ")
age = int(input("Hi old are you, {0}? ".format(name))) #Adding type cast
print(age)
if age > 18:
print("You are old enough to vote")
else:
print("Please come back in {0}".format(18 - age)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.