blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
cbc6012a9ffab6745f197b42a9a081f3c4d0c0af | polo1250/CS50-Projects | /Problem_Set_6/mario/more/mario.py | 280 | 4.25 | 4 | # Get the right value for the height
while True:
height = input("height: ")
if (height.isdigit()) and (1 <= int(height) <= 8):
height = int(height)
break
# Print the pyramid
for i in range(1, height+1):
print(" " * (height-i) + "#"*i + " " + "#"*i)
| true |
ca2f6b097aa5462fd678bc93466dcc90aef4c593 | clintjason/flask_tutorial_series | /4_url_building/app.py | 1,031 | 4.28125 | 4 | from flask import Flask, url_for # import the Flask class and the url_for function
'''
url_for() is used to build the url to a function.
It takes as first argument the function name.
If it takes any more arguments, those arguments will be variables used
to build the url to the function.
'''
app = Flask(__name__) # ins... | true |
29551642e0ccfb4874e64ef84701c46bc5d4760c | CloudBIDeveloper/PythonTraining | /Code/Strings Methods.py | 303 | 4.21875 | 4 | str='Baxter Internationl'
print(str.lower())
print(str.upper())
s1 = 'abc'
s2 = '123'
""" Each character of s2 is concatenated to the front of s1"""
print('s1.join(s2):', s1.join(s2))
""" Each character of s1 is concatenated to the front of s2"""
print('s2.join(s1):', s2.join(s1))
| true |
29b87f157ef7686c53d896f60724bd97189a2851 | huskydj1/CSC_630_Machine_Learning | /Python Crash Course/collatz_naive.py | 366 | 4.40625 | 4 |
def print_collatz(n):
while (n != 1):
print(n, end = ' ')
if (n % 2 == 0):
n = n // 2
else:
n = 3*n + 1
print(1)
num = input("Enter the number whose Collatz sequence you want to print: ")
try:
num = int(num)
print_collatz(num)
except:
print("Error. Y... | true |
2955a1dac0e1ff268564954509c7100dcbe8c334 | shazia90/code-with-mosh | /numbers.py | 268 | 4.25 | 4 | print (10 + 3)
print (10 - 3)
print (10 * 3)
print (10 / 3) #which gives float no
print (10 // 3)# this gives integer
print (10 % 3)#modulus remainder of division
print (10 ** 3)#10 power 3
x = 10
x = x + 3 # a)
x += 3 # b) a, b both are same
print (x)
| true |
0a0c80b6182e450fe6d7c90e6fcd438dc8e0a6bf | pranshuag9/my-cp-codes | /geeks_for_geeks/count_total_permutations_possible_by_replacing_character_by_0_or_1/main.py | 768 | 4.1875 | 4 | """
@url: https://www.geeksforgeeks.org/count-permutations-possible-by-replacing-characters-in-a-binary-string/
@problem: Given a string S consisting of characters 0, 1, and ‘?’, the task is to count all possible combinations of the binary string formed by replacing ‘?’ by 0 or 1.
Algorithm:
Count the number of ? c... | true |
2bd068d2ef3a4069eeeed84807cf730a806abac1 | pranav1698/algorithms_implementation | /Problems/unique_character.py | 318 | 4.15625 | 4 | def uniqueChars(string):
# Please add your code here
char=list()
for character in string:
if character not in char:
char.append(character)
result=""
for character in char:
result = result + character
return result
# Main
string = input()
print(uniqueChars(string))
| true |
70956143a82115aff42295f241d966c6aa3d55f6 | UN997/Python-Guide-for-Beginners | /Code/number_palindrome.py | 271 | 4.15625 | 4 | num = input('Enter any number : ')
try:
val = int(num)
if num == str(num)[::-1]:
print('The given number is PALINDROME')
else:
print('The given number is NOT a palindrome')
except ValueError:
print("That's not a valid number, Try Again !") | true |
485369e97ba682adae1920a4eb135330bd8ef2d2 | tecmaverick/pylearn | /src/43_algo/11_permutation_string.py | 1,180 | 4.1875 | 4 | # The number of elements for permutations for a given string is N Factorial = N! (N=Length of String)
# When the order does matter it is a Permutation.
# Permutation Types -
# Repetation allowed - For a three digit lock, the repeat permutations are 10 X 10 X 10 = 1000 permutations
# No Repeat - For a three digit lock... | true |
372a40b95e5464150724b67f66c94b59c2424a04 | tecmaverick/pylearn | /src/38_extended_args/extended_args_demo.py | 2,116 | 4.90625 | 5 | #extended argument syntax
#this allows functions to receive variable number of positional arguments or named arguments
#example for variable positional args, which accepts variable number of argument
print "one","two"
#example of variable keyword args, which accepts variable number of keyword aegs
val = "hello {a}, {b... | true |
46bb500aa36043c5d94e7217dc2b4b9a04c71eb3 | tecmaverick/pylearn | /src/39_scopes/scope_demo.py | 1,051 | 4.1875 | 4 | #LEGB Rule
#Local, enlcosing, global, built-in
my_global_var = "this is global"
def outer():
outer_msg = "outer msg"
val1 = {"test":"val"}
def inner():
#here the variables in the enclosing scope in outer() function
#is closed over by referencing the vairables referred
#the enclosed variables can be viewed by... | true |
73d5479e38e90c50d977e16ad32e549185b633ba | tecmaverick/pylearn | /src/32_closures/closuredemo.py | 1,360 | 4.5 | 4 |
#Python closure is lst nested function that allows us to access variables of the outer function even after the outer function is closed.
def my_name(name, time_of_day):
def morning():
print "Hi {} Good Morning!".format(name)
def evening():
print "Hi {} Good Evening!".format(name)
def night():
print "Hi {} ... | true |
6d0c94be6a853bb27bc1fa316a1248294bfa5599 | ArturRejment/snake | /scoreboard.py | 725 | 4.15625 | 4 | from turtle import Turtle
""" A class to display current score and game over message """
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.score = -1
self.color("white")
self.hideturtle()
self.goto(0, 250)
self.write_score()
# Update and w... | true |
61ebe352704ce9bbbf643534cacb3287214725e7 | dnieafeeq/mysejahtera_clone | /Day2/chapter32.py | 705 | 4.46875 | 4 | theCount = [1, 2, 3, 4, 5]
fruits = ['banana', 'grape', 'mango', 'durian']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in theCount:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# am... | true |
2580f8a9daee003faf559e5e880ecc12c7170e83 | Rantpel/Batch-Four | /leap year.py | 272 | 4.375 | 4 | #Purpose of the program
print("Program to Determine is a given year is a leap year")
year=int(input("Enter yearto be Checked."))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year")
else:
print("The year isn't a leap year!")
| true |
5cb76103b8e0c3142b9530c0d8f4c3498ba3f439 | Rantpel/Batch-Four | /simple int.py | 573 | 4.3125 | 4 | #The purpose of the Program
print("this is a program to find Simple Interest")
#Ask the user to input the principal amount
print("Input the principal amount")
principal=int(input("the value of principal:"))
#Ask the user to input the rate
print("Input the principal amount")
rate=float(input("the value of rate:")... | true |
bdf46483e177e6e935750d552f5448f10a7d5bf2 | YXMforfun/_checkio-solution | /home/median.py | 1,251 | 4.15625 | 4 | """
A median is a numerical value separating the upper half of a sorted array of numbers from the lower half.
In a list where there are an odd number of entities, the median is the number found in the middle of the array.
If the array contains an even number of entities, then there is no single middle value, in... | true |
a109be86b2888df9b07f5a4a8b3cd254f7f99626 | sek550c/leetcode | /py/121BestTimeBuyAndSell.py | 901 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [... | true |
1805e80b2a72b2bec016f4a3180cdd649c3ecde6 | sek550c/leetcode | /py/27RemoveElement.py | 772 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave b... | true |
70979eb5db49ade6b309de53f1ca5eba96bca979 | sek550c/leetcode | /py/118PascalTriangle.py | 954 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
import time
def getNum(row, col):
if row == col or col == 1: return 1
else: return getNum(ro... | true |
b0d56744efd572d799a2a3d43924166ce2de0af0 | sek550c/leetcode | /py/283MoveZeros.py | 1,024 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do th... | true |
cebbe4aaacb3da2130490bb808a877c9272f2eee | sek550c/leetcode | /py/350IntersectionOfTwoArray.py | 2,526 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
... | true |
9a17391792811cb4a9ec80bb949315b09340b224 | Sharmaraunak/python | /wk215.py | 363 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 14:24:17 2018
@author: raunak
"""
##print("enter the base: ")
#base = eval(input())
#print("enter the exponential power: ")
#exp = int(input())
def iterPower(base,exp):
result =1
while exp > 0:
result = result*base
print(r... | true |
08a24f5866f3f3b9c14edfcdf459134bc530df3b | deepanshurana/Python-Codes | /ErrorsAndExceptions.py | 987 | 4.1875 | 4 | """
There are two kinds of errors: SyntaxError and Exceptions.
Even if the statement or expression is syntactically correct,it may cause
an error when an attempt is made to execute it.
It is possible to handle selected exceptions. (using try and except)
firstly, the try clause is executed. If no exceptions, then excep... | true |
07323696d37d37669753cca7eea3a943bf1adf78 | deepanshurana/Python-Codes | /max difference in an array.py | 500 | 4.125 | 4 | print('--'* 50)
list = [] #initialising list
size_of_array = int(input('ENTER THE TOTAL ELEMENTS IN AN ARRAY: ')) #for the total size of an array
for i in range(0,size_of_array):
value = int(input('Enter the %d element: ' % (i+1)))
list.append(value) #appending the list
print('The list is :' , lis... | true |
13a4a85fe117384d118cd3fe2f3a56d88d5747b0 | nikgun1984/Data-Structures-in-Python | /Queues and Stacks/Stack.py | 1,159 | 4.15625 | 4 | # Stack implementation using LinkedList
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def push(self, value):
new_node = Node(value)
if ... | true |
15369703773202192231181b1c5940dfb8488fca | patrick-du/Notes | /Courses & Books/Grokking Algorithms/breadth_first_search.py | 2,680 | 4.25 | 4 | # Breadth-first search (BFS): a graph algorithm to find the shortest path b/w 2 nodes
# Breath-first search answers 2 questions:
# - Is there a path from node A to node B?
# - What is the shortest path from node A to node B?
# Example Use Case
# - Checkers AI to calculate fewest moves to victory
# - Spell chc... | true |
df90b293ace1bab8e500c6ab24d6a008170b2666 | mlama007/4RockPaperScissors | /4ROCK_PAPER_SCISSORS.py | 1,193 | 4.15625 | 4 | """This is a simple game of rock, paper, scissors"""
from random import randint
from time import sleep
options = ["R", "P", "S"]
LOSE = "You lost!"
WIN = "You won!"
def decide_winner(user_choice, computer_choice):
print "Your choice: %s" % user_choice
print "Computer selecting..."
sleep(1)
print "Com... | true |
a960c05cf9b1f541bc638170cf8ecb616c00cf6d | Sandhya788/Basics | /python/password5.py | 394 | 4.15625 | 4 | incorrectPassword= True
while incorrectPassword:
password = input("type in your password")
if len(password < 8):
print("your password must be 8 characters long")
elif noNum(password == False):
print("you need a number in your password")
elif noCap(password == False):
print("you n... | true |
0ba02a9253e23eb402cbb15f8b317256283bc025 | xen0bia/college | /csce160/book_source_code/Chapter 10/exercise1/exercise1.py | 1,785 | 4.65625 | 5 | # 1. Pet Class
# Write a class named Pet , which should have the following data attributes:
# • _ _ name (for the name of a pet)
# • _ _ animal_type (for the type of animal that a pet is. Example values are ‘Dog’, ‘Cat’,
# and ‘Bird’)
# • _ _ age (for the pet’s age)
# The Pet class should have an _ _ ... | true |
bbb14262a5f93148882b0a0c0b91cb224e769682 | xen0bia/college | /csce160/lab5/payroll.py | 876 | 4.15625 | 4 | '''
Zynab Ali
'''
REG_HRS = 40.0 # Hours at regular pay before overtime starts
OVERTIME_RATE = 1.5 # Overtime payrate multiplier
def main():
hours_worked = float(input('\nEnter the number of hours worked this week: '))
hourly_rate = float(input('Enter the hourly pay rate: '))
if hou... | true |
989d12e0d08597a26cb87d17c91b37671a213a2f | githubcj79/nisum_test | /answers.py | 1,755 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ejercicio 1
# Write a Python program to square and cube every number in a given list of integers using Lambda.
# Original list of integers:
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square every number of the said list:
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Cube every num... | true |
7c68b401fcd371aae138cbf0e3ebd2472985e591 | im-swapnilb/python | /app3-part11.py | 2,935 | 4.34375 | 4 | """
Problem statement :
Ask the user how many floating point numbers with 5 integer digits and two decimal digits the program should accept.
That means you need to check if the number entered by the user has 5 digits and two decimal digits to be accepted.
Your program should accept five of them. Add the numbers and dis... | true |
799b0d3dfc32ffbf001cda74455b22230e7ae94b | im-swapnilb/python | /pythonTest1/create_dictionary.py | 1,046 | 4.3125 | 4 | """
Create dictionary with different key-values and print it
@Author Swapnil_Bandgar, Student_id : 500186962
"""
# creating dictionary with different approach and datatype
def create_dict():
# creating empty dictionary
dict4 = {}
# dictionary with multiple data types
dict1 = {"Name": "Swapnil", "Cour... | true |
5dc54c2f2a1a94ef286021646bb4639060b17356 | im-swapnilb/python | /pythonTest1/operations.py | 420 | 4.3125 | 4 | # Python program for practical application of sqrt() function
# import math module
import testMathFunc
# function to check if prime or not
def check(n):
if n == 1:
return False
# from 1 to sqrt(n)
for x in range(2, (int)(testMathFunc.sqrt(n)) + 1):
if n % x == 0:
return False... | true |
9188e2bac20ff5ffc20a18924629faac35eccd6b | Nethermaker/school-projects | /intro/dictionary_assignment.py | 2,734 | 4.28125 | 4 | # 1. Create a dictionary that connects the numbers 1-12 with each
# number's corresponding month. 1 --> January, for example.
months = {1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:... | true |
63f9d76cd6887ae1e04bb01c9c1e7f5ad2d91270 | Nethermaker/school-projects | /adv/crash_course.py | 1,904 | 4.125 | 4 | print 'Welcome to Advanced Programming'
#Math
print 3 + 4
print 3 - 4
print 3 * 4
print 3 / 4
name = 'Handelman'
number = 27
number2 = 15
print 'My name is {}.'.format(name)
#your_name = raw_input('What is your name? ')
#print 'Hello there, {}!'.format(your_name)
def average_of_three(x,y,z):
... | true |
2822851327677da64c8304bc70604beb3f2c46eb | Nethermaker/school-projects | /intro/warmup_day4.py | 870 | 4.3125 | 4 | # The following program is supposed to ask a user how much the meal
# cost, how many people ate, and what percentage they are tipping, and
# should return the amount each person should pay.
# Unfortunately, there are several errors in the program. Can you find
# them all? Here is what the program should look like ... | true |
05babfc47f24daf65034ad088d157e909125f077 | acalzadaa/python_bootcamp | /week03 input and coditionals/friday.py | 1,316 | 4.34375 | 4 | # end of week project
# making a calculator!
# 1. Ask the user for the calculation they would like to perform.
# 2. Ask the user for the numbers they would like to run the operation on.
# 3. Set up try/except clause for mathematical operation.
# a. Convert numbers input to floats.
# b. Perform operation and prin... | true |
e7c0d6a1deed8429577c1ecf9100226f75445668 | acalzadaa/python_bootcamp | /week08 Efficiency/tuesday.py | 1,575 | 4.71875 | 5 | # Lambda functions, otherwise known as anonymous functions,
# are one-line functions within
# >>> lambda arguments : expression
# >>> lambda arguments : value_to_return if condition else value_to_return
# Using a Lambda
# using a lambda to square a number
print( ( lambda x : x**2) (4) )
# Passing Multiple Argument... | true |
909c816c70dc94e74ad37588623cca19493a0a46 | acalzadaa/python_bootcamp | /week06 data collections and files/tuesday.py | 1,912 | 4.46875 | 4 | # Tuesday: Working with Dictionaries
#Adding New Information
# adding new key/value pairs to a dictionary
car = {"year" : 2018}
car["color"] = "Blue"
print(f'year {car["year"]} , color {car["color"]}')
#Changing Information
# updating a value for a key/value pair that already exists
car["color"] = "Red"
print(f'yea... | true |
4b5e34a4a0f10ff3034e4d82e7c61811636bfdfe | acalzadaa/python_bootcamp | /week08 Efficiency/week_challenge.py | 704 | 4.25 | 4 | # For this week’s challenge, I’d like you to create a program that asks a user to input a number
# and tells that user if the number they entered is a prime number or not.
# Remember that prime numbers are only divisible by one and itself and must be above the number 2.
# Create a function called “isPrime” that you ... | true |
a2e299f33ca165eb421f24d80ef8b9996348fc54 | acalzadaa/python_bootcamp | /week04 lists and loops/tuesday.py | 1,551 | 4.28125 | 4 | # writing your first for loop using range,
# COUNTS UP TO... BUT NOT INCLUDING
print("1st Exercise ---------------------")
for num in range(5):
print(f"Value: {num}")
# providing the start, stop, and step for the range function
print("2nd Exercise ---------------------")
for num in range(2, 10, 2):
print(f"Va... | true |
d802058971fb6d6805caf1bf4a08f9ddd8c31dcb | ksambaiah/Programming | /python/lists/listsComp.py | 434 | 4.375 | 4 | #!/usr/bin/env python3
# List comprehension is fun
if __name__ == "__main__":
# populate list with some values
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
# Get all even elements
even = [i for i in a if i % 2 == 0]
print(a)
print("Even numbers in the above list")
print(eve... | true |
024d2adce8e739fb8aaaedd3da198a789efc7e70 | usamayazdani/Python | /Practice/Important/codes/Q1(proper_index_in_list).py | 1,081 | 4.34375 | 4 | """function that inserts a value in
the list at its proper position (index) such that after inserting the value the list is still sorted. The list can
either be in ascending or descending order, your function should work for both types. You can write a
separate function to which would tell you in which order the list i... | true |
069f6ae77c525f691cc557fe3b2ba713017e6de9 | usamayazdani/Python | /Assignments/Assignment 005/Code/code_get_comany_names.py | 1,461 | 4.25 | 4 | """function you need to write is called “get_companies”. It takes the list of
dictionaries representing companies along with a dictionary representing
location. This dictionary will have “City” and “Country” as its keys. The values of
these keys can be any strings. Your function should return a list of companies
which ... | true |
2ebde5681e35e4dbb7233320f4bb721fa1c01685 | usamayazdani/Python | /Practice/reverse_given_number.py | 638 | 4.375 | 4 |
# This function take input from the user and than pass into the function .
# the output is the reverse of the number .
# This will run for both positive and negative integers
num = int(input("Enter any positive or negative number : "))
def reverse_a_given_integer_num(num):
if num < 0:
num = -1*num
... | true |
a601e1cd64b8b1e77d02d22bddc50ff57b6c12ed | ZahraFarhadi19/Leetcode-practices | /Unique Email Addresses/Unique-Email-Addresses.py | 1,469 | 4.15625 | 4 | '''
Every email consists of a local name and a domain name,
separated by the @ sign.
For example, in alice@leetcode.com,
alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name... | true |
000c5f4b6aebd1b321becfaf011f4fdd70433a84 | jjnorris31/metodosNumericos | /flip_boolean.py | 497 | 4.40625 | 4 | """
Create a function that reverses a boolean value and returns the string "boolean expected" if another variable type is given.
Examples
True ➞ False
False ➞ True
0 ➞ "boolean expected"
None ➞ "boolean expected"
"""
def reverse(arg):
if type(arg) == type(0) or arg == {}:
result = "boolean expected"
... | true |
b45a147939f5983102fe08ac10871675f5a99c88 | jjnorris31/metodosNumericos | /even_generator.py | 241 | 4.1875 | 4 | """
Using list comprehensions, create a function that finds all even numbers from 1 to the given number.
Examples
8 ➞ [2, 4, 6, 8]
4 ➞ [2, 4]
2 ➞ [2]
"""
def find_even_nums(num):
return [i for i in range(1, num + 1) if i % 2 == 0]
| true |
bbc409b2e9d9212d4c40e738aca76d4767ccce81 | jjnorris31/metodosNumericos | /array_of_arrays.py | 607 | 4.4375 | 4 | """
Create a function that takes three arguments (x, y, z) and returns a list containing sublists (e.g. [[], [], []]), each of a certain number of items, all set to either a string or an integer.
x argument: Number of sublists contained within the main list.
y argument Number of items contained within each sublist(s).
... | true |
72d30654274571f5fad472c4090b8d2fd414682a | jjnorris31/metodosNumericos | /is_anagram.py | 281 | 4.15625 | 4 | """
Write a function that takes two strings and returns (True or False) whether they're anagrams or not.
Examples
'cristian', 'Cristina' ➞ True
'Dave Barry', 'Ray Adverb' ➞ True
'Nope', 'Note' ➞ False
"""
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
| true |
5fdda35bdd889857a3dfb20bf12707f03b9b6ab3 | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_progrm_21.py | 656 | 4.28125 | 4 | # Prinitig an object
class Shoe:
def __init__(self, price, material):
self.price = price
self.material = material
s1 = Shoe(1000, "Canvas")
print(s1)
# the above print of s1 object is not in more readable format, it gives hexagonal form
# to implement the more readable format for prining the obje... | true |
feed600182879d3f19c072e7275306cc97010d4a | abhigyan709/dsalgo | /Python_basics/while_loops.py | 323 | 4.28125 | 4 | # while loop repeats a block of code as long as a particular condition remains true
# a simple value
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
# letting the user to choose when to quit
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(ms... | true |
44590fe7a33d99a7a8e21a5200b78602502753ab | abhigyan709/dsalgo | /OOPS_CONCEPT/OOP Principles/class_program_20.py | 464 | 4.125 | 4 | # just like the ballons and ribbons, we can make one reference variable refer to another object.
# now any change made through this refernce varible will not affect the old object.
class Mobile:
def __init__(self, price, brand):
self.price = price
self.brand = brand
mob1 = Mobile(1000, "Apple")
mo... | true |
dfca9ad207774c458ad78c9b0477d2c31cadb154 | AnoopPS02/Launchpad | /P5.py | 257 | 4.34375 | 4 | *program that asks the user for a phrase/sentence & Print back to the user the same string, except with the words in backwards order*
String="My name is Anoop"
String1=String.split()
String2=String1[::-1]
Ans=""
for i in String2:
Ans=Ans+" "+i
print(Ans)
| true |
7ce893d37b6c60644004bf0c01bbbb09d5fe194c | informramiz/Unscramble-Computer-Science-Problems | /Task1.py | 1,583 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone nu... | true |
3497a9d3abc8ec8d38e813b741749ce120525950 | apugithub/MITx-6.00.1x-Programming-Using-Python | /Week-3/Hangman_Is The Word Guessed.py | 735 | 4.125 | 4 | ##### 1st Approach:
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN... | true |
db97ad39dc4c39620b3285751f375d4c75fd167a | himu999/Python_oop | /H.inheritance/c.inheritance.py | 1,092 | 4.15625 | 4 | class Vehicle:
"""Base class for all vehicles"""
def __init__(self, name, manufacturer, color):
self.name = name
self.color = color
self.manufacturer = manufacturer
def drive(self):
print("Driving", self.manufacturer, self.name)
def turn(self, direction):
print... | true |
e730a2f4f5e0e752cb6304b604366dbce9d6ac12 | Jbranson85/Python | /drawface.py | 1,142 | 4.15625 | 4 | '''
drawface.py
Jonathan Branson, 3/27/17
This program will draw a face that has 2 eyes, nose and a mouth, by using the
tkinter mondule to draw the shapes on a canvas
'''
from tkinter import *
##Builds Frame
root = Tk()
##Creates the Canvas, for shapes to be drawn on
background = Canvas(root, ... | true |
ac7d3d379427f91dc20dc11731723ec3ecce0d36 | DaveRichmond-/sabine_learn_to_code | /pfk_exercises/review_chpt1_8.py | 1,913 | 4.21875 | 4 | # Chapter 2: Variables --------------->
# how much money would you have in your piggy bank, if you had 7 one dollar bills, 34 quarters, 71 dimes, 112 nickels and 42 pennies?
# create an equation below to calculate the result and store it in a variable called TOTAL.
# you can use the variables that I created for you:
... | true |
6cb8ca0e88370851e98b55c3778747352feb172e | ectrimble20/PythonExerciseCode | /PracticePython/ElementSearch.py | 2,609 | 4.1875 | 4 | # ElementSearch.py
import random
"""
Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to
largest) and another number. The function decides whether or not the given number is inside the list and
returns (then prints) an appropriate boolean.
Extras:
Use binary... | true |
502405c48c8a71d517817d1074c1ad766a99ead8 | ectrimble20/PythonExerciseCode | /PracticePython/Divisors.py | 689 | 4.34375 | 4 | # Divisors.py
"""
Create a program that asks the user for a number then prints out a list of all the divisors of that number
...divisor is a number that divides evenly into another number, ex 13 is a divisor of 26 because 26 % 13 == 0
"""
num = int(input("Enter a number to get it's divisors: "))
l = []
# for n in ran... | true |
176f1237183f9733598b42ef847ce809c188da52 | samarla/LearningPython | /fibonacci.py | 385 | 4.40625 | 4 | user_input = int(input('enter how many fibonacci numbers to be printed (not less than 3): \n'))
fibonacci = [1, 1]
def append_fibonacci(n):
"""this function appends the next fibonacci element into the list """
next_number = fibonacci[n-1]+fibonacci[n-2]
fibonacci.append(next_number)
for i in range(2, us... | true |
c7a67c23b2aae88e039c045f3dae89fe6b372e5e | samarla/LearningPython | /factorial using function.py | 289 | 4.25 | 4 | number = int(input('enter any number: '))
def factorial(n):
if n == 1: # The termination condition
return 1 # The base case
else:
res = n * factorial(n-1) # The recursive call
return res
print('the factorial of given number is: ',factorial(number))
| true |
3b4b7774719a9a625ac876df22fa0c8240f4b543 | SonoDavid/python-ericsteegmans | /CH7_lists/indexSmallest.py | 1,080 | 4.40625 | 4 | def index_smallest_of(sequence, start=0):
"""
Return the position of the smallest element in the
given sequence starting from the given position.
- If several smallest elements can be found, the
function return the position of te leftmost
smallest element.
- None is return if no such sm... | true |
999b4c25b114ca8354eac7a2d3f4ea6ad6c18512 | SonoDavid/python-ericsteegmans | /CH4_strings/calc_num_digits.py | 504 | 4.34375 | 4 | # Calculate the sum of the digits in an integer number
# in decimal format
# - The program keeps on prompting for a non-negative
# integer number until it finally gets one
number = ""
while not str.isdigit(number):
number = input\
("Enter a non-negative number: ")
digit_sum = 0
current_pos = 0
whil... | true |
3d390d7d50f009bf9aaa30677332ed3d637a44d5 | SonoDavid/python-ericsteegmans | /CH1_integer_arithmetic/leapyear.py | 411 | 4.28125 | 4 | # Check whether a given year is a leap year.
# A year is a leap year if it is a multiple of 4 and
# not a multiple of 100, or it is a multiple of 400.
#
# Author: Joachim David
# Date: June 2019
year = int(input("Enter the year to examine: "))
if ((year % 4 == 0) and not (year % 100 == 0)) or (year % 400 == 0):
... | true |
801faa729dc97d01fc50f8bf3a112f56777a6689 | EmpowerSecurityAcademy/daily_exercises | /lambda_operator/lambda_operator.py | 610 | 4.3125 | 4 | # list comprehensions follow the format
# [dosomething(num) for num in array if some_condition_is_true]
# use a list comprehension to return only even numbers
def even_numbers(array_numbers):
return [num for num in array_numbers if num % 2 == 0]
# use list comprehension to return words starting with the letter "a"
... | true |
d78278d86a8e2b522e1845cb876fb9f9c85132f9 | flavienfr/bootcamp_ml | /day00/ex00/sum.py | 547 | 4.1875 | 4 | def sum_(x, f):
"""Computes the sum of a non-empty numpy.ndarray onto wich a function is
applied element-wise, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
f: has to be a function, a function to apply element-wise to the
vector.
Returns:
The sum as a float.
None if x is ... | true |
d48bd9fab26d6876b882c9cb209a102e83d00a4a | Ciwonie/python_cs150 | /cs150/week_6/project_2.py | 1,472 | 4.34375 | 4 | # This project works with while loops and inputs . Your program will generate a random value, and ask for your guess.
# Upon submitting your guess, the program will return back if your guess is too high or too low.
# This will continue until you guess the correct number in which the program will output:
# "Correct con... | true |
233a31e57427b5f4b0566215076380cd209a0365 | jatinsumai1104/Essence | /ml_model/text-module/readCsv.py | 1,501 | 4.125 | 4 | # importing csv module
import csv
# csv file name
filename = "aapl.csv"
# initializing the titles and rows list
fields = []
rows = []
# reading csv file
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting field nam... | true |
d0dfb47058916c53ec30d41696a076a2d7430773 | devichandanpati/python | /conditionals_13.py | 669 | 4.28125 | 4 | week = [(0,"Sunday"), (1,"Monday"), (2,"Tuesday"), (3,"Wednesday"), (4,"Thursday"), (5,"Friday"), (6,"Saturday")]
x = int(input("Enter number for a week day between 0-6"))
for number,day in week :
if x == 0 :
print("Day is Sunday")
break
elif x == 1 :
print ("Day is Monday")
... | true |
463f670913fdbbe42ac74b8478e3e4ed2aafbf40 | devichandanpati/python | /functions_20.py | 624 | 4.25 | 4 | def turn_clockwise(direction) :
direction = str(input("Enter direction"))
if direction == "N" :
print("Direction is E")
direction == "E"
return direction
elif direction == "E" :
print("Direction is S")
direction == "S"
return d... | true |
98a722a91f143889d8b88442a2430d0d52c4606d | ulises28/PHW | /ClassCompositionExample.py | 1,182 | 4.5 | 4 | from typing import List #List, tuple, set... etc
import sys
class BookShelf:
def __init__(self, *books): #When calling a function, the * operator can be used to unpack an iterable into the arguments in the function call
self.books = books
#Type hinting -> the value that must be returned or ": str" afte... | true |
89f7be3862af86fdf222b2b3268795ed908983fd | rybli/Python-Class-Practice | /Vehicle/Exercise 4.py | 746 | 4.34375 | 4 | # Exercise Question 4: Class Inheritance
# Create a Bus class that inherits from the Vehicle class.
# Give the capacity argument of Bus.seating_capacity() a default value of 50.
# Use the following code for your parent Vehicle class. You need to use method overriding.
class Vehicle:
def __init__(self, name, max... | true |
063094016c88e3f76a69e919b11adf39ff762f31 | rybli/Python-Class-Practice | /Random/dice_rolling.py | 1,842 | 4.40625 | 4 | # Dice Rolling Program
# Original Problem Statement
# Write a program that will roll a 6-sided dice and display it with ascii art.
from random import randint
class Dice:
# Die face count that are allowed.
allowed_sides = [3, 4, 6, 8, 12, 20]
def __init__(self, sides: int):
"""
Create a ... | true |
ba9615892470400493ff92ff97c59eb76b6e5a8b | cla473/PythonTest | /Genfuncs.py | 1,503 | 4.25 | 4 | """
A set of generic functions:
reverse_string(string) --> string
split_string(orig_str, no_chars) --> list
strip_leading_digits(orig_str) --> string
transcribe_DNA(orig_DNA) --> string
@author: cla473
"""
#Signature: string --> string
def reverse_string(orig_str):
""" return a reversed string
... | true |
3ca72ae79bcd3c5128f9391287fc32b75bee38ee | laminsawo/python-365-days | /python-fundamentals/day-6-Dictionaries/dictionary-labs-decisions.py | 2,000 | 4.53125 | 5 | dict1 = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'key': 54}
print(dict1)
print(dict1['one'])
print(dict1['two'])
print(dict1['three'])
# modify a dictionary key value
dict1['key'] = 22
print(dict1, '\n')
# add new a dictionary key and a value
dict1['newKey'] = 66
print(dict1, '\n')
# creat... | true |
a8bf71ee2acb3edf2a8cca85e819dba665f99465 | laminsawo/python-365-days | /python-fundamentals/day-1-Operators/advanced-operators.py | 1,185 | 4.8125 | 5 | # This Python file exhibits Advanced Python Maths operators
"""
Operators and usage:
// = Floor division - This rounds down the answer to the nearest whole number when two numbers are divided
% = Modulus - This gives the remainder when two numbers are divided e.g. 5 % 2 = 1
** = Exponent - gives the result of powe... | true |
115f7fb591125aca6b3b8a132aa3528b0cc169c9 | brandonmorren/python | /C7 text Files/oefTextFiles/extraOEF1.py | 1,241 | 4.25 | 4 | def read_month(input_month):
if input_month == 8:
file = open("./Files/weather_2018 08.csv")
elif input_month == 10:
file = open("./Files/weather_2018 10.csv")
file.readline() #titel lezen
line = file.readline().rstrip()
highest_temperature = 0
first_period = line.split(";")[0]... | true |
47dbe1afe497cd782da601861888775c94cb3e7c | brandonmorren/python | /C3 iteratie/oefIteratie/oefening 5.py | 619 | 4.25 | 4 | number = int(input("enter a number: "))
if number != 0:
smallest_number = number
highest_number = number
difference = 0
while number != 0:
if number < smallest_number:
smallest_number = number
else:
if number > highest_number:
highest_number = numb... | true |
8ae7e1a9e691f66b965f09644bf849f4938d5506 | brandonmorren/python | /C10 set/OefeningenSet/oef 5.py | 479 | 4.4375 | 4 | months_days = {"January": 31, "February": 28, "March": 31,
"April": 30, "May": 31, "June": 30, "July": 31,
"August": 31, "September": 30, "October": 31,
"November": 30, "December": 31}
input_month = input("Month (press enter for an overview of all months): ")
if input_month... | true |
12a0e490f5025bca17f7957ae7cf6a7677bfd7fe | naldridge/algorithm_exercises | /algorithm_exercise.py | 1,468 | 4.25 | 4 | # Algos
## 1. Bubble Sort
Write a program to sort a list of numbers in ascending order, comparing and swapping two numbers at a time.
```python
[3,1,4,2]
[1,3,4,2]
[1,3,2,4]
[1,2,3,4]
```
## 2. Candies
Given the list `candies` and the integer `extra_candies`, where `candies[i]` represents the number of candie... | true |
440aad874dfa186c0419813799507b6f4a31debb | midathanapallivamshi/Saloodo | /Question one challange( return reverse of string)/reversestring.py | 988 | 4.28125 | 4 | #!/usr/bin/env python3
import random
# Json module import only if we are reading json input reading and currently we are not reading json input and hence commenting out
# import json
def reverse_string(str_input):
"""
This method is used to reverse a string
"""
reverse_string = str_input[1:]
... | true |
4187ba4726a9bd9feda1d72edf9a0a7215f9bdbf | saipavandarsi/Python-Learnings | /FileSamples/ReverseFileContent.py | 344 | 4.3125 | 4 | #File content Reversing
#Using read()
file = open('myfile.txt', 'r')
content = file.read()
print content
print content[::-1]
# Using ReadLines
file = open('myfile.txt', 'r')
content_lines = file.readlines()
#content_lines[::-1] is to reverse lines
for line in content_lines[::-1]:
#print characters in reverse
... | true |
f387d5872cd714e4f672fa9cd08e788072c4cd99 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/1-BasicPython/integers_floats.py | 683 | 4.125 | 4 | ''' ------ Working with Integers and Floats in Python -----
There are two Python data types that could be used for numeric values:
- int - for integer values
- float - for decimal or floating point values
You can create a value that follows
the data type by using the following syntax:
'''
x = int(4.7) # x is no... | true |
d32d3cfd34306257a27952348fa9c647a504ecb1 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/2-DataStructures/dictionaries.py | 1,178 | 4.125 | 4 | # Dictionary :
'''
A Data Type for mutable object that store pairs or mappings of unique keys to values.
'''
elements = {'hydrogen': 1, 'helium': 2, 'carbon': 6 }
elements['lithium']= 3
print("\n\n")
print(elements)
print("\n\n")
# We can also use " in" in dictionaries to check if an element is present.
print("... | true |
dbdc1a6706be097b1727dcfa8d72c3511011dbbd | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/6-iterator-generator/iterator-generator.py | 2,954 | 4.78125 | 5 | import numpy as np
'''
--Iterators And Generators
- Iterables: are objects that can return one of their elements at a time,
such as a list. Many of the built-in functions we’ve used so far,
like 'enumerate,' return an iterator.
- An iterator: is an object that represents a "stream of data".
This is different from ... | true |
8b03d7b5c1edd3313ff972108fa7fc3173cc2a01 | jldroid25/DevOps | /Python_scripting/Review_Python/Foundation/5-Scripting/ScriptingRawInput.py | 571 | 4.3125 | 4 | # -------------Scripting Raw Input ------------------#
#using the input() function
name = input("Enter a name: ")
#print("Welcome come in ", name.title())
# When using the the input() with numbers
# you must include the data type "int()" or "float()" funtion
# else python will throw an error
print('\n')
num = int(... | true |
4445febfb60cfa94adc57d490b02afe4d66c2397 | GaborBakos/codes | /CCI/Arrays_and_Strings_CHP1/1_string_compression.py | 1,037 | 4.375 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters.
EXAMPLE:
Input: aabcccccaaa
Output: a2b1c5a3
If the "compressed" string would not become smaller than the original return the original.
You can assume the string has only uppercase and lowercase... | true |
aff2467f53cb555016ebfd476cec773bbb316f7f | Spandan-Dutta/Snake_Water_Gun_Game | /SNAKE_WATER_GUN_GAME.PY | 2,988 | 4.21875 | 4 | """
So the game is all about that:
1) If you choose Snake and computer choose Gun, you loose as computer shots the snake with a gun.
2) If you choose Gun and computer choose water, you loose as gun is thrown in the water.
3) If you choose Snake and computer choose Water, you wins as Snake drinks the water.
"""
i... | true |
464c3b7fcfd0409dc72f9a238227af789aed4aa0 | Asmithasharon/Python-Programming | /square_root.py | 409 | 4.375 | 4 | '''
To find the square root of a number using newton's method.
'''
def sq_root(number, precision):
sqroot = number
while abs(number - (sqroot * sqroot)) > precision :
#'''abs() is to get the absolute value'''
sqroot = (sqroot + number / sqroot) / 2
return sqroot
number = int(inp... | true |
0425427f405ff360a9b61b66dd26ecfd25f1ba28 | pawnwithn0name/Python-30.03-RaKe | /py_07_04_second/decision_making/if-demo.py | 386 | 4.1875 | 4 | num = float(input("Enter a floating-point: "))
var = int(input("Enter an integer: "))
if num > 100:
print("Numbers entered: {}, {} is greater than 100.".format(num, var))
print("Numbers entered: {1}, {0} is greater than 100.".format(num, var))
print(f"Numbers entered: {num}, {var} is greater than 100.")
... | true |
6829fda3257b5e28f7d54f699bfedabb1ef6da06 | BitanuCS/Python | /College-SemV/10. vehicle class with max_speed and mileage attributes.py | 437 | 4.25 | 4 |
# creat a vehicle class with max_speed and mileage attributes.
class Vehicle:
def __init__(self,max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
print("Max. Speed of your car is: {}\nMileage is: {}".format(max_speed,mileage))
max_speed = float(input("What is the max... | true |
56354c5fcf9292ceaae13f4455af5ec3437d7c5e | pksingh786/BETTER-CALCULATOR | /BETTER CALCULATOR.py | 601 | 4.25 | 4 | #this is a better calculatorin comparison of previous one
first_num=float(input("enter first number:"))
second_num=float(input("enter second number:"))
print("press + for addition")
print("press - for subtraction")
print("press * for Multiplication")
print("press / for division")
input=input("enter the symbol fo... | true |
2b53d5961c27ba0e1144b4eb74065e29bf6e7471 | mochapup/LPTHW | /ex20_SD5.py | 1,078 | 4.28125 | 4 | # Functions and files
# import argv
from sys import argv
# Scripr and argument input
script, input_file = argv
# defining function that prints all of file
def print_all(f):
print(f.read())
# defining a function to rewind to character 0 of file
def rewind(f):
f.seek(0)
# defining a function to print each line s... | true |
e40e0d6fb683e2da5b75fbe9ad8f3385b7ad7617 | alfrash/git_1 | /Pandas/Pandas_1.py | 763 | 4.28125 | 4 | import pandas as pd
groceries = pd.Series(data=[30,6,'yes','no'],index=['eggs', 'apples', 'milk', 'bread'])
print(groceries)
print(groceries.shape)
print(groceries.ndim)
print(groceries.size)
print(groceries.values)
print(groceries.index)
print('banana' in groceries)
# lesson 5 - Accessing and Deleting Elements in P... | true |
9fa1c6ab1f961cce3d2464b1e8079a2bd407c631 | chetangargnitd/Python-Guide-for-Beginners | /Factorial/iterativeFactorial.py | 442 | 4.40625 | 4 | # Python program to find the factorial of a given number
# input the number to find its factorial
num = int(input("Enter a number: "))
factorial = 1
if num < 0: #factorial doesn't exist for a negative number
print("Please enter a valid number!")
elif num == 0: #factorial of 0 is 1
print("The factorial of 0... | true |
63a8f0dfb92e74e4fa574f3048f810823893b820 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch3_stacks_and_queues/bracket_matching_app.py | 1,856 | 4.15625 | 4 | """
Bracket-matching application
----------------------------
- using our stack implementation, verify whether a statement containing brackets --(, [, or {-- is balanced:
whether the number of closing brackets matches the number of opening brackets
- It will also ensure that one pair of brackets really is contained... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.