blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b2468f3a4cc6e93daeabb9b8fbda27b2049c86ff
avikram553/Basics-of-Python
/string.py
458
4.34375
4
str = 'Hello World!' print(str) # Prints complete string print(str[0]) # Prints first character of the string print(str[2:7]) # Prints characters starting from 3rd to 5th print(str[2:]) # Prints string starting from 3rd character print(str * 2) # Prints string two times print(str + "T...
true
ab9c2b816a1713a162ef9500f7c00927fd2edd9e
luohaha66/MyCode
/python/python_magic_method/repreesent_class.py
2,434
4.4375
4
""" In Python, there’s a few methods that you can implement in your class definition to customize how built in functions that return representations of your class behave __str__(self) Defines behavior for when str() is called on an instance of your class. __repr__(self) Defines behavior for when repr() is called on an...
true
f08ec6439bfbcc2bef9ae906a869c157c60217ca
kjnevin/python
/09.Dictionaries P2/__init__.py
1,231
4.1875
4
fruit = {"Orange": "a sweet, orange citrus fruit", "Apple": "Round fruit used to make cider", "Banana": "Yellow fruit, used to make sandwiches", "Pear": "Wired shaped fruit", "Lime": "a sour green fruit"} # while True: # dict_keys = input("Please enter a piece of fruit:...
true
83813a6fc6389bc8839f0eb52c5f318a9361c819
MunavarHussain/Learning-Python
/Basics/io.py
1,177
4.125
4
''' print() and input() are basic stdio write and read functions respectively. let's see some examples to understand both functions, its usage and capabilities. ''' print('hello world') var = 10 # var is not a keyword in python print('The value of variable var is',var) ''' Output: hello world The value of variable v...
true
b73ae3d97ace11943c5ec19124c0370d840304ac
MunavarHussain/Learning-Python
/OOP/classes_instances.py
1,544
4.1875
4
#Tutorial 1 - Understanding classes and instances '''Object oriented programming is a way of programming, that in its unique way allows us to group data based on objects.It is indeed inspired from real world. In tutorial 1 we'll learn about class and instances. Classes are blueprint associated with some data and func...
true
b4b63b5670446d080a5de26eb6a6944737480559
mjfeigles/technical_interview_practice
/arraysAndStrings/rotate_matrix.py
1,239
4.15625
4
#input: n x n matrix as 2D array #output: the same matrix rotated 90 degrees #Run instructions: #python3 rotate_matrix.py matrix1 # Example matrix1: (can include spaces or not; must be n x n) # [[1, 2], [3, 4]] # [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] import sys import math def matrixRotate(matrix): ...
true
b03687696d732833496fbee14822b706ea6f1aa9
gaurishanker/learn-python-the-hard-way
/ex3.py
675
4.3125
4
#first comment print("I will now count my chickens:") #counting hens print("Hens", 25 + 30 / 6) print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs:") #an expression it will be evaluated as first 1/4 = 0.25 then from left to write # poit to note 1 + 4 % 2 is 1. print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6...
true
f975cdbc75ee254825989d79556328ab5b7c9ae5
19sblanco/cs1-projects
/futureDay.py
2,310
4.4375
4
''' requirement specification: have user play a game of rock paper scissors against a 'random' computer ''' ''' system anaysis: user inputs ''' ''' system design: 1. have user input 0, 1, or 2 (represents scissor, rock and paper) respectively 2. store number 1 as value 3. have computer randomly choose number between...
true
aaf71b8b743424126b75802724ea47942bfa7df6
LibbyExley/python-challenges
/FizzBuzz.py
492
4.1875
4
""" Write a program that prints the numbers from 1 to 100. If it’s a multiple of 3, it should print “Fizz”. If it’s a multiple of 5, it should print “Buzz”. If it’s a multiple of 3 and 5, it should print “Fizz Buzz”. """ numbers = list(range(1,101)) for number in numbers: if number % 5 == 0 and number % 3 == 0: ...
true
2895873d8b4e03ecd2a78284ab1978ee1725673f
MudassirASD/darshita..bheda
/.py
261
4.21875
4
n=int(input("Enter a number:")) if n>0: print("The number is positive") elif n<0: print("The number is negative:") else: print("The number is zero") def n=int(input("Enter the 1st integer:")) m=int(input("Enter the 2nd integer:"))
true
8397c08437aedea80cd0ee729f98c9ffcbd17648
bradandre/Python-Projects
/College/Homework Programs/November 25th/One.py
899
4.375
4
#Initial list creation colors = ["red", "black", "orange"] #Appending new items to the list for c in ("yellow", "green", "blue", "indigo", "violet"): colors.append(c) #Removing the color black from the list colors.remove("black") #Outputting the third element print("Third element: {0}".format(colors[2])) #Outputti...
true
54678d9ea9aa057adc9cb30b354902ee1905e203
sokhij3/210CT-Coursework
/Question 10.py
1,249
4.21875
4
#Q - Given a sequence of n integer numbers, extract the sub-sequence of maximum length # which is in ascending order. l = input("Please input a list of integers: ") lis = list(map(int, l)) #map() function makes each iterable in the list lis an int def ascendingOrder(lis): temp = [] maxSeq = [0] ...
true
53e4a8503866e93d0895a1d012f2bedc6855803e
munikarmanish/cse5311
/algorithms/min_spanning_tree/prim.py
768
4.1875
4
""" Implementation of the Prim's algorithm to find the minimum spanning tree (MST) of a graph. """ from data_structures.heap import Heap def prim(G, root=None): """ Find the minimim spanning tree of a graph using Prim's algorithm. If root is given, use it as the starting node. """ nodes = Heap([(...
true
e4c25b4bf3e65511806a091af990dd9d6608b66f
Steven98788/Ch.08_Lists_Strings
/8.3_Adventure.py
2,609
4.21875
4
''' ADVENTURE PROGRAM ----------------- 1.) Use the pseudo-code on the website to help you set up the basic move through the house program 2.) Print off a physical map for players to use with your program 3.) Expand your program to make it a real adventure game ''' room_list=[] current_room=0 inventory = [] done= Fals...
true
8139cd54762564ee4824367d4a1c96ff0a199c1c
thread13/shpy-1
/demo00.py
612
4.1875
4
#!/usr/bin/python2.7 -u import sys # prints range between first two args and points at third arg if in range a = sys.argv[1] b = sys.argv[2] c = sys.argv[3] if (int(a) < int(b)): while (int(a) <= int(b)): # range up if (int(a) == int(c)): print str(a) + ' <<' else: ...
true
edfa5113c29949ee7567d472fc85021e395f8a13
SKVollala/PYTHON_REPO
/experienceCalc.py
717
4.25
4
""" This program calculates the age/experience in years, months, and days format Input: Asks the user to enter a date in YYYY-MM-DD format Output: Calculates and prints the experience in years, months, and days """ from datetime import date from dateutil.relativedelta import relativedelta def ...
true
6b99166a38563d7948c26b2fd571879a84c86b0b
mindnhand/Learning-Python-5th
/Chapter17.Scopes/nested_default_lambda.py
756
4.15625
4
#!/usr/bin/env python3 #encoding=utf-8 #------------------------------------------ # Usage: python3 nested_default_lambda.py # Description: nested scope and default argument #------------------------------------------ # nested scope rules def func(): # it works because of the nested scop...
true
835a6fde6e06b9253e64d2cdc22108df356abd07
mindnhand/Learning-Python-5th
/Chapter34.ExceptionCodingDetails/2-try-finally.py
1,169
4.15625
4
#!/usr/bin/env python3 #encoding=utf-8 #--------------------------------------- # Usage: python3 2-try_finally.py # Description: try-finally to do some cleanup jobs #--------------------------------------- ''' When the function in this code raises its exception, the control flow jumps back and runs the finally bl...
true
e5b34e73ebee7acbfda4bfab71c5dbaf4e039943
mindnhand/Learning-Python-5th
/Chapter31.DesigningWithClasses/converters.py
2,457
4.21875
4
#!/usr/bin/env python3 #encoding=utf-8 #--------------------------------------------- # Usage: python3 converters.py # Description: compostion and inheritance #--------------------------------------------- from streams import Processor class Uppercase(Processor): def converter(self, data): return da...
true
35739c614d955ff51bc8013a63450ae242870584
godsonezeaka/Repository
/PythonApp/stringFunctions.py
854
4.375
4
# String functions myStr = 'HelloWorld' # Capitalize print(myStr.capitalize()) # Swap case print(myStr.swapcase()) # Get length print(len(myStr)) # Replace print(myStr.replace('World', 'Everyone')) #Count - allows you to count the number of occurrences of a substring in a given string sub = 'l' print(myStr.count(...
true
cfb42c8f3dfa6aa9368953c40094f8c436986b17
NAKO41/Classes
/Classes practice pt 1.py
1,082
4.125
4
class FireBall(object): #this is the class object #it will be used to track weather an attack hits or not def __init__(self): #each ball will start at (0,0) self.y = 0 self.x = 0 def move_forward(self): self.x += 1 #create a fireball and make it move forward fire_ba...
true
811aef10c87431213551ed5bbe44a23d8957029e
summerfang/study
/collatzconjecture/collatz_recursion.py
911
4.375
4
# 3n + 1 problem is also called Collatz Conjecture. Please refer to https://en.wikipedia.org/wiki/Collatz_conjecture # Giving any positive integer, return the sequence according to Collatz Conjecture. collatzconjecture_list = list() def collatzconjecture(i): if i == 1: collatzconjecture_list.append(i) ...
true
1cdd49fcc31773c4ca758c91c36ffa87841d184e
unins/K-Mooc
/package_i/calc_rectangular_area.py
629
4.1875
4
def choice(): shape = int(input("type in shape(rectangle = 1, triangle = 2, circle = 3)")) if shape == 1: weight = int(input("\ntype in Rectangle Weight:")) height = int(input("type in Rectangle Height :")) return print(("Rectangle area is %d") %(weight*height)) elif shape == 2: weight = int(input("\ntype in...
true
8f4073779fbac7eed417ef5880e49c2d7093824e
addison-hill/CS-Build-Week-2
/LeetCode/DecodeString.py
2,131
4.125
4
""" Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, squar...
true
a72db85874ec2f1bf62b9407487068709f9ef8f1
Lawren123/Randomfiles
/Chatbot2.py
2,866
4.1875
4
# --- Define your functions below! --- # The chatbot introduces itself and gives the user instructions. def intro(): print("Hi, my name is Phyllis. Let's talk!") print("Type something and hit enter.") # Choose a response based on the user's input. def process_input(answer): # Define a list of possible ...
true
84bbbf8888bd5646f892d1e3fc700a103c797721
fer77/OSSU-CS-Curriculum
/intro-cs-python/week1-2/pset1/problem-3.py
821
4.375
4
''' Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first subst...
true
93b861ca4f92a3184cb02bc29d0267c3aa15cb43
bartoszmaleta/3rd-Self-instructed-week
/loop control statements/while/Loop_control_statements.py
443
4.375
4
# Here is a simple Python example which adds the first ten integers together: total = 0 i = 1 while i <= 10: total += i print(total) i += 1 print('\n-------------------------------------------- ') # numbers is a list of numbers -- we don't know what the numbers are! numbers = [1, 5, 2, 12, 14, 7, 18, 30,...
true
5f5cf8bcf373e898279ee54dd5ed10fb52383ba7
bartoszmaleta/3rd-Self-instructed-week
/sorting/sorting_how_ to/lambda_expressions.py
971
4.5625
5
# Small anonymous functions can be created with the lambda keyword. # This function returns the sum of its two arguments: lambda a, b: a+b. # Lambda functions can be used wherever function objects are required. # They are syntactically restricted to a single expression. # Semantically, they are just syntactic sugar...
true
457bf2de01c95c82b3febd7eae03b35b48042cce
bartoszmaleta/3rd-Self-instructed-week
/functions/exe4 - return_values.py
564
4.25
4
def calculate_the_factorial_of_a_given_number(given_number_str): given_number = int(given_number_str) # total = 1 # given_number = 5 # i = 0 if given_number <= 0: print("Wrong number. ") if given_number == 1: return 1 # for given_number in range(1, given_number + 1)...
true
213e2dde435c17a0c6484cfc867ebf38d1ba6cf0
bartoszmaleta/3rd-Self-instructed-week
/Working with Dictionaries, and more Collection types/ranges/ranges.py
629
4.65625
5
# print the integers from 0 to 9 print(list(range(10))) # print the integers from 1 to 10 print(list(range(1, 11))) # print the odd integers from 1 to 10 print(list(range(1, 11, 2))) # We create a range by calling the range function. As you can see, if we pass a single parameter to the range function, # it is used a...
true
1183206db30f71bffd121a93b3ebcd5a1ced07cd
kristinbrooks/lpthw
/src/ex19.py
1,032
4.15625
4
# defines the function. names it & defines its arguments. then indent what will be done when the function is called def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a pa...
true
20dd021a971a341e22644431916fc1fed06763e5
mousaayoubi/lens_slice
/script.py
656
4.34375
4
#Create toppings list toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"] #Create prices list prices = [2, 6, 1, 3, 2, 7, 2] #Length of toppings num_pizzas = len(toppings) print("We sell "+str(num_pizzas)+" different kinds of pizza!") #Combine price list with toppings list...
true
27affa01e14c441390538e60af25253600082d9b
tommydo89/CTCI
/17. Hard Problems/circusTower.py
1,277
4.125
4
# A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter # than the person below him or her. Given the heights and weights of each person in the circus, write # a method to compute the largest po...
true
24185973d76ecf62fa816c7b2dbeb52cc89397c7
tommydo89/CTCI
/16. Moderate Problems/pondSizes.py
1,797
4.28125
4
# You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of # water connected vertically, horizontally, or diagonally. The size of the pond is the total number of # connected water cells. Write a...
true
17a49eb54c369a43f2c3445b291be65936677273
tommydo89/CTCI
/2. Linked Lists/palindrome.py
1,058
4.3125
4
# Implement a function to check if a linked list is a palindrome. class Node: def __init__(self, val): self.val = val self.next = None Node1 = Node(1) Node2 = Node(0) Node3 = Node(1) Node1.next = Node2 Node2.next = Node3 # def palindrome(node): # reversed_LL = palindrome_recursion(node) # while (reversed_LL...
true
ce2a5c7371177bd7c44bfc1f77c802afe5d37f87
tommydo89/CTCI
/5. Bit Manipulation/insertion.py
863
4.21875
4
# You are given two 32-bit numbers, N and M, and two bit positions, i and # j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You # can assume that the bits j through i have enough space to fit all of M. That is, if # M = 10011, you can assume that there are at least 5 bits between j a...
true
8174667c3319d5a75b118e31a583ae58330b3100
tommydo89/CTCI
/1. Arrays/URLify.py
435
4.15625
4
# Write a method to replace all spaces in a string with '%20'. You may assume that the string # has sufficient space at the end to hold the additional characters, and that you are given the "true" # length of the string. (Note: If implementing in Java, please use a character array so that you can # perform this operati...
true
5bc76b5c51d6ad868f36e0a0cde6c7f4c9cceb14
jdingus/discount_calculator
/discount_calculator.py
847
4.25
4
def calculate_discount(item_cost, relative_discount, absolute_discount): """ Calculate the discount price of an item in the shopping cart, First relative_discount is applied then absolute_discount is applied, final purchase price is the then returned (price) """ if relative_discount > 1. or absolute_discount > 1:...
true
26362fcee2e89a58574c3d9dc68cff945d8c776a
JacobWashington/python_scripting_food_sales
/my_script.py
1,850
4.28125
4
# Read only def read_only(): ''' a method that only reads the file ''' try: file1 = open('data.txt') text = file1.read() print(text) file1.close() # the reason for closing, is to prevent a file from remaining open in memory except FileNotFoundError: text = None ...
true
ac4a60ec2e36e3595babfe3c7c9a452f947651da
achan90/python3-hardway
/exercises/ex16.py
1,246
4.25
4
# Start import string. from sys import argv # Unpack argv to variables. script, filename = argv # Print the string, format variable in as raw. print("We're going to erase {}".format(filename)) # Print the string. print("If you don't want that, hit CTRL-C.") print("If you do want that, hit ENTER") # Prompt for user i...
true
bff642d35d826ab6371374cf15a997e00b0581f3
Sean-McLeod/ICS3U-Unit2-01-Python
/area_of_circle.py
456
4.21875
4
#!/usr/bin/env python3 # Created by Sean McLeod # Created on November 2020 # This program can calculate the area and perimeter of a circle with # a radius of 15mm import math def main(): # This function calculates the area and perimeter of a circle print("If a circle has a radius of 15mm:") print("") ...
true
0b98f43b8373fd1ed68230a9cf8c39073d6a9593
ChadDiaz/CS-masterdoc
/1.2 Data Structures & Algorithms/Number Bases and Character Encoding/ReverseIntegerBits.py
538
4.3125
4
""" Given an integer, write a function that reverses the bits (in binary) and returns the integer result. Examples: csReverseIntegerBits(417) -> 267 417 in binary is 110100001. Reversing the binary is 100001011, which is 267 in decimal. csReverseIntegerBits(267) -> 417 csReverseIntegerBits(0) -> 0 Notes: The input inte...
true
81918ebc623dc5f056379388da9217097124c330
ChadDiaz/CS-masterdoc
/1.1/Python II/schoolYearsAndGroups.py
992
4.1875
4
''' Imagine a school that children attend for years. In each year, there are a certain number of groups started, marked with the letters. So if years = 7 and groups = 4For the first year, the groups are 1a, 1b, 1c, 1d, and for the last year, the groups are 7a, 7b, 7c, 7d. Write a function that returns the groups in t...
true
e4ca5ef5250917fcc4df116e3e79a65ea6a6d14b
thanuganesh/thanuganeshtestprojects
/iterables.py
2,176
4.28125
4
"""This function helps to learn about iterables""" #List is iterable but not iterator #iterable somthing can be looped over becaz we can loop over list #how we can say some thing is iterable???? #__iter__() method in iterable then its called iterable #iterator is object with the state it rembers where its during...
true
27c34eafa416a0ada55670ee72004ad292e33a39
csankaraiah/cousera_python_class
/Python_Assignment/Ch6Strings/ex6_3.py
292
4.15625
4
def count_word(word, ch): count = 0 for letter in word: if letter == ch: count = count + 1 return count word_in = raw_input("Enter the word: ") ch_in = raw_input("Enter the character you want to count: ") count_ch = count_word(word_in, ch_in) print count_ch
true
a9dcb63a962456b3ec45766a3a990135405d7aa7
premsub/learningpython
/learndict.py
567
4.34375
4
# This program is a learning exercise for dictionaries in perl # Parse through a dict and print months = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } # print "Enter month>" # month=raw_inp...
true
b726154fcdd333f51421a3cc44c9c2aa45cca490
serenityd/Coursera-Code
/ex1/computeCost.py
644
4.3125
4
import numpy as np def computeCost(X, y, theta): """ computes the cost of using theta as the parameter for linear regression to fit the data points in X and y """ theta=np.mat(theta).T X=np.mat(X) y=np.mat(y) m = y.size print(X.shape,y.shape,theta.shape) # =================...
true
836e33d711e3f67a14a887a30b464976530ff6d3
selmansem/pycourse
/variables.py
1,436
4.125
4
# import only system from os from os import system, name # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # now call function we defined above clear() ##################...
true
1e7f8506a5038e42ffe5180d196af4b7e11fb44c
selmansem/pycourse
/numbers.py
1,247
4.21875
4
# import only system from os from os import system, name # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # now call function we defined above clear() ##################...
true
ece2157471c376a950e06a08cf7cd945ff0c8873
Tezameru/scripts
/python/pythoncrashcourse/0015_seeing-the-world.py
2,051
4.84375
5
# Seeing the World: Think of at least five places in the world you’d like to # visit. Store the locations in a list. Make sure the list is not in alphabetical order. countries = ['Paraguay', 'France', 'Greece', 'Italy', 'Sweden'] # Print your list in its original order. Don’t worry about printing the list neatly, # ju...
true
bfac445de754be4667af5ad4566787a099019e11
frankShih/LeetCodePractice
/sorting_practice/insertionSort.py
443
4.15625
4
def insertion_sort(InputList): # from head to tail for i in range(1, len(InputList)): j = i curr = InputList[i] # move current element to sorted position (at left part of list) while (InputList[j-1] > curr) and (j >= 1): InputList[j] = InputList[j-1] ...
true
13468e46256ebf8586a4a49c1b29674bcff52754
lingyenlee/MIT6.0001-Intro-to-CS
/ps1b.py
880
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 9 09:54:12 2019 @author: apple """ annual_salary = float(input("Enter your annual salary:")) semi_annual_raise = float(input("Enter your raise as decimal:")) portion_saved = float(input("Enter the portion saved:")) total_cost = float(input("Enter ...
true
b969117ca7174c1f3f77d2422f64a41fa6dcd8e4
Goldabj/IntroToProgramming
/Session03_LoopsAndUsingObjects/src/m1e_using_objects_and_zellegraphics.py
2,391
4.34375
4
""" This module uses ZELLEGRAPHICS to demonstrate: -- CONSTRUCTING objects, -- applying METHODS to them, and -- accessing their DATA via INSTANCE VARIABLES (aka FIELDS). Authors: David Mutchler, Amanda Stouder, Chandan Rupakheti, Katie Dion, Claude Anderson, Delvin Defoe, Curt Clifton, Matt Boutell, ...
true
faba8af94dda061f2acc45742658108fc0c5cf7e
ClemXIX/Solo_Learn_Courses
/Python/Beginner/23.2_Leap_Year.py
978
4.5625
5
""" else Statement You need to make a program to take a year as input and output "Leap year" if it’s a leap year, and "Not a leap year", if it’s not. To check whether a year is a leap year or not, you need to check the following: 1) If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT leap ...
true
d760adfa1d6c6444b0f6c36f6ea35f7904806589
ClemXIX/Solo_Learn_Courses
/Python/Beginner/20_Tip_Calculator.py
554
4.28125
4
""" Tip Calculator When you go out to eat, you always tip 20% of the bill amount. But who’s got the time to calculate the right tip amount every time? Not you that’s for sure! You’re making a program to calculate tips and save some time. Your program needs to take the bill amount as input and output the tip as a flo...
true
f9c5686400afa04ea29ec2e217f18e027857f7c2
ClemXIX/Solo_Learn_Courses
/Python/Intermediate/2 Functional Programming/12.2_How_Much.py
499
4.125
4
""" Lambda You are given code that should calculate the corresponding percentage of a price. Somebody wrote a lambda function to accomplish that, however the lambda is wrong. Fix the code to output the given percentage of the price. Sample Input 50 10 Sample Output 5.0 The first input is the price, while the second...
true
2054b0c9ca187bd13b6e9fc5829e6a63d3136f5b
ClemXIX/Solo_Learn_Courses
/Python/Core_Course/2_Strings_Variables/09.2_More_Lines_More_Better.py
366
4.21875
4
""" Newlines in Strings Working with strings is an essential programming skill. Task: The given code outputs A B C D (each letter is separated by a space). Modify the code to output each letter on a separate line, resulting in the following output: A B C D Consult the Python Strings lesson if you do not remember the...
true
491c6db30d4724556b9f0376b6b291aae9283585
pranav1214/Python-practice
/lec3/p9.py
315
4.21875
4
# to read a string and count the number of letters, #digits and other s1 = input("Enter a string: ") lc, dc, oc = 0, 0, 0 for s in s1: if (('A' <= s <= 'Z') or ('a' <= s <= 'z')): lc = lc + 1 elif ('0' <= s <= '9'): dc = dc + 1 else: oc = oc + 1 print("Letters: ", lc, "Digits: ", dc, "Other: ", oc)
true
01712f7719db69bd26adfd8372710cf9d38c15dc
DunnBC22/BasicPythonProjects
/PlayingWithNumbers.py
1,067
4.28125
4
import math ''' Take a number that is inputted and split it into 2s and 3s (maximize the number of 3s first). Take those numbers and multiply them together to get the maximum product of the values. ''' def defineNumber(): number = input('Please enter a number ') try: (isinstance(type(number), int)) ...
true
5f77ed8ab840fc2a8bb9280eb2ee7d2652c52738
tom1mol/python-fundamentals
/dictionaries/dictionaries1.py
1,050
4.71875
5
# Provides with a means of storing data in a more meaningful way # Sometimes we need a more structured way of storing our information in a collection. To do this, we use dictionaries # Dictionaries allow us to take things a step further when it comes to storing information in a collection. Dictionaries # will enable ...
true
6e384bb841ec5c2e5ba365ea1d9082546f9744ac
tom1mol/python-fundamentals
/there-and-back-again/while-loops1.py
1,798
4.5
4
countdown_number = 10 print("Initiating Countdown Sequence...") print("Lift Off Will Commence In...") while countdown_number >= 0: print("%s seconds..." % countdown_number) countdown_number -= 1 print("And We Have Lift Off!") # In this example we declare a variable called countdown_number, then we proceed ...
true
be03930099432c1f744dbf25cd4708564f318e6a
tom1mol/python-fundamentals
/break_and_continue/99bottles.py
1,953
4.375
4
for number in range(99, 0, -1): line_one = "{0} bottle(s) of beer on the wall. {0} bottle(s) of beer" line_two = "Take one down, pass it around. {0} bottle(s) of beer on the wall\n" print(line_one.format(number)) print(line_two.format(number - 1)) # OUTPUT: # Python 3.6.1 (default, Dec 2...
true
055730012920bf3dd282d898c5a67358c20b8d04
tom1mol/python-fundamentals
/there-and-back-again/range1.py
1,241
4.78125
5
for item in range(5): print(item) # OUTPUT: # Python 3.6.1 (default, Dec 2015, 13:05:11) # [GCC 4.8.2] on linux # 0 # 1 # 2 # 3 # 4 # NOTES: # Instead of just starting from 0, we can use additional arguments to achieve various sequence combinations. # We know this by looking at the Pytho...
true
b1d992f84b5be48b7acc1ca7490f5119d688b6cd
tom1mol/python-fundamentals
/mutability-and-immutability/mutability-and-immutability3.py
753
4.4375
4
# Tuples, however, are not mutable, meaning that they cannot be changed or modified and have a fixed size # and fixed values. Therefore if we create a tuple containing two items, then it will always have two items. # It cannot be changed. If we wanted to use the del keyword on an item in a tuple, then Python will com...
true
5769f5662f13e5393432a3ca24319a8d90400900
tho-hoffmann/100DaysOfCode
/Day007/Challenges/ch01.py
837
4.3125
4
#Step 1 word_list = ["aardvark", "baboon", "camel"] #TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. import random chosen_word = random.choice(word_list) #TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowerca...
true
1513dc748e97fa9529d7dff58b535f75305b7f74
Apekshahande/Python_small_project
/rockpapergame.py
2,386
4.21875
4
from random import randint def win():# def is pree difine keyword. win is variable name and we pass the prameter inside the parenteses. print ('You win!') # return ('You win!')# if we are returen the function then i have to print this function when i will pass then argument. def lose():# def is pree dif...
true
745e2bb0bbd2a55e7f49c0c788ec1fc8a0d4a0eb
ballib/Forritun1
/assignment 9 (files and exceptions)/dæmi3.py
562
4.28125
4
def open_file(filename): file_object = open(filename, "r") return file_object def longest(file_object): longest_word = '' count = 0 for word in file_object: strip = word.strip().replace(' ', '') if len(strip) > len(longest_word): longest_word = strip count +=...
true
5290553652abe667784a4526453b6e958b1990c4
AndrewShmorhunGit/py-learning
/builtin/decorator_fn.py
2,241
4.375
4
""" Decorators with or without arguments """ import functools def decorator1(fn_or_dec_arg): """ Simplest variant - No need to use named args for decorator - Different wrapper's for decorator with and without arguments - Decorator argument can't be a function """ if callable(fn_or_dec_arg...
true
f9036151afb3f796786f8aefbcff7e35f6da31a7
h15200/notes
/python/fundamentals.py
573
4.125
4
# using args in for loops <starting, ending, increment> for i in ["a", "b"]: print(i) # prints the actual List items nums = [10, 20, 30] for i in range(len(nums) - 1, -1, -1): print("item is", nums[i]) # input, string template literal with `f` for formatted string literal # try/except dangerous blocks of c...
true
3cea8b8c4d009cf5d049d3df9fb40d2308e7cb1c
cuber-it/aktueller-kurs
/Archiv/Tag1/01_list_tuple_set.py
852
4.53125
5
# Create a list, a tuple, and a set with the same elements my_list = [1, 2, 3, 3, 4, 5] my_tuple = (1, 2, 3, 3, 4, 5) my_set = {1, 2, 3, 3, 4, 5} # Print the elements in each data structure print("List:") for x in my_list: print(x) print("Tuple:") for x in my_tuple: print(x) print("Set:") for x in my_set: ...
true
10122b6e8d395d9817ccd9fc9c26597ead045439
cuber-it/aktueller-kurs
/Archiv/Tag1/02_comprehensions.py
1,216
4.125
4
# Creating a list of squares of numbers 0 to 9 squares = [x**2 for x in range(10)] print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Creating a list of even numbers from another list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [x for x in numbers if x % 2 == 0] print(evens) # Output: [2, 4, 6, 8,...
true
eb8e8072b9526941522dbb22e789573ee8106474
faizan2sheikh/PythonPracticeSets
/sem2set2/Q11.py
2,014
4.46875
4
# 11. In ocean navigation, locations are measured in degrees and minutes of latitude and longitude. Thus if you’re lying off # the mouth of Papeete Harbor in Tahiti, your location is 149 degrees 34.8 minutes west longitude, and 17 degrees 31.5 # minutes south latitude. This is written as 149°34.8’ W, 17°31.5’ S. Ther...
true
d686267126f4b318cb3620df49471f49e0959099
faizan2sheikh/PythonPracticeSets
/sem2set2/Q10.py
1,057
4.375
4
# Write code to create a class called Time that has separate member data for hours, minutes, and seconds. Make # constructor to initialize these attributes, with 0 being the default value. Add a method to display time in 11:59:59 # format. Add another method addTime which takes one argument of Time type and add this ...
true
6f02dbdbbf180593ebfcbc4b8c14d870485491df
deejayM/wagtail_sb_goals
/sb_goals/lib/shared-lib/calendar.py
1,119
4.34375
4
import datetime def days_in_month(year, month): """ Inputs: year - an integer between datetime.MINYEAR and datetime.MAXYEAR representing the year month - an integer between 1 and 12 representing the month Returns: The number of days in the input month. """ #if mont...
true
749d231fdbeeeb0f6b02aac9f9976263baaaffe5
ashish8796/Codewars
/python-kata/count_smiley_faces.py
633
4.15625
4
''' Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Valid smiley face examples: :) :D ;-D :~) Invalid smiley faces: ;( :> :} :] ''' arr = [':D',':~)',';~D',':)'] def count_smileys(arr): symb = [[':', ';'], ['-', '~',')', 'D']] count...
true
86dc1856142f81e6d7eef77ef5baae3b51d080e7
ashish8796/Codewars
/python-kata/head_at_wrong_end.py
675
4.28125
4
''' You're at the zoo... all the meerkats look weird. Something has gone terribly wrong - someone has gone and switched their heads and tails around! Save the animals by switching them back. You will be given an array which will have three values (tail, body, head). It is your job to re-arrange the array so that the...
true
c6826de606a4ee7e9bf17c40057a0b9eda0ea76a
imolina218/Practica
/Modulo01/Parte_04_02_products_bill.py
1,752
4.46875
4
# Create a program that have a list of products by code. # Then the user can choose the product and the amount, the option to choose more than # one product needs to be available. # Once the user doesn't want to enter any more products the program will print the # bill with all the product/s and the quantity d...
true
7493f14ffb26d3fdeea0cb65a822ac7609cd3295
yshshrm/Algorithms-And-Data-Structures
/python/Sorts/quick_sort.py
920
4.15625
4
# Implementation of Quick Sort in Python # Last Edited 10/21/17 (implemented qsort_firstE(arr)) # Worst case performance: O(n^2) # Average performance: O(nlogn) # In this first implementation of quick sort, the choice of pivot # is always the first element in the array, namely arr[0] def qsort_firstE(arr): # if th...
true
5d53368ee0c009da195721291844f7f7ae592799
sonikku10/primes
/primes.py
509
4.34375
4
import math #Import the math module def is_prime(num): ''' This function will determine whether a given integer is prime or not. Input: An integer. Output: True/False Statement :param num: :return: ''' if num % 2 == 0 and num > 2: #All even numbers greater than 2 are not prime. ...
true
ff085804195df8c213d1a4b6571b6256ccfaa110
KaraKala1427/python_labs
/task 2/53.py
339
4.125
4
rate = float(input("Enter the rating : ")) if rate == 0: print("Unacceptable performance") elif rate>0 and rate<0.4 or rate>0.4 and rate<0.6: print("Error") elif rate == 0.4: print("Acceptable performance", "Employee's raise= $", 2400*0.4) elif rate >= 0.6: print("Meritorious performance", "Employee's r...
true
f27357315751de19f22270227e3c3bb73c9f977c
oliverschwartz/leet
/longest_univalue_path/longest_univalue_path.py
1,070
4.125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: if not root: return 0 self.global_max = 0 def long...
true
5e265310ffb378751e71d486f0f94416c12372ba
OSL303560/Parenitics
/Source codes/Beginning.py
1,976
4.15625
4
import time from os import system temp = 0 def startstory(): print("In February 2019, ", end = "") time.sleep(1) print("the Hong Kong government proposed the ") time.sleep(0.5) print("\nFugitive Offenders and Mutual legal Assistance in Criminal Matters Legislation (Amendment) Bill 2019.") ...
true
190f6a92cad55fa3b8ca1f757f8b6c42eac5f13d
PhilipMottershead/Practice-Python
/Tutorials/Exercise 13 - Fibonacci.py
656
4.4375
4
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. starting_number = [1] def next_number(num): if num == 1 or...
true
cca82bcf32c9f686707d821e20d7232e978d6624
PhilipMottershead/Practice-Python
/Tutorials/Exercise 01 - Character_Input.py
802
4.1875
4
# Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. # Extras: # Add on to the previous program by asking the user for another number # and printing out that many copies of the previous message. (Hint...
true
a98ec918c69cf8b6926f80cd0388b716ec1f9b71
jim-cassidy/foursquare-with-flask
/module/createtable.py
1,914
4.1875
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) ...
true
00ed0a5bf8383fc9cc31344c481bad2e2ea8cd7e
dr01/python-workbench
/lettfreq.py
2,125
4.21875
4
#!/usr/bin/env python3 """ Print number of occurrences and frequency of letters in a text """ __author__ = "Daniele Raffo" __version__ = "0.1" __date__ = "14/10/2018" import argparse from string import ascii_lowercase as _alphabet from collections import Counter as _Counter def parse_command_line(): """Pa...
true
816706b0788b7bac1bea4c218fa77cec1cdf2492
Bajpai-30/Coffee-Machine-in-python---hyperskill
/stage4.py
2,135
4.1875
4
amount = 550 water = 1200 milk = 540 coffee = 120 cups = 9 def print_state(): print('The coffee machine has:') print(f'{water} of water') print(f'{milk} of milk') print(f'{coffee} of coffee beans') print(f'{cups} of disposable cups') print(f'{amount} of money') print() d...
true
849f167637b964a3e8d0de273a0a43ad7c3857cd
CiaranGruber/CP1404practicals
/prac_10/extension_test_date.py
2,244
4.4375
4
""" Create the class Date which contains code to add days according to leap years Date Class. Created by Ciaran Gruber - 28/08/18 """ import doctest class Date: """Represent the Date""" month_to_day = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} def __init__(...
true
d1dddeb8a44b1cb0f4430fc9971653dced1c7a19
CiaranGruber/CP1404practicals
/prac_02/exceptions_demo.py
889
4.53125
5
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? Value Error will occur if you use a non-integer 2. When will a ZeroDivisionError occur? This will occur when the person puts the denominator as a 0 3. Could you change the code to avoid the possibility of a ZeroDivisi...
true
b0a6f193b22b83b4f6ad92957fef9b6489c08bbc
HenziKou/CIS-211
/Projects/duck_compiler-master/alu.py
1,891
4.21875
4
""" The arithmetic logic unit (ALU) is the part of the central processing unit (CPU, or 'core') that performs arithmetic operations such as addition, subtraction, etc but also logical "arithmetic" such as and, or, and shifting. """ from instr_format import OpCode, CondFlag from typing import Tuple class ALU(object):...
true
b953de6e34b2eb3e482e94f97f41fe1503d30319
syedsaad92/MIT-6.0001
/week3Problem3_printing_all_available_letters.py
573
4.15625
4
# Next, implement the function getAvailableLetters that takes in one parameter - a list of letters, lettersGuessed. This function returns a string that is comprised of lowercase English letters - all lowercase English letters that are not in lettersGuessed. def getAvailableLetters(lettersGuessed): temp = '' imp...
true
5a1da23b4558b4da778ae275f4fb8247735ff4f6
Grey-EightyPercent/Python-Learning
/ex18.py
778
4.40625
4
# Names, Variables, Code, Funcstions!!! 函数!! # this one is like your scripts with argv def print_two(*args): # use def to give the function name arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # ok, that *args is actually pointless, we can just do This def print_two_again(arg1, arg2): pr...
true
f40a4c7f84d966786da49f21e22eb1dcc349327b
apulijala/python-crash-course
/ch3-4/pizza.py
1,790
4.28125
4
def pizzas(): pizzas = ("Pepperoni", "Cheese", "Tomato") print("\n") for pizza in pizzas: print(f"I like {pizza}") print("I really love Pizza!") def pets(): pets = ("Dog", "Horse", "Cat") print("\n") for pet in pets: print(f"A {pet} would make a great Pet") print("Any o...
true
a25342fe26e0766e5003e6839b661789fa916a53
SaentRayn/Data-Structures-By-Python
/Python Files/Set-Prob.py
835
4.375
4
def intersection(set1, set2): differentValues = set() # Add Code to only add values that are not in both sets to the differentValues # Hint: One need only cycle a value and check if it is in the other set return(differentValues) def union(set1, set2): unionOfSets = set() # Add code to add both the val...
true
50871b83a9b35cd72104f1684a6e6c30b9bd0aa5
jb240707/Google_IT_Automation_Python
/Interacting with OS/test_script.py
2,719
4.5
4
""" The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. Fill in the gaps to create a script called "program.py". """ import datetime import os def create_python_scri...
true
fa3f9e982b12fc3726adeebf47e40a9d4a475c18
Sannj/learn-python-in-a-day
/bmiCalc.py
796
4.21875
4
def calBMI(h, w): bmi = int(w)/(int(h)/100)**2 print('Your BMI is: {}'.format(round(bmi, 2))) bmi = round(bmi, 2) if bmi > 25: print('You have this sweetheart! You can get rid of those extra pounds!') elif bmi < 18.5: print('Omg. You need Nutella like right now! You need more pounds.') else: print('Keep mai...
true
68b6d97adc41e0aa374fc1235e342605aa8c9ae6
llakhi/python_program
/Practise_1.py
1,408
4.15625
4
# split a string and display separately filename = input("Type file name") print ("Filename : ",filename) print ("Split the file name and show ") data = filename.split('.') print("file name - " ,data[0]) print("file name - " ,data[1]) # Write a program and display all the duplicates of list alist = [10,20,30,10,...
true
bf5d24a9e92a2afe969b118890bce75e2f57d9cc
clive-bunting/computer-science
/Problem Set 2/probset2_1.py
745
4.25
4
balance = 4842 # the outstanding balance on the credit card annualInterestRate = 0.2 # annual interest rate as a decimal monthlyPaymentRate = 0.04 # minimum monthly payment rate as a decimal monthlyInterestRate = annualInterestRate / 12.0 totalPaid = 0.0 for month in range(1,13): minimumMonthlyPayment = monthlyPa...
true
d46d1b419391f408934e1f1a94092d18f9c50d61
Irbah28/Python-Examples
/recursion_examples.py
1,365
4.3125
4
'''A few simple examples of recursion.''' def sum1(xs): '''We can recursively sum a list of numbers.''' if len(xs) == 0: return 0 else: return xs[0] + sum1(xs[1:]) def sum2(xs): '''Or do the same thing iteratively.''' y = 0 for x in xs: y += x return y def product1...
true
37a83e497842185ec4fa9c8126d959f1d38164b6
msmiel/mnemosyne
/books/Machine Learning/Machine Learning supp/code/chapter2/Divisors3.py
240
4.125
4
def divisors(num): count = 1 div = 2 while(div < num): if(num % div == 0): count = count + 1 div = div + 1 return count result = divisors(12) if(result == 1): print('12 is prime') else: print('12 is not prime')
true