blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
17ee83f78ffc75ddc60789152a67d32531fff727 | mzanzilla/Python-For-Programmers | /Exceptions/ex1.py | 656 | 4.375 | 4 | #demonstrating how to handle a division by zero exception
while True:
#attempt to convert and divide values
try:
number1 = int(input("Enter numerator: "))
number2 = int(input("Enter denuminator: "))
result = number1 / number2
except ValueError: #Tried to convert non-numeric value to ... | true |
4461ea009cb18cfc2b7167372e5d31c1a8e35c2f | tmemud/Python-Projects | /ex72.py | 1,110 | 4.40625 | 4 | # Use the file name mbox-short.txt as the file name
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
#looking for lines of the form: X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and
#compute the av... | true |
b527e70db8dd5f3cf9afa0047c9a4140cbb94e82 | bkoehler2016/python_projects | /forloop.py | 458 | 4.28125 | 4 | """
a way to print objects in a list
"""
a = ["Jared", 13, "Rebecca", 14, "Brigham", 12, "Jenn", 3, "Ben", 4]
# printing the list using * operator separated
# by space
print("printing the list using * operator separated by space")
print(*a)
# printing the list using * and sep operator
print("printing list... | true |
091ad70053e25fc51ac502a53946d36d96219715 | OctaveC/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 566 | 4.375 | 4 | #!/usr/bin/python3
"""
This is a module that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
def text_indentation(text):
""" This function indents text based on special characters """
if type(text) is not str:
raise TypeError("text must be a string")
leap = T... | true |
183e49a5349c95ef8196ad65754fec65fedf3a35 | Invecklad-py/New_start | /What_is_your_name_input.py | 295 | 4.125 | 4 | first_name = input("What's your first name?")
last_name = input("What's your last name?")
answer = input("So your name is " + first_name + " " + last_name + "?")
if answer == "yes":
print("Great!")
if answer == "no":
print("I'm sorry we got that wrong, please try again")
| true |
104df48126c81aaade444844a5c67c501a98126a | Lumiras/Treehouse-Python-Scripts | /Beginning_python/general_exercises/shopping_list_4.py | 2,236 | 4.125 | 4 | shopping_list = []
def clear_list():
confirm = input("Are you sure you want to completely clear the list?\nThere is no way to undo this!\nType YES to confirm ")
if confirm == 'YES':
del shopping_list[:]
def move_item(idx, mov):
index = idx - 1
item = shopping_list.pop(index - 1)
shopping_l... | true |
04f1caf80aaf3699dfe4e525c7f69909c5a33476 | clarencekwong/CSCA20-B20 | /e4.py | 1,672 | 4.15625 | 4 | import doctest
def average_list(M):
'''(list of list of int) -> list of float
Return a list of floats where each float is the average of the
corresponding list in the given list of lists.
>>> M = [[0,2,1],[4,4],[10,20,40,50]]
>>> average_list(M)
[1.0, 4.0, 30.0]
>>> M = []
>>> average_... | true |
27ff7f866f125b4930facd5f7f28d04e151b0f79 | pinardy/Digital-World | /Week 3/wk3_hw4.py | 622 | 4.21875 | 4 | def isPrime(x):
if x==2:
return True
elif x<2 or x % 2 == 0:
return False
elif x==2:
return True
else:
return all(x % i for i in xrange(2, x))
#all function: Return True if all elements of the iterable are true
#(or if the iterable is empty).
#range returns a Python li... | true |
6435a57030eda2023e17f57b4c127cce9c45163c | TheManTheLegend1/python_Projects | /updateHand.py | 2,062 | 4.1875 | 4 | import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
... | true |
d1dbff287e9541cab7ec2f46958e0990ccc73eb6 | Arya16ap/moneyuyyyyyof.py | /countingWords.py | 403 | 4.125 | 4 | introString = input("enter your introduction: ")
characterCount = 0
wordCount = 1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount = wordCount+1
characterCount = characterCount-1
if(wordCount<5):
print("invalid intro")
print("no. of words in the string: "... | true |
99355b9314b27ebb7d7ec5a4c523cdeaaf3e97fd | NAMELEZS/Python_Programs | /length_function.py | 248 | 4.15625 | 4 | ### 03/28/2021
### Norman Lowery II
### How to find the length of a list
# We can use the len() fucntion to find out how long a list is
birthday_days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
print(len(birthday_days)) | true |
4f247571b9e29902cdfab301b0b2039e6c0e3d3b | lebronjames2008/python-invent | /w3schools/Scopes.py | 799 | 4.375 | 4 | # A variable is only available from inside the region it is created. This is called scope.
def myfunc():
x = 300
print(x)
myfunc()
# A variable created inside a function is available inside that function
x = 300
def myfunc():
print(x)
myfunc()
print(x)
# Printing 2 300's
x = 300
def myfunc():
x = 200
p... | true |
469cf9247ced31818e7060426dfb7f1f67d91ad6 | lebronjames2008/python-invent | /w3schools/Inheritance.py | 1,945 | 4.34375 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
#Use the pass keyword when... | true |
a5a700f7fa77777ea9a3c65669d67f0fd4313dd0 | lebronjames2008/python-invent | /chapter9/testlist1.py | 706 | 4.34375 | 4 | names_list = ['sibi', 'rahul', 'santha', 'scott', 'james']
# print all the elements in the list
print(names_list)
# print the 4th index of the list
print(names_list[4])
print(names_list[-5])
thislist = ["apple", "banana", "cherry"]
print(thislist)
thislist[1] = "blackcurrant"
print(thislist)
thislist = ["apple", ... | true |
71039d8b5847e341112b2194918eebe219589a40 | vlad-zankevich/LearningPython | /album.py | 1,222 | 4.1875 | 4 | def run():
# Theme with function
def make_album(singer_name, album_name, track_number=''):
"""This function will make the dictionary with your album"""
# Album dictionary, empty in default
album = {}
# You can enter quantity of tracks in album if you want
if track_numb... | true |
a900892c18dfd7679221269c3a7d8cfe3a1586a7 | mblahay/blahay_standard_library | /regexp_tools.py | 1,129 | 4.25 | 4 | import re
import itertools
import blahay_standard_library as bsl
def regexp_like(args, argp):
'''
A simple wrapper around the re.search function. The result
of that function will be converted to a binary True/False.
This function will return a simple True or False, no match object.
Parameters... | true |
322747201ef9fe9aa660c5a8831e396266789520 | Santhosh-27/Practice-Programs | /N_day_profit_sell_k_times.py | 1,317 | 4.34375 | 4 | '''
Stock Buy Sell to Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.
For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3.
Again buy on... | true |
095cf2d2b9c6d71f606901fc6c3aef5ab75b0ac7 | bc-townsend/aco_example | /aco_example/path.py | 2,145 | 4.40625 | 4 | import pygame
from math import sqrt
class Path:
"""Represents a path object. These are connections between nodes.
"""
def __init__(self, color, node1, node2):
"""Initialization method for a path object.
Args:
color: The color of this path.
node1: One of the nodes ... | true |
33901933c76acda3b74577e52e989c1e4d4e34a8 | NiteshKumar14/MCA_SEM_1 | /Assignments/OOPs pythonn/synonym_using_existing_dict.py | 1,495 | 4.46875 | 4 | # create an empty my_dictionary
my_my_dict={
"sad":"sure",
"depressed":"Sad",
"Dejected":"Sad",
"Heavy":"Sad",
"Amused":"Happy",
"Delighted":"Happy",
"Pleased":"Happy",
"Annoyed":"Angry",
"Agitated":"Angry",
"Mad":"Angry",
"Determined":"Energized",
"Creative":"Energized",... | true |
b08167b84bd467cc501f5b59165ca3ef8c100f38 | NiteshKumar14/MCA_SEM_1 | /Assignments/OOPs pythonn/happy_sum_of_squares.py | 2,261 | 4.125 | 4 |
def sum_of_squares(sqdnumber): #defining a function that take a string and return its elements sum
sqdNumber_result=0 #initializing sum array for storing sum
iteratator=len(sqdnumber)-1 #iterating till the length of string in desce... | true |
5f5df0b3966bb1a5c613d0c4f6e4f524cee0c742 | freebrains/Python_basics | /Lesson_3.3.py | 580 | 4.3125 | 4 | """
Реализовать функцию my_func(), которая принимает три позиционных
аргумента, и возвращает сумму наибольших двух аргументов.
Implement the my_func () function, which takes three positional
arguments, and returns the sum of the largest two arguments.
"""
def my_func(var_1=int(input("Enter first number - ")), var_2=i... | true |
1d40d049794faa916c6f4a845d138e1b02ae8ef7 | jamilcse13/python-and-flask-udemy | /16. whileLoop.py | 598 | 4.1875 | 4 | count = 0
while count<10:
count += 1
print("count=", count)
print("good bye!")
## while loop else statement
count = 0
while count<10:
print(count, "is less than 10")
count += 1
else:
print(count, "is not less than 10")
print("good bye!")
# single statement suits
flag = 1 #it eill be an in... | true |
6a40da9daeb7b5c96488dd8552caafac2f0e0044 | tedgey/while_loop_exercises | /p_a_s_II.py | 346 | 4.15625 | 4 | # print a square II - user chooses square size
square_size_input = input("How long should the square's sides be? ")
square_size_length = int(square_size_input)
symbol_count = square_size_length * ("*")
counter = 0
while counter < square_size_length:
counter = counter + 1
if counter <= square_size_length:
... | true |
22f7df39cb5e448034c348c6b3587138de937361 | MTDahmer/Portfolio | /hw2.py | 2,972 | 4.28125 | 4 | # File: hw2.py
# Author: Mitchell Dahmer
# Date: 9/18/17
# Section: 503
# E-mail: mtdahmer@tamu.edu
# Description: a program that takes two operands from a user and then modifies them based on the operation given by the user in the form of a string
import math
def main():
firstInteger = int(input("Please... | true |
6d63f96591f210049407b3930d131435727b2dfa | nicodlv99/100-days-of-code | /basics/sequence-types.py | 1,657 | 4.59375 | 5 | #Creating a string
s = "Hello World, how are you doing!" #Creating a string to print
print(s)
s1 = """This is a
line of code
with multiple ines"""
print(s1) #defining a string that contains multiple lines
print(s[0]) #indexing to find the first letter in a word using dictionaries
... | true |
621c0d35b6e0a2ff8fad1f30b74164b30c09115b | kicksmackbyte/project_euler | /p004.py | 589 | 4.3125 | 4 | """
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(i):
str_ = str(i)
if str_ == str_[::-1]:
return True
else:
return False
def main():
num_1 = 999
num_2 = 999
palindromes = []
for i in range(900):
a = 999 - i
... | true |
8faa9ef69ed763164ec130d4a91088df7d30030d | satishraut/inter-prep | /oops/methodOverLoadingAndRiding.py | 799 | 4.125 | 4 | '''
Override means having two methods with the same name but doing different tasks.
It means that one of the methods overrides the other.
Like other languages (for example method overloading in C++) do, python does not supports method overloading.
We may overload the methods but can only use the latest defined meth... | true |
0bf5883db8abc4f19b9fa91778012fc4a0faa28d | pkiuna/CS490-MachineLearning-Python | /ICP2/ICP2.py | 1,350 | 4.15625 | 4 | class employee:
# Members to count employees and find average salary
counter = 0
salary = 0
#contructor to initialize family, salary, department using self
def _init_(self, name, family, salary_num, department):
self.name = name
self.family = family
self.salary_num = salary_... | true |
7e24870e885624f70f0532f545823d73e3a16a1a | annamnatsakanyan/HTI-1-Practical-Group-1-Anna-Mnatsakanyan | /Lecture_6/insertion_sort.py | 345 | 4.15625 | 4 | def insertion_sort(num):
for i in range(1, len(num)):
value_to_insert = num[i]
j = i - 1
while j >= 0 and value_to_insert < num[j]:
num[j + 1], num[j] = num[j], num[j + 1]
j -= 1
numbers = [int(elem) for elem in input("enter the numbers: ").split()]
insertion_sort(n... | true |
26eb512c18e30d70e0a383ca748302bfef9a3681 | samarthgowda96/pycharprojects | /pal.py | 493 | 4.15625 | 4 | string= input("enter the input"+" ")
def isPalindrome(str):
length = len(str)
first = 0
last = length - 1
palindrome = 1
while first < last:
if(str[first] == str[last]):
first = first + 1
last = last - 1
continue
else:
palindrome= 0
... | true |
8b89a4b42869fb143357174fcf98e5c0d50170e8 | srujanprophet/PythonPractice | /11 - Unit 4/4.1.12.py | 407 | 4.1875 | 4 | str = "Global Warming"
print str[-4:]
print str[4:9]
if str.isalpha() == True:
print "It has alphanumeric characters"
else:
print "It does not have alphanumeric characters"
print str.strip("ming")
print str.strip("Glob")
print str.index('Wa')
print str.swapcase()
if str.istitle() == True:
print "It i... | true |
f02ac49567bc1f4089fcc75e4307c397ffc9cdf0 | saurabhpati/python.beginner | /OperatorsAndConditionals/elif.py | 535 | 4.40625 | 4 | # elif keyword is used to make the else if statement in python
# Requirement for this example: User gives the amount.
# 1. If amount is less than 1000, discount is 5%
# 2. If amount is less than (or equal to) 5000, discount is 10%
# 3. If amount is more than 5000, discount is 15%
amount = input('Enter the amount: ');
... | true |
fe5b725a5760c7c55a3aeff33b85cce2aaa6aa5a | saurabhpati/python.beginner | /Lists/list-operations.py | 1,426 | 4.5 | 4 | # iterating over a list.
testList = [1, 2, 3] ;
for x in testList:
print(x, end='\n');
# extend will the given list to the list on which extend is called.
languagesKnownList = ['c#', 'javascript','python'];
languagesKnownList.extend(testList)
print('Languages known and extended:', languagesKnownList);
# appe... | true |
3ec9c0250c484d50af12a557650e415956c1303f | saurabhpati/python.beginner | /OperatorsAndConditionals/arithmetic.py | 287 | 4.3125 | 4 | # This programs intends to highlight between the differences of '/' and '//' operators.
x = input('Enter the dividend: ');
y = input('Enter the divisor: ');
x = int(x);
y = int(y);
print('x/y = ', x/y);
print('x//y = ', x//y);
print('divident raised to the power of divisor = ', x**y); | true |
a0050a3c5375653743e52283756fbe648cb01e62 | kazmanbanj/Practice_on_Python | /file io/script.py | 953 | 4.1875 | 4 | # my_file = open('test.txt')
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# my_file.seek(0)
# print(my_file.read())
# print(my_file.readlines())
# my_file.close()
# Standard way to Read, write, append in python
# with open('test.txt', mode='r+') as my_file:
# print(my_file.readlines()... | true |
c666e839c06a7dcb299706f8fb77bbccf29d1e70 | kb9zzw/arcpy_scripts | /distanceTry.py | 1,012 | 4.1875 | 4 | #Name: distanceTry.py
#Purpose: converts miles to kilometers or vice-versa
#Usage: distanceTry.py <numerical_distance> <distance_unit>
#Example: distanceTry.py 5 miles
#Author: Jon Burroughs (jdburrou)
#Date: 2/16/2012
import sys
# get distance value from user (assume they'll provide it correctly)
dist... | true |
8713d7b1db28ea750666376aecce9231393655bf | PromytheasN/Project_Euler_Solutions_1-10 | /Task 5 Solution.py | 1,201 | 4.1875 | 4 | import numpy
def small_divident():
"""
This is a function that calculates the smallest divident number,
evenly divisable by all numbers between 1 to 20.
"""
#If our number is evenly divisable with the list bellow, it should be evenly divisable with
#1 to 10 as well as all the numbers bell... | true |
afa0a8a76248a73be56eec3d388a23ec11945f96 | anandtakawale/classcodes | /optimizations_sem8/fibonacci.py | 2,787 | 4.15625 | 4 | import texttable
import math
def fibonacciMethod(f, a, b, epsilon):
"""
Returns minima of the function
"""
#calculating number of iterations
fn = (b - a) / epsilon
n = fibFinder(fn)
print n
k = 0
table = texttable.Texttable()
table.add_row(["Iteration", "a", "b", "x1", "x2", "f(... | true |
35cd0814bb7aaedc923c533943637886830c0593 | AshVijay/Leetcode_Python | /496.py | 2,433 | 4.125 | 4 | """
496. Next Greater Element I
Easy
1103
1685
Add to List
Share
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is t... | true |
70ac588cf1ba0c9fd8db5fe5688ed44730e73efe | Tadrop/30_days_of_code | /day9.py | 484 | 4.21875 | 4 | def fibSum(number):
if not isinstance(number,int):
return 'Invalid input, number must be positive integer'
if number == 0 :
return 0
elif number < 0:
return "Invalid, number can't be negative"
elif number > 0:
pass
num =0
a,c=0,1
while c>=number:
... | true |
69c2bc890089754abd6ca0021ba726b2ebe7844b | Abinesh1991/Numpy-tutorial | /NumpyTutorial8.py | 755 | 4.28125 | 4 | """
Python, Numpy and Probability
Random using numpy
"""
import numpy as np
outcome = np.random.randint(1, 7, size=10)
print(outcome)
# generated 5*4 matrix using the random number range from 1 - 7
"""
output:
[[4 4 5 4]
[4 4 5 2]
[3 3 3 4]
[3 5 4 5]
[6 1 2 6]]
"""
print(np.random.randint(1, 7, size=(5, 4)))
#... | true |
409cb01cecf4af685af65480648c49c8efaf57c0 | Abinesh1991/Numpy-tutorial | /NumpyTutorial5.py | 2,239 | 4.1875 | 4 | """
Data type object 'dtype' is an instance of numpy.dtype class. It can be created with numpy.dtype.
"""
import numpy as np
# sample example with int16 data type
i16 = np.dtype(np.int16)
print(i16)
lst = [[3.4, 8.7, 9.9],
[1.1, -7.8, -0.7],
[4.1, 12.3, 4.8]]
A = np.array(lst, dtype=i16)
print(A)
"... | true |
8b57cdcbba3d3c0f7d0203ec3be8e29167c11a8d | Helianus/Python-Exercises | /src/SumOfNumbers.py | 452 | 4.25 | 4 | #Given two integers a and b, which can be positive or negative,
# find the sum of all the numbers between including them too and return it.
# If the two numbers are equal return a or b.
# Note: a and b are not ordered!
def get_sum(a, b):
sum = 0
if a == b:
return a
elif a > b:
for i in ra... | true |
11ef074543b310af32ce9d0b43a2a23111422650 | mor16fsu/bch5884 | /tempconversion.py | 286 | 4.25 | 4 | #!/usr/bin/env python3
#github.com/mor16fsu/bch5884
import math
x=float(input("Please enter a value in degrees Farenheit to convert to degrees Kelvin:"))
print (type (x))
x=float(x)
y=math.floor(x-32)*5/9+273.15
print (y)
print ("The calculation is complete: Degrees Kelvin")
| true |
6db4d82f13ebcf3bb99365d2b8af9ff458ca5961 | puhelan/150 | /1. DS/1.1.py | 1,364 | 4.3125 | 4 | ''' 1.1
_______________________________________________________________________________
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures?
_______________________________________________________________________________
Notes:
1. with hash map... | true |
cdacc8f0adeea4aab139c8bb9d714415fc294c9a | BryceBoley/PythonExercises | /Exercise_2.py | 1,059 | 4.28125 | 4 | # getting user input and checking that it is a number and not zero
gas = input("\nWelcome to the fun conversion tool!\n\nPlease enter a number to represent gallons of gasoline: ")
while not gas.isdigit() or int(gas) == 0:
gas = input("A number you numskull, not a letter or zero!\nEnter your number")
# math for con... | true |
1429b690d10a055ef3dfcdb7fd855470b5c4a310 | Teldrin89/DBPythonTut | /LtP11_custom_exception.py | 991 | 4.15625 | 4 | # it is possible to create a custom exception - it has to be
# inherited from the exception class
# create a new class for handling custom made exception - use
# inheritance of exception build in class
class DogNameError(Exception):
# initialize the class with init function
def __init__(self, *args, **kwargs)... | true |
50b4bc46338d0e7ff766988ea9ed05f565aaa7a0 | Teldrin89/DBPythonTut | /Problem_23.py | 1,445 | 4.28125 | 4 | import re
# Problem 23:
# Use regular expressions to match email addresses
# from the list with set rules for what is an email
# address (just find how many there are):
# 1. 1 to 20 lowercase and uppercase letters, numbers,
# plus ._%+- symbols
# 2. An @ symbol
# 3. 2 to 20 lower case and uppercase letters, numbers... | true |
21c8f84e8b76eff91026f0c155d2a552952b8edb | Teldrin89/DBPythonTut | /LtP13_list_comprehension.py | 1,970 | 4.8125 | 5 | # list comprehension is going to execute an expression
# against an iterable - much as "map" and "filter"
# while a list comprehension is powerful it has to be used
# with cautious to not get overcomplicated
# use different methods to obtain the same list
# of values: multiplication by 2 using map and lc
# a) map
prin... | true |
bc22d61afc37ca167a7550f922397c394f9c4d9a | Teldrin89/DBPythonTut | /Problem17.py | 1,317 | 4.375 | 4 | # Problem 17:
# - create a file named "mydata2.txt" - put any type of data
# - use methods from LtP8 how to open a file without "with"
# (open in "try" block)
# - catch FileNotFoundError
# - in "else" print contents of the file
# - in finally print out some msg that will always be on screen
# - try to open nonexisten... | true |
58684c61c8d6dcecc16fb15542f46ef9a6dcffe0 | Teldrin89/DBPythonTut | /LtP14_threads_example.py | 2,750 | 4.40625 | 4 | # example of threads usage: whenever threads are used
# it is possible to block one of the threads - the
# real world script that can utilize this option
# will cover a modeling of bank account: let's say
# that there is 100$ in the account but there are 3
# different people that can withdraw money from that
# account,... | true |
56ecd290945ebaceecad8e9ea69386558474eb74 | Teldrin89/DBPythonTut | /LtP1.py | 999 | 4.25 | 4 | # Ask the user to input their name and assign
# it to a variable named name
name = input('What is your name ')
# Print out hello followed by the name they entered
print('Hello ', name)
# Ask the user to input 2 values and store them in variables
# num1 and num2
num1, num2 = input('Enter 2 numbers: ').split()
# Co... | true |
45f2072b3cf0ab1858f85048ebf2c1672e904e6c | Teldrin89/DBPythonTut | /LtP6_lists.py | 1,900 | 4.21875 | 4 | import random
import math
# list generated similar as to in problem 11
num_list = []
for i in range(5):
num_list.append(random.randrange(1, 10))
# sorting list
num_list.sort()
# reverse sorting
num_list.reverse()
# change value at specific index -in this example it inserts
# number "10" at index 5
num_list.inser... | true |
33ba04c4c59b0e51ef8f8e5acd62f2cffb9e05bb | AricA05/Python_OOP | /encapsulation.py | 1,480 | 4.34375 | 4 | #4.Encapsulation
'''It is the concept of wrapping data such that the outer world has access only to exposed properties.
Some properties can be hidden to reduce vulnerability.
This is an implementation of data hiding.
For example, you want buy a pair of trousers from an online site.
The data that you want is its cos... | true |
f7c22e308aa4f6903129e8b7d76842ff5c830e14 | dansackett/learning-playground | /project-euler/problem_1.py | 321 | 4.25 | 4 | #!/usr/bin/python
"""
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
limit = 1000
print sum(x for x in xrange(limit) if not x % 3 or not x % 5)... | true |
d01b142a983b9c682f5412d7c504b642fd847cd3 | adimukh1234/python_projects | /hangman1.py | 871 | 4.125 | 4 | import random
name = input("What is your name?\n")
print("Hello ", name)
print("Welcome to the Hangman Game \nBest of luck")
words = ["balloon", "hook", "octopus", "communication", "piano", "honey", "playstation"]
guesses = ''
word = random.choice(words)
print("Guess the characters!")
turns = 6
# main ... | true |
ca8a612e654795d55625e199997945549b713a1c | untalinfo/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 296 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Basic annotations - to string
"""
def to_str(n: float) -> str:
"""takes a float n as argument and returns the string representation
of the float
Args:
n (float): number
Returns:
str: convert float to string
"""
return str(n)
| true |
a16d910dad34c229805ed9875e638a077216b788 | StarTux/DailyCodingProblem | /003-2019-03-07-TreeSerialize.py | 1,154 | 4.125 | 4 | #!/usr/bin/python3
# Problem #3 [Medium]
# Given the root to a binary tree, implement serialize(root),
# which serializes the tree into a string, and deserialize(s),
# which deserializes the string back into the tree.
#
# For example, given the following Node class
class Node:
def __init__(self, val, left=None,... | true |
0aebab530dfa54a10e1d98bd2ba6ad0458f85b2b | jp117/codesignal | /Arcade/Intro/010 - commonCharacterCount.py | 804 | 4.125 | 4 | '''
https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
Input/Output
[execution... | true |
14c11a27484edf19581bca75d54f84ad101b16c0 | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/1-sensitivity.py | 736 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Calculates sensitivity in a confusion matrix
"""
import numpy as np
def sensitivity(confusion):
"""
Calculates the sensitivity for each class in a confusion matrix
Args:
- confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices... | true |
30f5b94defb435a4bb6d98c51b865b46446ef48c | deepika-13-alt/Python-Assignment | /assignment2/second_smallest.py | 1,087 | 4.34375 | 4 | '''
Program: WAP to input 3 numbers and find the second smallest.
'''
import re
# Declarations
regex_float = '[+-]?[0-9]+\.[0-9]+'
regex_int = "[-+]?[0-9]+$"
small_list = []
small_1 = 0
small_2 = 0
# Taking input from users
print("Enter 3 numbers for finding smallest among them")
for i in range(3):
inp = input("... | true |
9ea111f75ba5c9ceb956b78c3ac9f70fdf69540d | tachyonlabs/raspberry_pi_pyladies_presentation | /hello_world_blink.py | 1,566 | 4.28125 | 4 | # See https://github.com/tachyonlabs/raspberry_pi_pyladies_presentation
# for information on the wiring and the presentation in general
# The Rpi.GPIO library makes it easy for your programs to read from and write to
# the Raspberry Pi's GPIO (General Purpose Input/Output) pins
import RPi.GPIO as GPIO
import time
# G... | true |
f4a1d0b9f4725cbb845088e97bf460d1931dc301 | mdeakyne/IT150 | /Blank Class Activities/0119Blank.py | 2,694 | 4.90625 | 5 | """
This assignment is worth 10 points and you should be able to answer the following questions after completing it:
What is the difference between a variable and a literal?
How do you assign variables in python?
How do you deal with errors in python?
What are different types of python variables?
How do you make a mult... | true |
8b0222d0314beb0a3ceb76d601ff1dd7803b8834 | jazywica/Computing | /_01_Interactive_Programming_1/_01_Rock-paper-scissors-lizard-Spock.py | 2,086 | 4.3125 | 4 | """ ROCK-PAPER-SCISSORS-LIZARD-SPOCK - simple game: player vs random computer choice """
# use following link to test the program in 'codeskulptor': http://www.codeskulptor.org/#user45_uPVHROOe6b_2.py
# The key idea of this program is to equate the strings "rock", "paper", "scissors", "lizard", "Spock" to numbers a... | true |
6658a147827c0582c57c8c2cfb644a1342ef51ef | arnaudmiribel/streamlit-extras | /src/streamlit_extras/word_importances/__init__.py | 2,050 | 4.15625 | 4 | from typing import List
import streamlit as st
from .. import extra
@extra
def format_word_importances(words: List[str], importances: List[float]) -> str:
"""Adds a background color to each word based on its importance (float from -1 to 1)
Args:
words (list): List of words
importances (list... | true |
d9760fcbe2c615552887a271c707beb0bc7018b3 | sonyarpita/ptrain | /function_recursive.py | 260 | 4.53125 | 5 | def calc_factorial(x):
"""This is recursive function
to find the factorial of an integer"""
# return(x*calc_factorial(x-1))
if x == 1:
return 1
else:
return (x*calc_factorial(x-1))
num=5
fact=calc_factorial(num)
print("Factorial of",num,"=",fact)
| true |
662ed97b3d686b28c2345a53425b37ffd871055d | sonyarpita/ptrain | /ReModule/Metacharacters/alternation.py | 222 | 4.34375 | 4 | import re
str = "The stays rain in Spain maui falls mainly in the plain!"
#Check if the string contains "falls" or "stays"
x=re.findall("falls|stays",str)
print(x)
if (x):
print("match")
else:
print("No Match")
| true |
8f167f28002b91f926c295843a0131fa194c04b9 | sonyarpita/ptrain | /Advanced_Functions/unzip_1.py | 570 | 4.25 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
pri... | true |
f63386a5b3cb3c829f318691f3e87fb878d4a56a | sonyarpita/ptrain | /ReModule/Metacharacters/Period.py | 235 | 4.125 | 4 | import re
str = "hello world helo"
# search for a sequence that starts with "he", followed by two (any)characters, and an "o"
x=re.findall("he..o", str)
print(x)
x=re.findall("he...o", str)
print(x)
x=re.findall("he.o", str)
print(x)
| true |
3a9d2e9ddcb4ded42e2df4130db0cb1b87e5cf35 | sonyarpita/ptrain | /Advanced_Functions/zip_1.py | 317 | 4.28125 | 4 | #Python code to demonstrate zip()
#initialize lists
name=["Sony","Arpita", "Das","Susmita"]
roll_no=[4,3,6,7]
marks=[90,98,89,99]
#using zip() to map values
mapped=zip(name,roll_no,marks)
#converting values to print as set
mapped=list(mapped)
#printing result values
print("Zipped result is: ",end=" ")
print(mapped)
| true |
bb699c692c649f5a3a6a2a5df0a2ff6b598eb0f2 | dubirajara/learning_python | /add_length.py | 274 | 4.125 | 4 | '''
write a function that takes a String and returns an
list with the length of each word added to each element.
'''
def add_length(words):
return [f'{i} {str(len(i))}' for i in words.split()]
assert add_length('carrot cake') == ['carrot 6', 'cake 4'] # testcase
| true |
66d50bc8acfe3e1a4a3997170fa10f6f00302f07 | kamat-o/MasteringPython | /27_08_2019/AddTwoNumbers.py | 239 | 4.1875 | 4 |
# get the input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
#compute the addition
result = num1 + num2
#print the result
print ("The sum of {0} and {1} is {2}".format(num1,num2,result)) | true |
a65c5f2d60e78fda18111cbf5498d5855d49bfc7 | hina-murdhani/python-project | /pythonProject3/demo/set.py | 1,391 | 4.375 | 4 | # set has no duplicate elements, mutabable
set1 = set()
print(set1)
set1 = set("geeksforgeeks")
print(set1)
string = 'geeksforgeeks'
set1 = set(string)
print(set1)
set1 = set(["geeks", "for", "geeks"])
print(set1)
set1 = set(['1', '2', '3', '4'])
print(set1)
set1 = set([1, 2, 'geeks', 'for', 3, 3])
# add() method is u... | true |
2f4b40b0b435a50c8a59dbb0d3d3eb93cb772e86 | hina-murdhani/python-project | /pythonProject3/demo/array.py | 1,710 | 4.3125 | 4 | import array as arr
# by importing array module we can generate the array
a = arr.array('i', [1, 2, 3])
for i in range(0, 3):
print(a[i])
a = arr.array('d', [1.3, 4.5, 6.7])
for i in range(0, 3):
print(a[i])
# can add element in array using insert():- at any index ,method and append() method : at the end of ... | true |
9dcd641e1b18997ab78e66fdde81c400eecfce7f | DahlitzFlorian/python-training-beginners | /code/solutions/solution_04.py | 263 | 4.40625 | 4 | # This is a possible solution for exercise_04.py
word = input("Enter a word (possible palindrom): ")
reversed_word = word[::-1]
if word == reversed_word:
print("Your submitted word is a palindrom.")
else:
print("Your submitted word is not a palindrom.")
| true |
1a020f32b2a6b3a72571371ca42c2534f816c579 | mr-parikshith/Python | /S05Q02_MaxMinNumber.py | 1,366 | 4.1875 | 4 | """
S05Q02
- Ask the user to enter a number till he enters 0.
Print the maximum and minimum values among all entered numbers.
Print the number of single, two and three digit numbers entered.
"""
def print_CurrentMaxMin(Max, Min):
print("Current Maximum Number is ", Max)
prin... | true |
1163df1cb6c0cad5800a2f74913a90e5d9bbc9d4 | mr-parikshith/Python | /S08Q03_NumberAsString.py | 610 | 4.1875 | 4 | """
S08Q03
Ask the user to enter a number.
- If the user enters a number as 5, then
generate the following string :
- 00001111222233334444
- If the user enters the number as 3, then
generate the following string :
- 001122
"""
def enterNumber():
Number = int(input("Enter Number : "))
while Numbe... | true |
4c11ef1533db7dc7f2dfebe2239878e69d9ec9c4 | mattlorme/python | /coursera/list_8.4.py | 823 | 4.34375 | 4 | #!/usr/bin/python2.7
# 8.4 Open the file romeo.txt and read it line by line.
# For each line, split the line into a list of words
# using the split() function.
# The program should build a list of words.
# For each word on each line
# check to see if the word is already in the list
# and if not append it to the list.
... | true |
21164843eccf32ab55d740847f8990ec306255de | OmniaSalah/CompilerProject | /regex.py | 652 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 23:00:55 2021
@author: LENOVO
"""
import rstr
import re
# ask the user to input the regular expression
regex=input("Enter regex :\n")
# print examples for strings that accepted
print("Examples for regex :\n",rstr.xeger(regex))
# ask the user to input if he want to ... | true |
ac937e2d1d61950723beddbbd3ed6f4f2d5466db | rohegde7/competitive_programming_codes | /Interview-TestPress-Reverse_of_number.py | 839 | 4.1875 | 4 | '''
Given a number N, print reverse of number N.
Note: Do not print leading zeros in output.
For example N = 100 Reverse of N will be 1 not 001.
Input: Input contains a single integer N. Output: Print reverse of integer N.
Constraints: 1<=N<=10000
'''
number = input() #storing the numeber in string fo... | true |
79cba5c7d8c031964a6648c34191448a774f373a | shenoyrahul444/CS-Fundamentals | /Trees/Flatten Binary Trees.py | 1,033 | 4.25 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
# class TreeNode:
# ... | true |
13a9a16ed598e6b2f79f666ad34ae0012064e9dd | ashwin-5g/LPTHW | /ex3.py | 704 | 4.375 | 4 | #prompt for chicken count
print "I will now count my chickens:"
#display hens' count
print "Hens", 25 + 30 / 6
#display roosters' count
print "Roosters", 100 - 25 * 3
% 4
#display eggs' count
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
#comparison operation in use
print "Is it true tha... | true |
90012c431612c0221318d69ee94b8bed263a9736 | Garvit-32/Opencv_code | /15_adaptive_thresholding.py | 775 | 4.125 | 4 | import cv2 as cv
import numpy as np
# Adaptive Thresholding algorithm provide the image in which Threshold values vary over the image as a function of local image characteristics. So Adaptive Thresholding involves two following steps
# (i) Divide image into strips
# (ii) Apply global threshold method to each strip... | true |
a8dbc4ead47024aaae3146f4860fd8930a4f21b4 | cromptonhouse/examplesPi | /hiworld.py | 750 | 4.53125 | 5 | # This is a comment! If we type a # we can type what we want and the computer ignores it!
print "hello world" # prints words, know in code as a string - "Hello World"
# We are going to learn about variables"
# A variable is somewhere (memory) where we can store information"
x = 6 # we have assigned the ... | true |
53d6443c954e116282e4048a560cc1e0650a9df7 | dannydiaz92/MIT_IntroToCS | /Pset2/ps2_hangman.py | 2,974 | 4.375 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending... | true |
801f87165fd8036da1aece5348751af8a68dd685 | Frootloop11/lectures | /week 10/warm_up.py | 576 | 4.28125 | 4 | """
Take in a file
Find and return the longest line in that file
print the line number and length character
"""
def main():
line_number, length = find_longest_line("warm_up.py")
print(line_number, length)
def find_longest_line(file_name):
max_line_number, max_length = -1, 0
with open(file_name, 'r')... | true |
06e6492146dc1e08ca2aa72428d72cb2c59431be | nick-lehmann/SnakeCharmerGuide | /games/ninjas.py | 744 | 4.21875 | 4 | """
The wall has been breached and cobras are attacking the castle 🏰
We see that there are 50 cobras approaching 🐍
Fortunately we have special ninjas that can defeat the cobras 🥷
Every ninja can defeat 3 cobras.
Can we defeat all the cobras with the ninjas we have?
1. Define a variable "ninjas" and one "cobras" and... | true |
78ec49439d956378c5f414bf673cc92f3c3bccda | nick-lehmann/SnakeCharmerGuide | /games/pizza.py | 687 | 4.28125 | 4 | """
Mario is eating a pizza.
The pizza is so tasty that every time he eats a slice he wants to say "Mhhhhhh".
Every time he eats a slice his hunger gets lowered by 1.
If he is full, he stops eating and says "I'm full 🤤"
When he is finished he says "Mamma mia! Buonissima! 😋"
Say if he is still hungry after eating all ... | true |
f93c3a294a435212eceb18e67c5e7c5f86a7e403 | nick-lehmann/SnakeCharmerGuide | /games/rock_paper_scissors.py | 1,841 | 4.40625 | 4 | """
You want to play rock-paper-scissors against the computer.
1. Define a dictionary for each player that stores its name and current score.
2. Ask the player about his or her name and ask how many round should be played.
3. Each round, ask the player for his or her choice. The computer should pick a random choice.
4... | true |
88d46bf4694d95c6f9e62726f88cc21871ccbea6 | Greensahil/CS697 | /Playground/listAndTuples.py | 2,067 | 4.4375 | 4 | #sequence an object that contains multiple items of data
#list is mutable can be changed in place in memory
#tuple cannot be modified unless you are reassigining to a different place in memory
list = [1,2]
print(list)
#list is similar to array list in java
#list is dynamic and we can change the size
#list can be h... | true |
8401ef69843234d30758eecc923f15296cc9b1a3 | Greensahil/CS697 | /Playground/passwordchecker.py | 757 | 4.3125 | 4 | password = input("Enter a string for password:")
validPassword = True
#A password must have at least eight characters.
if len(password) < 8:
validPassword = False
#A password consists of only letters and digits
if not password.isalnum():
validPassword = False
#A password must contain at least two digits
#A p... | true |
5a9cae303fbc660ac7566063f5593a78c263dabf | half-rice/daily_programmer | /easy_challenge_1.py | 699 | 4.21875 | 4 | # create a program that will ask the users name, age, and username. have it
# tell them the information back, in the format:
# your name is (blank), you are (blank) years old, and your username is (blank)
# for extra credit, have the program log this information in a file to be
# accessed later.
file = open("easy_ch... | true |
870430a89fb57bdadf8863b9ee8a43ccd3bff287 | NhatNam-Kyoto/Python-learning | /100 Ex practice/ex8.py | 375 | 4.125 | 4 | '''Write a program that accepts a comma separated sequence of words
as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
'''
inp = input('Nhap c... | true |
a93dd6d0d3929fb5e0004fc9f86ae9703c0a7a60 | Lifefang/python-labs | /CFU07.py | 1,880 | 4.25 | 4 | # By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: Matthew Rodriguez
# Section: 537
# Assignment: CFU-#9
# Date: 10/23/2019
# this... | true |
0311d830fd6398fc5056583cfe1ac83e2b1ea5bf | Lifefang/python-labs | /Lab3_Act1_e.py | 1,031 | 4.25 | 4 | # By submitting this assignment, all team members agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Names: Isaac Chang
# Matthew Rodriguez
# James Phillips
# ... | true |
0e1b7ba647bf813dc211973b5a06720dc2c77eb2 | Lifefang/python-labs | /Lab3_Act1_a.py | 894 | 4.125 | 4 | # By submitting this assignment, all team members agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Names: Isaac Chang
# Matthew Rodriguez
# James Phillips
# ... | true |
41c89e83236a971c90349a0cef1c89753a191993 | lcgarcia05/370-Group5Project | /name/backend_classes/temporary_storage.py | 1,293 | 4.15625 | 4 |
from name.backend_classes.playlist import Playlist
class TemporaryStorage:
""" A class which will handle the temporary storage of a created
playlist and store the list of songs in a text file.
"""
def __init__(self, temp_playlist):
""" Initializes the temp_playlist class and converts playl... | true |
6a350be7b75cc55510365c0992478dea32fabef0 | apatten001/strings_vars_ints_floats | /strings.py | 786 | 4.3125 | 4 |
print('Exercise is a good thing that everyone can benefit from.')
var1 = "This is turning a string into a variable"
print(var1)
# now i'm going to add two strings together
print("I know im going to enjoy coding " + ","+ " especially once I've put the time in to learn.")
# now lets print to add 2 blank lines in be... | true |
d2ad7cfbd2bb9c727dc6e60d38da40a323b3105d | CaseyNord-inc/treehouse | /Write Better Python/docstrings.py | 457 | 4.3125 | 4 | # From Docstrings video in Writing Better Python course.
def does_something(arg):
"""Takes one argument and does something based on type.
If arg is a string, returns arg * 3;
If arg is an int or float, returns arg + 10
"""
if isinstance(arg, (int, float)):
return arg + 10
elif ... | true |
c9b4ec541b0b9ab0f390b6792fe553789c2c3302 | Rrawla2/cs-guided-project-python-i | /src/demonstration_1.py | 1,696 | 4.375 | 4 | """
Define a function that transforms a given string into a new string where the original
string was split into strings of a specified size.
For example:
If the input string was this:
"supercalifragilisticexpialidocious"
and the specified size was 3, then the return string would be:
"sup erc ali fra gil ist ice xpi... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.