blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
26c7ace59a7074f0584cd63e7f21eedc2159579e | ephreal/CS | /searching/python/binary_search.py | 549 | 4.21875 | 4 | def binary_search(search_list, target):
""""
An implementation of a binary search in python.
Returns the index in the list if the item is found. Returns None
if not.
"""
first = 0
last = len(search_list) - 1
while first <= last:
midpoint = (first + last) // 2
if search... | true |
7f8ca8e54858853fb057e7076eed9b9c634b82b6 | PacktPublishing/The-Complete-Python-Course | /1_intro/lectures/15_dictionaries/code.py | 921 | 4.625 | 5 | friend_ages = {"Rolf": 24, "Adam": 30, "Anne": 27}
print(friend_ages["Rolf"]) # 24
# friend_ages["Bob"] ERROR
# -- Adding a new key to the dictionary --
friend_ages["Bob"] = 20
print(friend_ages) # {'Rolf': 24, 'Adam': 30, 'Anne': 27, 'Bob': 20}
# -- Modifying existing keys --
friend_ages["Rolf"] = 25
print(fr... | true |
8c8020d86d108df7264b3448c4f6cbfa6c6fc7a3 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/05_argument_unpacking/code.py | 2,507 | 4.90625 | 5 | """
* What is argument unpacking?
* Unpacking positional arguments
* Unpacking named arguments
* Example (below)
Given a function, like the one we just looked at to add a balance to an account:
"""
accounts = {
'checking': 1958.00,
'savings': 3695.50
}
def add_balance(amount: float, name: str) -> float:
... | true |
85748dc41cd9db69df420983540035e866d89a7e | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/7_else_with_loops/code.py | 591 | 4.34375 | 4 | # On loops, you can add an `else` clause. This only runs if the loop does not encounter a `break` or an error.
# That means, if the loop completes successfully, the `else` part will run.
cars = ["ok", "ok", "ok", "faulty", "ok", "ok"]
for status in cars:
if status == "faulty":
print("Stopping the producti... | true |
533360c4d458f8e2fc579b60af0441f5ec49ec17 | PacktPublishing/The-Complete-Python-Course | /6_files/files_project/friends.py | 735 | 4.3125 | 4 | # Ask the user for a list of 3 friends
# For each friend, we'll tell the user whether they are nearby
# For each nearby friend, we'll save their name to `nearby_friends.txt`
friends = input('Enter three friend names, separated by commas (no spaces, please): ').split(',')
people = open('people.txt', 'r')
people_nearby... | true |
c712a62a9b104cbb2345f00b18dfdee6712d5c0c | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/15_functions/code.py | 894 | 4.3125 | 4 | # So far we've been using functions such as `print`, `len`, and `zip`.
# But we haven't learned how to create our own functions, or even how they really work.
# Let's create our own function. The building blocks are:
# def
# the name
# brackets
# colon
# any code you want, but it must be indented if you want it to run... | true |
fab51111c8d19f063d67d289cfeef4c9a71bb801 | PacktPublishing/The-Complete-Python-Course | /7_second_milestone_project/milestone_2_files/app.py | 1,197 | 4.1875 | 4 | from utils import database
USER_CHOICE = """
Enter:
- 'a' to add a new book
- 'l' to list all books
- 'r' to mark a book as read
- 'd' to delete a book
- 'q' to quit
Your choice: """
def menu():
database.create_book_table()
user_input = input(USER_CHOICE)
while user_input != 'q':
if user_input ... | true |
42677deb29fcb61c5aeff5b093742d97952c9e27 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/10_timing_your_code/code.py | 1,661 | 4.5 | 4 | """
As well as the `datetime` module, used to deal with objects containing both date and time, we have a `date` module and a `time` module.
Whenever you’re running some code, you can measure the start time and end time to calculate the total amount of time it took for the code to run.
It’s really straightforward:
"""... | true |
90aa93be4b574939d568c13f67129c50c4f34d19 | ItzMeRonan/PythonBasics | /TextBasedGame.py | 423 | 4.125 | 4 | #--- My Text-Based Adventure Game ---
print("Welcome to my text-based adventure game")
playerName = input("Please enter your name : ")
print("Hello " + playerName)
print("Pick any of the following characters: ", "1. Tony ", "2. Thor ", "3. Hulk", sep='\n')
characterList = ["Tony", "Thor", "Hulk"]
characterNumber = ... | true |
23c8d095e97226e3c7558de15a692abda0bd0e01 | kunal-singh786/basic-python | /ascii value.py | 219 | 4.15625 | 4 | #Write a program to perform the Difference between two ASCII.
x = 'c'
print("The ASCII value of "+x+" is",ord(x))
y = 'a'
print("The ASCII value of "+y+" is",ord(y))
z = abs(ord(x) - ord(y))
print("The value of z is",z) | true |
87a6d5e514a8d472b5fe429ddf28190fb3e38547 | EddieMichael1983/PDX_Code_Guild_Labs | /RPS.py | 1,514 | 4.3125 | 4 |
import random
rps = ['rock', 'paper', 'scissors'] #defining random values for the computer to choose from
user_choice2 = 'y' #this sets the program up to run again later when the user is asked if they want to play again
while user_choice2 == 'y': #while user_choice2 == y is TRUE the program keeps going
user... | true |
698c8d06b87bda39846c76dff4ddb1feb682cf4f | ManchuChris/MongoPython | /PrimePalindrome/PrimePalindrome.py | 1,739 | 4.1875 | 4 | # Find the smallest prime palindrome greater than or equal to N.
# Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
# For example, 2,3,5,7,11 and 13 are primes.
# Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
#
... | true |
ebe3d0b8c5d85eb504e9c68c962c1fa8343eab3b | aartis83/Project-Math-Painting | /App3.py | 2,137 | 4.1875 | 4 | from canvas import Canvas
from shapes import Rectangle, Square
# Get canvas width and height from user
canvas_width = int(input("Enter the canvas width: "))
canvas_height= int(input("Enter the canvas height: "))
# Make a dictionary of color codes and prompt for color
colors = {"white": (255, 255, 255), "blac... | true |
d202ee1b2a40990f05daa809841df5bab91c8c9e | sharatss/python | /techgig_practice/age.py | 1,547 | 4.15625 | 4 | """
Decide yourself with conditional statement (100 Marks)
This challenge will help you in clearing your fundamentals with if-else conditionals which are the basic part of all programming languages.
Task:
For this challenge, you need to read a integer value(default name - age) from stdin, store it in a variable and... | true |
a9786b118e8755d0b94e2318f514f27d7eeaa263 | sharatss/python | /techgig_practice/special_numbers.py | 1,070 | 4.125 | 4 | """
Count special numbers between boundaries (100 Marks)
This challenge will help you in getting familiarity with functions which will be helpful when you will solve further problems on Techgig.
Task:
For this challenge, you are given a range and you need to find how many prime numbers lying between the given range.... | true |
e6c0effb856be274dabe3f6fc6913cf9a5d1440b | alyhhbrd/CTI110- | /P3HW1_ColorMixer_HubbardAaliyah.py | 1,225 | 4.3125 | 4 | # CTI-110
# P3HW1 - Color Mixer
# Aaliyah Hubbard
# 03032019
#
# Prompt user to input two of three primary colors; output as error code if input color is not primary
# Determine which secondary color is produced of two input colors
# Display secondary color produced as output
# promt user for input
print('LET`S MIX ... | true |
df088fb37c67578d8327ad3fd90b2eebfaba85dd | dk4267/CS490 | /Lesson1Question3.py | 1,151 | 4.25 | 4 |
#I accidentally made this much more difficult than it had to be
inputString = input('Please enter a string') #get input
outputString = '' #string to add chars for output
index = 0 #keeps track of where we are in the string
isPython = False #keeps track of whether we're in the middle of the word 'python'
for ch... | true |
67b81266248d8fb5394b5ffbd7a950a2ae38f5b2 | appsjit/testament | /LeetCode/soljit/s208_TrieAddSearchSW.py | 2,080 | 4.125 | 4 | class TrieNode:
def __init__(self, value=None):
self.value = value
self.next = {}
self.end = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
... | true |
5db6b90a933778253e1c023dce68643d026d367b | voitenko-lex/leetcode | /Python3/06-zigzag-conversion/zigzag-conversion.py | 2,703 | 4.28125 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conv... | true |
6303d1c3706e99b0bbd18d019cd124323d4d90e4 | adamabad/WilkesUniversity | /cs125/projects/weights.py | 1,289 | 4.25 | 4 | # File: weights.py
# Date: October 26, 2017
# Author: Adam Abad
# Purpose: To evaluate pumpkin weights and average their total
def info():
print()
print("Program to calculate the average of a")
print("group of pumpkin weights.")
print("You will be asked to enter the number of")
print("pumpkins... | true |
671b743b1a208bb2f23e00ca96acad7710bd932f | slutske22/Practice_files | /python_quickstart_lynda/conditionals.py | 1,192 | 4.21875 | 4 | # %%
raining = input("Is it raining outside? (yes/no)")
if raining == 'yes':
print("You need an umbrella")
# %%
userInput = input("Choose and integer between -10 and 10")
n = int(userInput)
if n >= -10 & n <= 10:
print("Good Job")
# %%
def minimum(x, y):
if x < y:
return x
else:
retu... | true |
19830b17fe1289929e9d9d7f6312715ea6cafeb7 | SDSS-Computing-Studies/006b-more-functions-ye11owbucket | /problem2.py | 774 | 4.125 | 4 | #!python3
"""
##### Problem 2
Create a function that determines if a triangle is scalene, right or obtuse.
3 input parameters:
float: one side
float: another side
float: 3rd side
return:
0 : triangle does not exist
1 : if the triangle is scalene
2 : if the triangle is right
3 : if the triangle is obtuse
Sam... | true |
e935b348e9f40316060ccab9f045ce3b7151a1fe | scriptedinstalls/Scripts | /python/strings/mystrings.py | 574 | 4.25 | 4 | #!/usr/bin/python
import string
message = "new string"
message2 = "new string"
print message
print "contains ", len(message), "characters"
print "The first character in message is ", message[0]
print "Example of slicing message", message, "is", message[0:4]
for letter in message:
print letter
if message == m... | true |
e6b681234935ea15b7784a76d9921a900e137e7f | hboonewilson/IntroCS | /Collatz Conjecture.py | 885 | 4.46875 | 4 | #Collatz Conjecture - Start with a number n > 1. Find the number of steps it...
#takes to reach one using the following process: If n* is even, divide it by 2.
#If *n is odd, multiply it by 3 and add 1.
collatz = True
while collatz:
input_num = int(input("Give me a number higher than 1: "))
if input_... | true |
2a251fb6764b5d54e052d754a0931951e0c590a7 | AWOLASAP/compSciPrinciples | /python files/pcc EX.py | 343 | 4.28125 | 4 | '''
This program was written by Griffin Walraven
It prints some text to the user.
'''
#Print text to the user
print("Hello!! My name is Griffin Walraven.")
#input statement to read name from the user
name = input("What is yours? ")
print("Hello ", name, "!! I am a student at Hilhi.")
print("I am in 10th grade an... | true |
3bc172ed239a7420049479378bc660dab7ce772e | ambikeshkumarsingh/LPTHW_ambikesh | /ex3.py | 477 | 4.25 | 4 | print("I will count my chickens:" )
print("Hens", 25 +30/6)
print("Roosters",100-25*3 %4)
print("Now I will count the eggs")
print(3 + 2 + 1- 5 + 4 % 2-1 /4 + 6)
print("Is is true that 3+2<5-7")
print(3+2<5-7)
print("What is 3+2 ? ", 3+2)
print("What is 5-7 ?", 5-7)
print("Oh! that's why It is fa... | true |
cffc2440c9d7945fe89f9cc7d180ee484f0a7689 | bartoszkobylinski/tests | /tests/tests.py | 1,544 | 4.3125 | 4 | import typing
import unittest
from app import StringCalculator
'''
class StringCalculator:
def add(self, user_input: str) -> int:
if user_input is None or user_input.strip() == '':
return 0
else:
numbers = user_input.split(',')
result = 0
... | true |
e465bf117aef5494bb2299f3f2aaa905fb619b52 | purple-phoenix/dailyprogrammer | /python_files/project_239_game_of_threes/game_of_threes.py | 1,346 | 4.25 | 4 | ##
# Do not name variables "input" as input is an existing variable in python:
# https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python
#
# By convention, internal functions should start with an underscore.
# https://stackoverflow.com/questions/11483366/protected-method-in-python
##
##
# @param o... | true |
40dcaf6d0f51e671ed643d3c49d2071ed65df207 | yb170442627/YangBo | /Python_ex/ex25_1.py | 339 | 4.34375 | 4 | # -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
words = "where are you come from?"
word = break_words(words)
print word
word1 = sort_words... | true |
b86bc57163990cb644d6449b1e70a5eb435325b4 | Green-octopus678/Computer-Science | /Need gelp.py | 2,090 | 4.1875 | 4 | import time
import random
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
score = 0
operator = 0
question = 0
#This part sets the variables for the question number, score and the operator
print('Welcome to my brilliant maths quiz\n')
time.sleep(1.5)
print()
prin... | true |
a5f3fdde75ca1ba377ace30608a3da5012bb5937 | itspratham/Python-tutorial | /Python_Contents/Python_Loops/BreakContinue.py | 443 | 4.21875 | 4 | # User gives input "quit" "Continue" , "Inbvalid Option"
user_input = True
while user_input:
user_input = str(input("Enter the valid input:"))
if user_input == "quit":
print("You have entered break")
break
if user_input == "continue":
print("You habe entered continue")
conti... | true |
7563439f6f667bbe4c71a7256353dcf50de0ee8c | itspratham/Python-tutorial | /Python_Contents/data_structures/Stacks/stacks.py | 1,842 | 4.21875 | 4 | class Stack:
def __init__(self):
self.list = []
self.limit = int(input("Enter the limit of the stack: "))
def push(self):
if len(self.list) < self.limit:
x = input("Enter the element to be entered into the Stack: ")
self.list.append(x)
return f"{x} in... | true |
eaa4cb4848a01460f115a9dec5fe56ef329fc578 | Blu-Phoenix/Final_Calculator | /runme.py | 2,632 | 4.40625 | 4 | """
Program: Final_Calculator(Master).py
Developer: Michael Royer
Language: Python-3.x.x
Primum Diem: 12/2017
Modified: 03/28/2018
Description: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over.
Input: The user will be asked f... | true |
1aa2f192350934e720cb2546d7a7eebf9e09732e | un1xer/python-exercises | /zippy.py | 1,073 | 4.59375 | 5 | # Create a function named combo() that takes two iterables and returns a list of tuples.
# Each tuple should hold the first item in each list, then the second set, then the third,
# and so on. Assume the iterables will be the same length.
# combo(['swallow', 'snake', 'parrot'], 'abc')
# Output:
# [('swallow', 'a'), ('... | true |
983a91b383f63fedd4ba16a2cb8f2eaceaffc57a | rlugojr/FSND_P01_Movie_Trailers | /media.py | 926 | 4.3125 | 4 |
'''The media.Movie Class provides a data structure to store
movie related information'''
class Movie():
'''The media.Movie constructor is used to instantiate a movie object.
Inputs (required):
movie_title --> Title of the movie.
movie_year --> The year the movie was released.
... | true |
e93bd1d37465c9976728899914d468b036f3b1f3 | kannan5/Algorithms-And-DataStructures | /Queue/queue_py.py | 829 | 4.21875 | 4 | """
Implement the Queue Data Structure Using Python
Note: In This Class Queue was implemented using Python Lists.
List is Not Suitable or Won't be efficient for Queue Structure.
(Since It Takes O(n) for Insertion and Deletion).
This is for Understanding / Learning Purpose.
"""
cl... | true |
8e5c3324d1cf90eb7628bf09eca7413260e39cb7 | kannan5/Algorithms-And-DataStructures | /LinkedList/circularlinkedlist.py | 2,310 | 4.3125 | 4 | "Program to Create The Circular Linked List "
class CircularLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
new_node = Node(data_val, self.head)
if current is None:
self.head = new_node
new_node.next... | true |
952b645f8ba4d792112e905bc646976bec523670 | blairsharpe/LFSR | /LFSR.py | 1,205 | 4.125 | 4 | def xor(state, inputs, length, invert):
"""Computes XOR digital logic
Parameters:
:param str state : Current state of the register
:param list inputs: Position to tap inputs from register
Returns:
:return output: Output of the XOR gate digital logic
:rtype int :
"""
... | true |
31f01f01b4e5abec5c6bb6e42ec704047b78d42e | DLaMott/Calculator | /com/Hi/__init__.py | 826 | 4.125 | 4 |
def main():
print('Hello and welcome to my simple calculator.')
print('This is will display different numerical data as a test.')
value = float(input("Please enter a number: "))
value2 = float(input("Please enter a second number: "))
print('These are your two numbers added t... | true |
e48382f4282df95b1f268af7648eec1c885cef18 | viticlick/PythonProjectEuler | /archive1.py | 331 | 4.3125 | 4 | #!/usr/bin/python
"""If we list all the natural numbers below 10 that are multiples of 3 or 5 \
we get 3, 5, 6 and 9. The sumof these multiples is 23.\
\
Find the sum of all the multiples of 3 or 5 below 1000."""
values = [ x for x in range(1,1001) if x % 3 == 0 or x % 5 == 0]
total = sum(values)
print "The result i... | true |
a11e6981301bbdc6a6f55ac7853598ad3b61ede9 | BenjaminFu1/Python-Prep | /square area calculator.py | 205 | 4.1875 | 4 | length=float(input("Give me the lenth of your rectangle"))
width=float(input("Give me the width of your rectangle"))
area=(length) * (width)
print("{0:.1f} is the area of your rectangle".format(area))
| true |
866c36768b1363d7cd4adef7212458a470e6b0fd | kayshale/ShoppingListApp | /main.py | 1,196 | 4.1875 | 4 | #Kayshale Ortiz
#IS437 Group Assignment 1: Shopping List App
menuOption = None
mylist = []
maxLengthList = 6
menuText = '''
1.) Add Item
2.) Print List
3.) Remove item by number
4.) Save List to file
5.) Load List from file
6.) Exit
'''
while menuOption != '6':
print(menuText)
menuOption = input('Enter Selec... | true |
b0b67fba426642ef56a1cfa5d5e6a65a0286dacb | Rhysoshea/daily_coding_challenges | /other/sort_the_odd.py | 612 | 4.3125 | 4 | '''
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
'''
def sort_array(source_arr... | true |
6a02c3fe5111ddf6690e5a060a543164b2db0563 | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily25.py | 1,686 | 4.5 | 4 | """
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string match... | true |
be3a184aecc35085a7d69bc447eeaf99d5c2320b | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily44.py | 1,329 | 4.1875 | 4 | # We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
# Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
#... | true |
0f01a1e6aa57c4ed9dccf237df27db0465bae2cc | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily27.py | 848 | 4.15625 | 4 | """
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
def solution(input):
stack = []
open = ["{", "("... | true |
8e3f51ca47d9937f5aae6b56f81bfdba273d3336 | shreyashetty207/python_internship | /Task 4/Prb1.py | 616 | 4.28125 | 4 | #1. Write a program to create a list of n integer values and do the following
#• Add an item in to the list (using function)
#• Delete (using function)
#• Store the largest number from the list to a variable
#• Store the Smallest number from the list to a variable
S = [1, 2, 3,4]
S.append(56)
print('Updated list... | true |
55dca8c77d3eed88301fd93979dbd1b6b4ad657f | brityboy/python-workshop | /day2/exchange.py | 2,914 | 4.125 | 4 | # def test():
# return 'hello'
# this is the game plan
# we are going to make
# a function that will read the data in
# built into this, we are going to make functions that
# 1. creates a list of the differences <- we will use from collections
# Counter in order to get the amounts
# 2. We are going to create a fun... | true |
178592a57ce09b002482bc4e7638d25730b323ce | Smrcekd/HW070172 | /L03/Excersise 4.py | 385 | 4.34375 | 4 | #convert.py
#A program to convert Celsius temps to Fahrenheit
#reprotudcted by David Smrček
def main():
print("This program can be used to convert temperature from Celsius to Fahrenheit")
for i in range(5):
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5*celsius+32
print("The... | true |
ac4e2b8034d0c78d302a02c03fdb45ecb3026b56 | Smrcekd/HW070172 | /L04/Chapter 3/Excersise 15.py | 421 | 4.21875 | 4 | # Program approximates the value of pi
# By summing the terms of series
# by David Smrček
import math#Makes the math library available.
def main():
n = eval(input("Number of terms for the sum: "))
x = 0
m = 1
for i in range (1,2 * n + 1, 2):
x = x + (m *4/i)
m = -m
r... | true |
1c0caaffdef74eb1911756360307908310c811b2 | laviniabivolan/Spanzuratoarea | /MyHangman.py | 2,394 | 4.125 | 4 | import random
def guess_word():
list_of_words = ["starwards", "someone", "powerrangers", "marabu", "mypython", "wordinthelist", "neversurrender"]
random_word = random.choice(list_of_words)
return random_word
def hangman_game():
alphabet = 'abcdefghijklmnoprstuvwxyqz'
word = guess_word()
... | true |
efcb63ba80b697680a8b907923bcbcdc609ae94e | Wmeng98/Leetcode | /Easy/merge_2_sorted_lists.py | 1,295 | 4.21875 | 4 | # Solution 1 - Recursive Approach
# Recursivelly define the merge of two lists as the following...
# Smaller of the two head nodes plus to result of the merge on the rest of the nodes
# Time 0(n+m) and Space O(n+m) -> first recursive call doesn't return untill ends of l1 && l2 have been reached
# Solution 2 - Itera... | true |
ff234acf470b12fe21ee41df3d2a2cf69bd0af91 | tejalbangali/HackerRank-Numpy-Challenge | /Arrays.py | 502 | 4.40625 | 4 | # Task:
# --> You are given a space-separated list of numbers. Your task is to print a reversed NumPy array with the element type float.
# -> Input Format: A single line of input containing space-separated numbers.
# -> Sample Input: 1 2 3 4 -8 -10
# -> Sample Output: [-10. -8. 4. 3. 2. 1.]
import numpy
def... | true |
83243d09a2140da62c7a572d2d887e879801e104 | victordity/PythonExercises | /PythonInterview/binarySearch.py | 1,029 | 4.21875 | 4 | import bisect
def bisect_tutorial():
fruits = ["apple", "banana", "banana", "banana", "orange", "pineapple"]
print(bisect.bisect(fruits, "banana"))
print(bisect.bisect_left(fruits, "banana"))
occurrences = bisect.bisect(fruits, "banana") - bisect.bisect_left(fruits, "banana")
print(occurrences) # ... | true |
4d51b16c7673470425579525742dd537470e48b9 | loide/MITx-6.00.1x | /myLog.py | 841 | 4.46875 | 4 | '''
This program computes the logarithm of a number relative to a base.
Inputs:
number: the number to compute the logarithm
base: the base of logarithm
Output:
Logarithm value [ log_base (number) ]
'''
def myLog(number, base):
if ( (type(number) != int) or (number < 0)):
return "Error: Number value must... | true |
579e0da0253ec03a4583ba2288b552b72c0d5ced | anweshachakraborty17/Python_Bootcamp | /P48_Delete a tuple.py | 295 | 4.15625 | 4 | #Delete a tuple
thistuple1 = ("apple", "banana", "mango")
del thistuple1
print(thistuple1) #this will raise an error because the tuple no longer exists
#OUTPUT window will show:
#Traceback (most recent call last): File "./prog.py", line 3, in NameError: name 'thistuple1' is not defined | true |
5cf51d431c50db3886d1daa7c5dc07ea19e133f7 | harsh4251/SimplyPython | /practice/oops/encapsulation.py | 543 | 4.4375 | 4 | class Encapsulation():
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
print("Private can only be accessed inside a class {}".format(self.__private))
e = Encapsulation(1,2,3)
print("Public & protacted can be access outside class{},{} ".format(e.public,e._protected))
"""Nam... | true |
0b2deb15577ba07a878f00d91eee617d48605bec | beekalam/fundamentals.of.python.data.structures | /ch02/counting.py | 583 | 4.15625 | 4 | """
File: counting.py
prints the number of iterations for problem sizes
that double, using a nested loop
"""
if __name__ == "__main__":
problemSize = 1000
print("%12s%15s" % ("Problem Size", "Iterations"))
for count in range(5):
number = 0
#The start of the algorithm
work = 1
... | true |
8e19018571298372b73695afb9139596e1524464 | MITRE-South-Florida-STEM/ps1-summer-2021-luis-c465 | /ps1c.py | 1,706 | 4.125 | 4 | annual_salary = float(input("Enter the starting salary: "))
total_cost = 1_000_000
semi_annual_raise = .07
portion_down_payment = 0.25
r = 0.04 # Return on investment
total_months = 0
current_savings = 0.0
def down_payment(annual_salary: int, portion_saved: float, total_cost: int,
portion_down_payment: float... | true |
315ace2527ebf89d6e80aea2a47047f0484f5b40 | Owensb/SnapCracklePop | /snapcrackle.py | 457 | 4.125 | 4 | # Write a program that prints out the numbers 1 to 100 (inclusive).
# If the number is divisible by 3, print Crackle instead of the number.
# If it's divisible by 5, print Pop.
# If it's divisible by both 3 and 5, print CracklePop. You can use any language.
i = []
for i in range (1, 101):
if (i % 3 ==0) & (... | true |
64ba459b0b322274f900e1716496e7643d90bde1 | shermansjliu/Python-Projects | /Ceasar Cipher/Ceaser Cipher.py | 1,888 | 4.21875 | 4 | def ReturnEncryptedString():
code = input("Enter in the code you would like to encrypt")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += EncryptKey(oldChar)
print(newString)
def ReturnDecryptedString():
code = input("Enter in the code you ... | true |
48def1c3190fb8e4463f68dd478055621b12e4b6 | yooshxyz/ITP | /Feb19.py | 1,702 | 4.125 | 4 | import random
# answer = answer.strip()[0].lower()
def main():
while True:
user_choice_input = int(input("What Function do you want to Use?\nPlease type 1 for the No vowels function, type 2 for the random vowels function, and 3 for the even or odd calculator.\n"))
if user_choice_input == 1:
... | true |
a09d239c09374761d9c78ae4cfd872eec416a71c | NishadKumar/leetcode-30-day-challenge | /construct-bst-preorder-traversal.py | 1,585 | 4.15625 | 4 | # Return the root node of a binary search tree that matches the given preorder traversal.
# (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displa... | true |
b1d83a286acfa0d779945d7ab5f0cfbb608f735e | nandanabhishek/C-programs | /Checking Even or Odd/even_odd.py | 249 | 4.21875 | 4 | a = int(input(" Enter any number to check whether it is even or odd : "))
if (a%2 == 0) :
print(a, "is Even !")
# this syntax inside print statement, automatically adds a space between data separated by comma
else :
print(a, "is Odd !")
| true |
3507349ce69a165ef1b4165843a3ba72e09e4a12 | Rishab-kulkarni/caesar-cipher | /caesar_cipher.py | 1,861 | 4.40625 | 4 | import string
# Enter only alphabets
input_text = input("Enter text to encrypt:").lower()
shift_value = int(input("Enter a shift value:"))
alphabet = string.ascii_lowercase
alphabet = list(alphabet)
def encrypt(input_text,shift_value):
"""
Shifts all the characters present in the input text b... | true |
0e8366c415dd5b7ba4812b30d1a97dd5b4bf7763 | Sipoufo/Python_realisation | /Ex-12/guess_number.py | 1,389 | 4.125 | 4 | from art import logo
import random
print("Welcome to the Number Guessing Game")
# init
live = 0
run = True
# function
def add_live(difficulty):
if difficulty.lower() == 'easy':
return 10
elif difficulty.lower() == 'hard':
return 5
def compare(user, rand):
if user < rand:
print("... | true |
f55819c8e653d6b4d94ad5f74cffd6a8121ddda2 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23.py | 2,317 | 4.375 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
name = input("Who's grade do you want? ")
print(name in grades)
## if not there, add them
name = input("Who's grade do you want? ").capitalize()
if name in grades:
prin... | true |
39a97c3366248770fba81735c9c4e231b34077b9 | kuwarkapur/Robot-Automation-using-ROS_2021 | /week 1/assignement.py | 2,292 | 4.3125 | 4 | """Week I Assignment
Simulate the trajectory of a robot approximated using a unicycle model given the
following start states, dt, velocity commands and timesteps
State = (x, y, theta);
Velocity = (v, w)
1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25
2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps... | true |
22e283d052f9b9931bf09c823dfb93dba87b33ed | Aijaz12550/python | /list/main.py | 953 | 4.375 | 4 |
#########################
##### remove method #####
#########################
list1 = [ 1, 2, True, "aijaz", "test"]
"""
list.remove(arg) it will take one item of list
as a argument to remove from list
"""
list1.remove(1) # it will remove 1 from list1
#list1.remove(99) # it will throw error because 99 is not exi... | true |
43224d710674f33eafd7a5d1b0feb25bfec35141 | FlyingEwok/Linear-BinarySearch | /binarysearch.py | 1,116 | 4.21875 | 4 | def binarySearch (list, l, listLength, value):
# Set up mid point variable
if listLength >= l:
midPoint = l + (listLength - l) // 2
if list[midPoint] == value: # return the midpoint if the value is midpoint
return midPoint
elif list[midPoint] > value: # Do a search to... | true |
15bf570be794b9919f43b5786f61a8a97eb81d31 | YunusEmreAlps/Python-Basics | /2. Basic/Output.py | 1,846 | 4.34375 | 4 | # --------------------
# Example 1 (Output)
# This is comment
"""
This
is
multi-line
comments
"""
# if you want to show something on console
# you need to use a "print" instruction
# syntax:
# print('Message') -> single quotes
# print("Message") -> double quotes
print(' - Hello World!')
print(" - I love Python pr... | true |
f5f54b5db00added0abbf07df9fa2c38bb2e2fbc | compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay | /class10-05/calculator.py | 844 | 4.21875 | 4 | #get the first number
#get the second number
#make an individual function to add, subtract, multiply and divide
#return from each function
#template for add function
def add(num1, num2):
return (num1+num2)
def sub(num1, num2):
return (num1-num2)
def multiply(num1, num2):
return (num1*num2)
def division... | true |
8d438c71959d3fd16bffc44490bdfea783fcf61d | vassmate/Learn_Python_THW | /mystuff/ex3.py | 1,312 | 4.8125 | 5 | # http://learnpythonthehardway.org/book/ex3.html
# This will print out: "I will count my chickens:".
print "I will count my chikens:"
# This will print out how much Hens we have.
print "Hens", 25.0 + 30.0 / 6.0
# This will print out how much roosters we have.
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# This will pr... | true |
1abd8eea6ff68cbb119651fc9e978bef80dfa1a8 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 577 | 4.4375 | 4 | #!/usr/bin/env python3
"""Module to compute the shape of a matrix"""
def matrix_shape(matrix):
"""Calculates the shape of a matrix.
Arguments:
matrix (list): the matrix that will be processed
Returns:
tuple: a tuple that contains the shape of every dimmension
in the matr... | true |
79969b00b7683284a24114fa72d3b613caf1d3d2 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/14-saddle_up.py | 598 | 4.15625 | 4 | #!/usr/bin/env python3
"""Module to compute matrix multiplications.
"""
import numpy as np
def np_matmul(mat1, mat2):
"""Calculate the multiplication of two NumPy Arrays.
Arguments:
mat1 (numpy.ndarray): a NumPy array that normally represents a square
matrix.
... | true |
a403e25b42db8d2b9033c06b5aac45074300d4b3 | dkrusch/python | /lists/planets.py | 1,109 | 4.40625 | 4 | planet_list = ["Mercury", "Mars"]
planet_list.append("Jupiter")
planet_list.append("Saturn")
planet_list.extend(["Uranus", "Neptune"])
planet_list.insert(1, "Earth")
planet_list.insert(1, "Venus")
planet_list.append("Pluto")
slice_rock = slice(0, 4)
rocky_planets = planet_list[slice_rock]
del[planet_list[8]]
# Use appe... | true |
94d4dae91040dd8a74cce61e0977cc3931760ac0 | mali44/PythonPracticing | /Palindrome1.py | 645 | 4.28125 | 4 |
#Ask the user for a string and print out whether this string is a palindrome or not.
#(A palindrome is a string that reads the same forwards and backwards.)
mystr1= input("Give a String")
fromLeft=0
fromRight=1
pointer=0
while True:
if fromLeft > int(len(mystr1)):
break
if fromRight > int(len(mys... | true |
71dad1096b5699d19ad30d431d025aa12b8165f4 | E-Cell-VSSUT/coders | /python/IBAN.py | 2,276 | 4.125 | 4 | # IBAN ( International Bank Account Number ) Validator
'''
An IBAN-compliant account number consists of:
-->a two-letter country code taken from the ISO 3166-1 standard (e.g., FR for France, GB for Great Britain, DE for Germany, and so on)
-->two check digits used to perform the validity checks - fast and simple, but n... | true |
68e650fa51502dcc2a1e15bb7b956cb0c8630c58 | E-Cell-VSSUT/coders | /python/Fibonacci.py | 750 | 4.3125 | 4 | # -- Case-1 -->> Using Function
# This is a program to find fibonacci series using simple function
def fib(n):
if n < 1: # Fibonacci is not defined for negative numbers
return None
if n < 3: # The first two elements of fibonacci are 1
return 1
elem1 = elem2 = 1
sum = 0
for i in ran... | true |
faf830c550d3166f125c4b846f95de6b1047d5c7 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check02b.py | 682 | 4.21875 | 4 | user_provide_file = input("Enter file: ")
num_lines = 0
num_words = 0
# method for opening file and assigning its contents to a var
# resource: https://runestone.academy/runestone/books/published/thinkcspy/Files/Iteratingoverlinesinafile.html
# file = open(user_provide_file, "r")
# best practice is to use "with" to ... | true |
5b9d02e8b3b62588d1de662ef4321b20097c8f10 | sgriffith3/python_basics_9-14-2020 | /pet_list_challenge.py | 843 | 4.125 | 4 | #Tuesday Morning Challenge:
#Start with this list of pets:
pets = ['fido', 'spot', 'fluffy']
#Use the input() function three times to gather names of three more pets.
pet1 = input("pet 1 name: ")
pet2 = input("pet 2 name: ")
pet3 = input("pet 3 name: ")
#Add each of these new pet names to the pets list.
pets.appen... | true |
900733030503c1011f0df3f2e5ee794499e422b0 | wreyesus/Python-For-Beginners---2 | /0025. File Objects - Reading and Writing to Files.py | 474 | 4.375 | 4 | #File Objects - Reading and Writing to Files
'''
Opening a file in reading / writing / append mode
'''
f = open('test.txt','r')
#f = open('test.txt','w') --write
#f = open('test.txt','r+') --read and write
#f = open('test.txt','a') --append
print(f.name) #will print file name
print(f.mode) #wi... | true |
412ac494347bf94d8fc4b42b4775f4516795005d | bryanjulian/Programming-11 | /BryanJulianCoding/Operators and Stuff.py | 1,028 | 4.1875 | 4 | # MATH!
x = 10
print (x)
print ("x")
print ("x =",x)
x = 5
x = x + 1
print(x)
x = 5
x + 1
print (x)
# x + 1 = x Operators must be on the right side of the equation.
# Variables are CASE SENSITIVE.
x = 6
X = 5
print (x)
print (X)
# Use underscores to name variables!
# Addition (+) Subtraction (-) Multiplycation (... | true |
9d175894ced0e8687bb5724763722efdeb70741f | Bmcentee148/PythonTheHardWay | /ex_15_commented.py | 743 | 4.34375 | 4 | #import argv from the sys module so we can use it
from sys import argv
# unpack the args into appropriate variables
script, filename = argv
#open the file and stores returned file object in a var
txt_file = open(filename)
# Tells user what file they are about to view contents of
print "Here's your file %r:" % filena... | true |
c4d5cc928ee53ccfdd17c60938a7f9d0ee54e0ba | donnell794/Udemy | /Coding Interview Bootcamp/exercises/py/circular/index.py | 533 | 4.1875 | 4 | # --- Directions
# Given a linked list, return true if the list
# is circular, false if it is not.
# --- Examples
# const l = new List();
# const a = new Node('a');
# const b = new Node('b');
# const c = new Node('c');
# l.head = a;
# a.next = b;
# b.next = c;
# c.next = b;
# circular(l) # true
def c... | true |
669afade07619df314a48551e17ad102f28b249f | donnell794/Udemy | /Coding Interview Bootcamp/exercises/py/fib/index.py | 608 | 4.21875 | 4 | # --- Directions
# Print out the n-th entry in the fibonacci series.
# The fibonacci series is an ordering of numbers where
# each number is the sum of the preceeding two.
# For example, the sequence
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# forms the first ten entries of the fibonacci series.
# Example:
# fib(4) === 3
... | true |
8fa85e0a0b64bcf6b2175da13c5414b6f4397e90 | cmattox4846/PythonPractice | /Pythonintro.py | 2,522 | 4.125 | 4 | # day_of_week = 'Monday'
# print(day_of_week)
# day_of_week = 'Friday'
# print(f"I can't wait until {day_of_week}!")
# animal_input = input('What is your favorite animal?')
# color_input = input('What is your favorite color?')
# print(f"I've never seen a {color_input} {animal_input}")
#**** time of day
# time_of_d... | true |
f6ddfe6d2be79149d6a0b7c7fd373e8524990574 | Hadiyaqoobi/Python-Programming-A-Concise-Introduction | /week2/problem2_8.py | 1,206 | 4.53125 | 5 | '''
Problem 2_8:
The following list gives the hourly temperature during a 24 hour day. Please
write a function, that will take such a list and compute 3 things: average
temperature, high (maximum temperature), and low (minimum temperature) for the
day. I will test with a different set of temperatur... | true |
c9696e77689ca80b0ec5c1a46f9e5a59857c3b57 | tHeMaskedMan981/coding_practice | /problems/dfs_tree/symmetric_tree/recursive.py | 995 | 4.21875 | 4 |
# A node structure
class Node:
# A utility function to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
r... | true |
62e3168c128f1d16bef0ec4cc31afa2e05ae9cae | IshmaelDojaquez/Python | /Python101/Lists.py | 413 | 4.25 | 4 | names = ['John', 'Bob', 'Sarah', 'Mat', 'Kim']
print(names)
print(names[0]) # you can determine a specific positive or negative index
print(names[2:4]) # you can return names at a index to a given index. Does not include that secondary index
names[0] = 'Howard'
# Practice
numbers = [3, 6, 23, 8, 4, 10]
max =... | true |
e2ba3d2b834e092bd3675fbcf8dbe5c33a31f729 | ajitg9572/session2 | /hackerrank_prob.py | 206 | 4.28125 | 4 | #!/bin/python3
# declare and initialize a list
fruits = ["apple","mango","guava","grapes","pinapple"]
# pritning type of fruits
print (type(fruits))
# printing value
for fruit in fruits:
print(fruit) | true |
7272a47b347604d33c2e3bcca50099c1976da126 | gdof/Amadou_python_learning | /rock_paper_scissor/main.py | 1,345 | 4.34375 | 4 | import random
# We are going to create a rock paper scissor game
print("Do you want a rock, paper, scissor game?")
# create a variable call user_input and port the user a Yes a No
user_input = input("Yes or No? ")
# if the user select no print out "It is sorry to see you don't want to play"
if user_input == "no":
... | true |
30aaffce13d69354705ccb9e3c9c46e565a3b6d2 | Bals-0010/Leet-Code-and-Edabit | /Edabit/Identity matrix.py | 1,664 | 4.28125 | 4 | """
Identity Matrix
An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity.
Create a function that takes an integer n and returns th... | true |
d07e252bff50c58d9cf0d612edbdfd78f9a7b7a7 | radhikar408/Assignments_Python | /assignment17/ques1.py | 349 | 4.3125 | 4 | #Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.
import tkinter
from tkinter import *
import sys
root=Tk()
def show():
print("hello world")
b=Button(root,text="Hello",width=25,command=show)
b2=Button(root,text="exit",width=25, command=exit)
b.pac... | true |
dd579fcf0c2dde41709cc6a552777d799a5240f2 | MattSokol79/Python_Introduction | /python_variables.py | 1,289 | 4.5625 | 5 | # How to create a variable
# If you want to comment out more than one line, highlight it all and CTRL + /
name = "Matt" # String
# Creating a variable called name to store user name
age = 22 # Int
# Creating a variable called age to store age of user
hourly_wage = 10 # Int
# Creating a variable called hourly_wage to... | true |
d7ee9dfcd9573db8b914dc96bff65c61753aceec | fadhilmulyono/CP1401 | /CP1401Lab6/CP1401_Fadhil_Lab6_2.py | 373 | 4.25 | 4 | '''
The formula to convert temperature in Fahrenheit to centigrade is as follows:
c = (f-32)*5/9;
Write a program that has input in Fahrenheit and displays the temperature in Centigrade.
'''
def main():
f = float (input("Enter the temperature in Fahrenheit: "))
c = (f - 32) * 5 / 9
print("The temp... | true |
d3e53df801c4e65d76e275b9414312bdb2f618e5 | fadhilmulyono/CP1401 | /Prac08/CP1401_Fadhil_Prac8_3.py | 607 | 4.3125 | 4 | '''
Write a program that will display all numbers from 1 to 50 on separate lines.
For numbers that are divisible by 3 print "Fizz" instead of the number.
For numbers divisible by 5 print the word "Buzz".
For numbers that are divisible by both 3 and 5 print "FizzBuzz".
'''
def main():
number = 0
... | true |
382700c11c43f4aa36ccdac6076a6b3685243c66 | jasigrace/guess-the-number-game | /main.py | 812 | 4.1875 | 4 | import random
from art import logo
print(logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
number = random.randint(1, 100)
def guess_the_number(number_of_attempts):
while number_of_attempts > 0:
print(f"You have {number_of_attempts} remaining to guess the n... | true |
48c2d231d58a0b04c6c91e529ee98bf985988857 | ernur1/thinking-recursively | /Chapter-3/3.2-factorial.py | 392 | 4.28125 | 4 | #===============================================================================
# find the factorial of the given integer
#===============================================================================
def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num-1)
if __name_... | true |
752eb476bdcfb40289559b662245786b635c1766 | ellen-yan/self-learning | /LearnPythonHardWay/ex33.py | 362 | 4.15625 | 4 | def print_num(highest, increment):
i = 0
numbers = []
while i < highest:
print "At the top i is %d" % i
numbers.append(i)
i = i + increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
print "The numbers: "
numbers = print_nu... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.