blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
09823770fe971ca2c6505750ca422201c5110a20 | jswoodburn/Ex14 | /rps_functions.py | 1,361 | 4.28125 | 4 | import random
# get user input
def get_user_choice(question_string="\nEnter your choice (r, p, or s): ", acceptable_answer=['R', 'P', 'S']):
while True: # fails after 3 attempts?
user_choice = input(question_string)
if user_choice.upper() in acceptable_answer:
return user_choice.upper... | true |
9205e997af7767698016b14cfcd9fdd949f439a3 | manuel-garcia-yuste/ICS3UR-Assignmentb-Python | /assigment2b.py | 393 | 4.4375 | 4 | #!/usr/bin/env python3
# Created by: Manuel Garcia
# Created on: September 2019
# This program calculates the surface area of the cube
def main():
length = int(input("Enter the length of the cube: "))
# process
surface_area = 6*length**2
# output
print("")
print("The surface area of the cub... | true |
35dd6500c70a59c8b655acbfe2e2d8667fb51700 | ashar-sarwar/python-works | /python_practice/filing2.py | 720 | 4.125 | 4 | filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.rstrip()
print(pi)
print(len(pi))
filename='pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi=''
for line in lines:
pi+=line.strip()
print(pi)
print(l... | true |
a1bb86465b14c847ce05c7e22eb87f123bed4d74 | youngminpark2559/prac_ml | /flearning/003_001_numpy_array.py | 2,739 | 4.25 | 4 | # 003_001_numpy_array
# ======================================================================
# Numpy manages data as array and performs operations in array
# At this moment, array can be considered as vector or matrix mathematically
# ======================================================================
import num... | true |
1120102a7bd5bb2239193623ec7d0cbf2a06decd | andysain/_Project-Euler | /Problems/Problem019.py | 1,544 | 4.1875 | 4 | """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs o... | true |
3dfb5ef5513de1172b741a69b154fde21d2ab84a | Aivrie/ping-pong | /pong.py | 2,893 | 4.1875 | 4 | # Procedural version of my ping pong game
'''
Ping Pong - A simple ping pong game built with procedural oriented programming coding style
'''
# Game 1 - Pong Game
import turtle
win = turtle.Screen()
win.title("Pong Game by Ivory")
win.bgcolor("white")
win.setup(width=800, height=600)
win.tracer(0)
# Score
score_... | true |
133cae86497cf23f3b6c68beb291b0840b269b23 | rickbr6/dojo | /python_stack/python/radix_sort.py | 2,227 | 4.28125 | 4 |
def get_digit(num, place):
"""
:param num: A single or multi digit number
:param place: A number representing the place value of the number to return. i.e, 1 would represent the ones position
and 2 would represent the 10s position
:return: the number in the position requested with the place par... | true |
74351ecf55a4f7c986f556f42856455dc8ec7808 | niktechnopro/linux101 | /algorithm2.py | 750 | 4.125 | 4 | #Fibonacci
#make the fib function which returns the value of the fib number if you put an argument in it
def fib(position):
if(position ==0 or position ==1):
return 1;
else:
return fib(position-2) + fib(position-1);
#loop through the fib function to find the sum from 1 to when sum of fib number... | true |
46660183744daeeed73374ab15d4a671be887753 | dpdahal/python7pm | /function.py | 2,420 | 4.125 | 4 | # A function is a block of code that only runes when it is called
# Types of function:
# 1. Inbuilt function: print(), len(),int()
# 2. User define function or custom function
# define function
# def course():
# # function body part
# print("Online python class")
#
#
# # calling
# course()
# def add(x, y):
# ... | true |
cc437d93c07cdf8eafe3f66fd46d19cd401367a5 | Athul-R/ds-algo | /python_code/arrays/array.py | 1,528 | 4.28125 | 4 | """
This file has the array implemention using Python Class.
"""
class ArrayWithDict(object):
"""
This is the array implementation with data as the Dict Object
"""
def __init__(self, arg):
self.data = {}
self.length = 0
def get(self, index):
return self.data.get(index)
def push(self, item):
self.da... | true |
128dd012fb956d2aaa29b4c962020e7e96da43cd | ghills3620/csce093 | /python/03PyBasicOperators.py | 1,898 | 4.4375 | 4 | #Basic Operators
#http://www.learnpython.org/en/Basic_Operators
#Just as any other programming languages, the addition, subtraction,
# multiplication, and division operators can be used with numbers.
number = 1 + 2 * 3 / 4.0
print( number )
#Another operator available is the modulo (%) operator,
# which retu... | true |
5eac0415e9ab36961d78765856320e6f91b41754 | gyratory/NPTfP3 | /12 - Boolean Expressions/exercise01.py | 486 | 4.21875 | 4 | # Write a program that has a user guess your name, but they only get 3
# chances to do so until the program quits.
print("=========")
print("You will now try to guess my name!\nYou have 3 tries.")
print("=========")
attempt = 0
while attempt != 3:
attempt += 1
guess = input("Take a guess: ")
if guess == "g... | true |
143b9e148598f400c67f35b97ee68489364980e1 | zf2169/Pythons | /primefactors.py | 920 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
@title: Prime Factorization
@function: Enter a number and find all Prime Factors (if there are
any) and display them
@author: Zhilin
"""
def findprime(n):
'''
find all the prime numbers smaller than n
'''
num= list(range(2,n+1))
pnum= list()
while True:
a= nu... | true |
bdf5689c233e9206f60057dcdff2e4c8ff06903c | duybui2905/C4T-13 | /session5/season.py | 279 | 4.375 | 4 | month = int(input("Insert month: "))
if month <= 3 and month > 0:
print("this is winter")
elif month <= 6:
print("this is spring")
elif month <= 9:
print("this is summer")
elif month <= 12:
print("this is fall")
else:
print("THIS IS NOT A MONTH !!!!!!!")
| true |
1fadb4adbdb5e74712ef45c9ef8bb9f321073a11 | vaishnavisaindane/Hacktoberfest2021-4 | /Scripts/smallest_and_largest_of_n_different_numbers.py | 353 | 4.3125 | 4 | #python program to display smallest and largest of n different numbers
n=int(input("Enter a limit"))
m=int(input("Enter first number"))
min=m
max=m
print("Enter next",n-1,"numbers")
for i in range(2,n+1):
m=int(input())
if m>max:
max=m
elif m<min:
min=m
print("\nlargest number is",max)
... | true |
800801cbdeb294ab5d70f3f6e5a625d8f377343f | chimaihueze/EDD-calculator | /EDD 2.py | 1,223 | 4.21875 | 4 | """
This promgram computes the Expected Date of Delivery (EDD) when a user
enters the date of their Last Menstrual Period (LMP).
"""
from datetime import timedelta, date
try:
#getting LMP from the user
lmp = input("Enter the date of your last period in DD-MM-YYYY format: ")
lst = lmp.split("-... | true |
24953a25857a31fb6d41955aa7d0e8774bfb5235 | CristofferJakobsson/sepm-team-a | /src/user_interface/centeredtext.py | 1,770 | 4.125 | 4 | class centeredtext(object):
"""
centeredtext extends the object class and centers text within an object
"""
def __init__(self, text, x,y,w,h, pygame, fontsize, color=(0,0,0)):
"""
Construct a new centeredtext object.
:param self: A reference to the centeredtext object itself
:param text: The te... | true |
011964435a3b4ba0046bebb406f45eababcf886f | Stephanie-Spears/LC101-Complete | /Unit1/Crypto/caesar.py | 1,010 | 4.21875 | 4 | """caesar shift module"""
from helpers import rotate_character, validate #, alphabet_position
def encrypt(text, rot):
"""shift string rot positions"""
new_text = ""
for char in text:
new_text += rotate_character(char, rot)
return new_text
def main():
"""encapsuate execution main"""
fro... | true |
911bf7bae8aefb880ffa09b7268665f002bb2fa8 | Ainnop/PYTHON-LEARNING | /nested_function.py | 425 | 4.1875 | 4 | def outer_function(x):
""" enclosing function
"""
def inner_function():
"""
nested function
"""
# nonlocal x
x = 5
print("The x value inside inner function is: {}".format(x))
x_local = x * 2
print("The x local value inside inner function is {}... | true |
b10d6dff6edd5f5e8da586f0a7ad4b51bb1b8c05 | patterson-dtaylor/100_Days_Of_Python | /Day_10/calculator.py | 1,842 | 4.3125 | 4 | calculator_power = True
first_calculation = True
total = 0
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def calculator(function=None, num1=0, num2=0):
if function == "... | true |
58f684be09fc2c363841b1f2696cdb472de70121 | Sheldonan2142/backup | /practice3.py | 411 | 4.375 | 4 | day = input("hey what day of the week is it? im mega lost ")
if day == "Monday" or day == "monday":
print("ah the weekend is over; it's monday")
if day == "Friday" or day == "friday":
print("friday !! the weekend is close friends")
if day == "Saturday" or day == "saturday" or day == "Sunday" or day == "sunday"... | true |
25faa2b23248280b65d4924bfce16e8ed4559e5f | Sheldonan2142/backup | /list.py | 1,300 | 4.40625 | 4 | # how to make a list
favMovies = ["Dora the Explorer", "The Emoji Movie", "High School Musical"]
# print the whole list
print(favMovies)
# print individuals
print(favMovies[2])
# to add you can append or insert
# append adds to the end
favMovies.append("High School Musical 2")
print(favMovies)
# insert will... | true |
3078b5dae76dd8e48600fca851c334639314d919 | irandjelovic/data-parser | /string_parser/remove_adjacent_same_letters.py | 2,124 | 4.21875 | 4 | #!/usr/bin/env python
'''
Simple string parser module with function(s):
- Remove adjacent pairs of same letters for an input string
'''
# standard lib
import argparse
arg_parser = argparse.ArgumentParser(description="Argument parser")
arg_parser.add_argument('-i', dest="input", help="Input string")
... | true |
951b5cfbb9d28aa1547c077ddac0b0d5fcfd146b | Jiaweihu08/EPI | /4 - Primitive types/4.0 - count_bits.py | 567 | 4.1875 | 4 | def count_bits_naive(x):
"""
x is a 64-bits integer, so the number of iterations here
is 64.
for each bit from the right, we check if it's 1 and then
remove it.
"""
num_bits = 0
while x:
num_bits += x & 1
x >>= 1
return num_bits
def count_bits_wegner(x):
"""
x & (x - 1) returns x with its last set bit... | true |
7bed948376991aa597310ec4fd65fefae91a431c | Jiaweihu08/EPI | /9 - Binary Trees/9.10 - inorder_traversal_no_recursion_with_parent_field.py | 511 | 4.1875 | 4 | """
Implement inorder traversal for binary trees without using recursion.
Hint: Analize cases depending on what the previous node is.
"""
def inorder_traversal(tree):
prev, results = None, []
while tree:
if prev is tree.parent:
if tree.left:
next = tree.left
else:
results.append(tree.data)
next =... | true |
4eab229f75cc28e91230150e4525b5e9bd567471 | Jiaweihu08/EPI | /12 - Hash Tables/12.3 - ISBN_cache.py | 2,681 | 4.40625 | 4 | """
Create a cache for looking up prices of books identified by their ISBN.
Implement lookup, insert, and erase methods. Use the LRU policy for cache
eviction - If the number of books exceeds the capacity of the cache when
inserting a new book, replace the oldest operated book with the new one
Use a hash table to stor... | true |
f8ce17590dcc54d24997126e3c75d39a732fc8ea | Jiaweihu08/EPI | /7 - Linked Lists/7.12 - is_palindromic_list.py | 1,873 | 4.3125 | 4 | """
Given a singly linked list, test is the data stored in the list
for a palindrom
"""
class Node:
def __init__(self, data=0, next_=None):
self.data = data
self.next = next_
def __repr__(self):
return f'Node: {self.data}'
def build_list(l):
L = [Node(l[0])]
for i in range(1, len(l)):
L.append(Node(l[i])... | true |
4e76efbcb5bba05f25fe376b11ee5b94ea7a2535 | Jiaweihu08/EPI | /9 - Binary Trees/9.2 - is_symmetric.py | 540 | 4.3125 | 4 | """
Check if a given binary tree is symmetric. If we draw a vertical line
through the root node, is the left tree the mirror image of the right
tree?
"""
def is_symmetric(tree):
def check_symmetric(subtree_0, subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_1 and subtree_1:
return (su... | true |
b38e80672246acac1f15ecbd209edde5980e1be1 | aml-spring-19/homework-1-nanshanli | /task1/task12.py | 420 | 4.125 | 4 | """Spring 2019 COMSW 4995: Applied Machine Learning.
UNI: nl2643
Homework 1 Task 1.2
Contains function that computes fibonacci sequence
"""
def fib(n):
"""Find fibonacci sequence for a given value n."""
prev = 1
curr = 1
if n == 1:
return 1
elif n == 2:
return 1
for i in r... | true |
2fa075710a19cd2db6c9704d6733665b9f568a19 | wajdm/ICS3UR-2-05-Python | /global_variables.py | 886 | 4.4375 | 4 | #!/usr/bin/env python 3
# Created by: Wajd Mariam
# Created on: Sept 2019
# This program shows how local and global variables works
# global variable
variable_X = 25
def local_variable():
# This variable shows what's happening with local_variable
variable_X = 10
variable_Y = 30
variable_A = variabl... | true |
cbee5a85ad921f68d1e925cf70cec15eb0afb788 | Aarom5/python-newbie | /dictionary.py | 275 | 4.28125 | 4 | classmates={'Tony':' cool but smells','Zack':' Sits at the front','Lucy': ' Weird'} # creates a set with key and values
print(classmates)
print(classmates['Zack']) # info about specific object
for k,v in classmates.items():# iterates through every item
print(k+v)
| true |
b49e59a06330afe5676d7a172b232948700d6b7b | YannisSchmutz/PythonTipsAndTricks | /generators/compute1.py | 981 | 4.1875 | 4 | """
Just the fundamental principe.
"""
from time import sleep
# Bad example
def compute():
"""
We would have to wait for the whole list, even though we might just need the first few element of it.
- takes a lot of time (for the first element being returned)
- needs much more memory than using an it... | true |
b5ed67afcf55f697d277aa0f714bf6ee7f091d12 | sarathrajkottamthodiyil/python | /Practise/list1.py | 299 | 4.125 | 4 | numbers = []
strings = []
names = ["sarath", "ajay", "arun"]
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("hello")
strings.append("friends")
second_name = names[1]
print(numbers)
print(strings)
print("the second name on the name list is !! %s !!" % second_name) | true |
5fb2dfa1d6d4d29f761d1e1593f0c5aa3b5de8d5 | RawandKurdy/snippets | /5_functions/function.py | 600 | 4.3125 | 4 | # Functions in Python
# 1- Traditional function
# also used to demonstrate how an anonymous func can be useful
# It runs a function passed as a param then prints its result
def traditionalFunc(anotherFunc):
text_with_duplicates = anotherFunc("NYC!", 3)
print(text_with_duplicates)
# 2- Anonymous Function
# I ... | true |
a6d6943be5220151308566d706edaf7a2e7e23ed | zcesur/algo | /tree_diam.py | 2,727 | 4.3125 | 4 | #!/usr/bin/env python
# A script that finds the diameter of a tree, which is defined as the
# maximum length of a shortest path. It runs in O(n+m) time, i.e., in
# time linear in the number of vertices and edges, which is equivalent
# to O(n) for trees.
#
# The main idea used in the algorithm is that the longest path ... | true |
c6ee234dcb13924182c3c0691b125481233bd68d | bliutwo/bliutwo_project_euler | /DigitFactorials/digitfactorials.py | 1,182 | 4.375 | 4 | # Filename: digitfactorials.py
# Description: https://projecteuler.net/problem=34
def factorial(num):
total = 1
while num > 0:
total *= num
num -= 1
return total
def lengthOfNum(num):
string = str(num)
return len(string)
def sumOfFactorialOfDigits(num):
total = 0
string = str(num)
for char in string:
d... | true |
12dcf665f4e0edf0299a3254854ce72d5d7ae9b6 | briwyatt/MITcomputerScience101 | /lecture03/lecture03.py | 1,261 | 4.15625 | 4 | # find the square root of a perfect square
# x = 16
# ans = 0 #counter variable
# while ans*ans <= x:
# ans = ans + 1
# print(ans)
# Is the number Even or Odd?
#
# if (x/2)*2 == x:
# print("Even")
# else:
# print("Odd")
# x = 150 #the number we are testing in this case
# ans = 0 #counter variable... | true |
5842de32ce5fc0fba622d0d07b63eea91cd7471f | Panmax/codewars-python | /look_and_say.py | 1,524 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: 'Panmax'
"""
There exists a sequence of numbers that follows the pattern
1
11
21
1211
111221
312211
13112221
1113213211
.
.
.
Starting with "1" the following lines are ... | true |
1a955c47291f3a2c6e22549649a25957c431c2f4 | naray89k/Python | /DeepDive_1/4_Numeric_Types/Comparison_Operators.py | 1,584 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Comparison Operators
# #### Identity and Membership Operators
# The **is** and **is not** operators will work with any data type since they are comparing the memory addresses of the objects (which are integers)
0.1 is (3+4j)
'a' is [1, 2, 3]
# The **in** and **not in** ope... | true |
457e4e90bda9e53e8554ca1064e184f4d4e4b841 | naray89k/Python | /DeepDive_1/4_Numeric_Types/Floats_Equality_Testing.py | 2,478 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Floats - Equality Testing
# Because not all real numbers have an exact ``float`` representation, equality testing can be tricky.
x = 0.1 + 0.1 + 0.1
y = 0.3
x == y
# This is because ``0.1`` and ``0.3`` do not have exact representations:
print('0.1 --> {0:.25f}'.format(0.1)... | true |
fd9e35d12f169d1abb5a971360db723c511f390f | naray89k/Python | /DeepDive_1/4_Numeric_Types/Booleans_Boolean_Operators.py | 1,833 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Booleans: Boolean Operators
# The way the Boolean operators ``and``, ``or`` actually work is a littel different in Python:
# #### or
# ``X or Y``: If X is falsy, returns Y, otherwise evaluates and returns X
'' or 'abc'
0 or 100
[] or [1, 2, 3]
[1, 2] or [1, 2, 3]
# You sh... | true |
121a2e796782216cde5bc857209565ce5e79738d | naray89k/Python | /DeepDive_1/2_A_Quick_Refresher_Basics_Review/Break_Continue_and_Try_Statements.py | 2,400 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Loop Break and Continue inside a Try...Except...Finally
# Recall that in a ``try`` statement, the ``finally`` clause always runs:
a = 10
b = 1
try:
a / b
except ZeroDivisionError:
print('division by 0')
finally:
print('this always executes')
# -----------------
... | true |
a8cd1fc49ca32a6a798216109975e0f68c8a4e25 | jatiinyadav/Python | /Class/Abstract.py | 957 | 4.1875 | 4 | # Abstract class
# Abstract Method, in a method where we have nothing in the method and we use pass
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def process(self):
pass
class Laptop(Computer):
def process(self):
print("Its running: ")
class Programmer:
... | true |
59fa82d39490e6c10e8fc7a9b0c1ee04ef1838f2 | KevinFTD/python_presentation | /exmaples/example8_cls_field.py | 371 | 4.125 | 4 | #!/usr/bin/env python2.7
#encoding=utf-8
'''
Created on 2015年4月7日
@author: kevinftd
'''
class MyClass(object):
key1 = 10
key2 = []
def __init__(self):
'''
Constructor
'''
self.key1 = 20
self.key2.append(30)
instance = MyClass()
print instance.key1
print MyClass.... | true |
e71d5f773f5f8236534832b40d2ddca0ad1b412b | KevinFTD/python_presentation | /exmaples/example_new_init.py | 740 | 4.28125 | 4 | #!/usr/bin/env python2.7
#encoding=utf-8
'''
Created on 2015年3月23日
@author: kevinftd
__new__创建类实例,__init__做初始化
'''
class base(object):
def __init__(self, arg="base"):
self.str = arg
def __str__(self):
return self.str
class strings(base):
def __init__(self, arg=""):
base.__init__(... | true |
eb375ea245384001f96c4f74b6da6e266f97477a | Phillip215/digitalcrafts | /week1/day3/inputPython.py | 1,255 | 4.25 | 4 | # name_of_user = input("What is your name?")
nameOfUser = input("What is your first name?")
# Store the users first name into a number value that we can use
lengthOfUserName = len(nameOfUser)
# While loop
# A condition has to be true to keep your loop running
while (lengthOfUserName < 1):
nameOfUser = input("What is... | true |
3fd11843ed03b30a3a694dd9508262418fa645f3 | nagask/python-essentials | /basic_collections/lists/sorting.py | 1,890 | 4.25 | 4 | import operator
# Sort a List Alphabetically
my_list = ['mango', 'apple', 'pear', 'orange']
my_list.sort()
for item in my_list:
print (item)
"""
Outputs:
apple
mango
orange
pear
"""
# Return a Copy of a List, Sorted Alphabetically
my_list = ['mango', 'apple', 'pear', 'orange']
my_sorted_list = sor... | true |
94790c09de2d538a75765223a3db2f7d6e98fad8 | nagask/python-essentials | /advanced_collections/defaultdict.py | 1,672 | 4.4375 | 4 | """
The collections module has a handy tool called defaultdict. The defaultdict is a subclass of Python’s dict that
accepts a default_factory as its primary argument. The default_factory is usually a Python type, such as int or list,
but you can also use a function or a lambda too.
It’s basically impossible to cause a... | true |
c4f40fb2866513f5e3fa663147cf4f6e17d317f0 | nancymukuiya14/Password-Locker | /user_test.py | 1,458 | 4.21875 | 4 | import unittest
from user import User
class TestClass(unittest.TestCase):
"""
A Test class that defines test cases for the User class.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"""
Method that runs before eac... | true |
64ec88ce1f194a7fc7d630deedd6208f10be0482 | teganbroderick/Calculator2 | /calculator.py | 1,929 | 4.25 | 4 | """A prefix-notation calculator."""
from arithmetic import *
def greet_player():
"""greets player"""
print("Hi Player! Welcome to the calculator.")
def turn_str_into_int(l):
"""takes list and turns string numbers into integers"""
operator_list = ["+", "-", "*", "/", "**", "squares", "cubes", "pows", ... | true |
9156f4bdcf549e4820910cacc8b25ddf53068652 | vennie1988/python_ref_code | /lambda.py | 680 | 4.34375 | 4 | """
lambdas:
lambda expressions (sometimes is called lambda forms) are used to create anonymous
functions. The expression lambda arguments: expression yields a function object.
The unnamed object behaves like a function object defined with the following.
"""
lambda_expr ::= "lambda" [parameter_list]: expression
lambda... | true |
475bded227f8ec6730ecececc165173b0e98bdf0 | HKang42/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 2,158 | 4.28125 | 4 | """
reverse the contents of the list using recursion, *not a loop.*
For example,
```
1->2->3->None
```
would become...
```
3->2->1->None
```
# CORRECITON: Loops are okay. Recursion is optional.
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = ne... | true |
b6d2aea38715a7ae5bf511a1bef05c1b45df0e4c | Ksheekey/RBootcamp | /cw/03-Python/2/Activities/02-Stu_KidInCandyStore-LoopsRecap/Unsolved/kid_in_candy_store.py | 672 | 4.34375 | 4 | # The list of candies to print to the screen
candy_list = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Swedish Fish", "Skittles", "Hershey Bar", "Starbursts", "M&Ms"]
# The amount of candy the user will be allowed to choose
allowance = 5
# The list used to store all of the candies selected inside of
can... | true |
29cf7ea6745659950bcee0725ee5a8a6556c37ce | Ksheekey/RBootcamp | /cw/03-Python/1/Activities/04-Stu_DownToInput/Unsolved/DownToInput.py | 1,016 | 4.125 | 4 | # Take input of you and your neighbor
me = input("What is your name? ")
neighbor = input("What is your neighbors name? ")
# Take how long each of you have been coding
me_coding = int(input("How many years have you been coding? "))
neighbor_coding = int(input("How long has your neighbor been coding? "))
# Add total ye... | true |
3a41cfe8aba9d9aa2daea650cc8a9f44121e3f1f | dupjpr/Hacker_Rank_challenge | /Agenda_while.py | 1,586 | 4.125 | 4 | print("Small Calculator")
print("""
Menu Options
1. Sum.
2. Weight Converter.
3. Guess Game.
4. Quit.
""")
command=""
while command != 4:
command=int(input("Opcin:"))
if command == 1:
print("__"*20)
print("You are in the space to sum two numbers")
a=int(input("First number: "))
b... | true |
d4f70cd8f154b59e562344c4525f2ae83884cce5 | ensarerturk/globalAiHubPythonHomework | /homework_1.py | 1,348 | 4.25 | 4 | #create an list
info=[]
#5 values received from the user and added to the list
name = input("Please enter your name : ")
info.append(name)
lastname = input("Please enter your lastname : ")
info.append(lastname)
#control was done. If the expected value is not entered, it has been requested to be re-entered.
try:
... | true |
051ab9274fa7a781326199086077b05fecba8a88 | cdebruyn/PackageName | /PackageName/sorting.py | 1,251 | 4.5625 | 5 | def bubble_sort(items):
'''Return array of items, sorted in ascending order.
Argument:
items (array): an array of numbers.
Returns:
array: items sorted in ascending order.
Examples:
>>> bubble_sort([5,4,3,2,1])
[1,2,3,4,5]
>>> bubble_sort([1,3,2])
[1,2,... | true |
9c06c1861d4e166d45e81c23111cfd09e8faa314 | wfields1/MIS3545 | /Assignments/assignment_1/palindrome.py | 646 | 4.25 | 4 | def isPalindrome(s):
"""
Write a recursive function isPalindrome(string) that returns True if string is a palindrome,
that is, a word that is the same when reversed. Examples of palindromes are “deed”, “rotor”, or
“aibohphobia”. Hint: A word is a palindrome if the first and last letters match and the ... | true |
b07940d23f4b7feec4b29662d117dece7090d68a | kristjanleifur4/forritun-2020 | /timaverk7.py | 2,675 | 4.125 | 4 | # The function definition goes here
def output_string(input_str):
for i in input_str:
return input_str[::2]
input_str = input("Enter a string: ")
# You call the function here
print("Every other character:",output_string(input_str))
# Your function definition goes here
def digit_count(input_str)... | true |
2eacfb81be308feccf1097b2bda36a780eb61dd2 | mandalpawan/Data-Stucture | /Stack/Stack.py | 782 | 4.125 | 4 | '''
Stack In Data Stucture
'''
class Stack:
def __init__(self):
self.item = []
"PUSH method is use for insert element in TOP of the STACK"
def push(self,item):
self.item.append(item)
"POP method is use to remove element from top of the stack"
def pop(self):
ret... | true |
e009e166a5260accd340fe69ad86e01f74fa589e | mandalpawan/Data-Stucture | /Stack/binary.py | 392 | 4.15625 | 4 | "Use Stack and Convert Decimal Number To Binary Number"
from Stack import Stack
def binary_Convertor(number):
s = Stack()
while number > 0:
remainder = number %2
s.push(remainder)
number = number //2
binary_number = ""
while not s.is_empty():
binary_number += str(s.p... | true |
80cb7a60563bcd2b1a9f0a9554b237c7b6ebd978 | GoogolDKhan/Student-Library | /main.py | 2,592 | 4.15625 | 4 | class Library:
# Constructor
def __init__(self, list_of_books):
self.books = list_of_books
# Method to display the books available in the library
def display_available_books(self):
print("Books available in this library are: ")
for index, book in enumerate(self.books):
... | true |
17c0758cf196d5916becaaffad5383fea3827536 | MohitMehta257/Show-me-the-Data-Structures | /problem_2.py | 879 | 4.375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix... | true |
76fc2fc987ac8afe42719e3d9563dc02f11d81e7 | VasBu/lrn_python3 | /src/Variables.py | 2,526 | 4.1875 | 4 | def basics():
print("\n****** Create and Delete Variables ******")
x = 42 # assigning integer variable
print("x = ", x)
print("id(x) = ", id(x)) # get reference (identifier) of the variable
y = x ... | true |
86f1796d0be666e3fd5a97530d548cd5bfd2c988 | ashirbad1212/Python-Task-1-by-Ashirbad | /main.py | 413 | 4.25 | 4 | #Accept two integer numbers from a user and return their product and if the product is greater than 1000, then return their sum
def product_sum(num1, num2):
product = num1 *num2
if(product <= 1000):
return product
else:
return num1 +num2
num1 = int(input("Please enter first number "))
num2 = int(input("... | true |
849fd5ed0c0a94f43c7b30a5bac23ee2105e5d73 | raghukhanal/Python3 | /Conditions.py | 313 | 4.15625 | 4 | age = 22
if age < 21:
print("No beer for you")
elif age == 21:
print("Yes, right on!")
else:
print("You definetely can!")
name = "Lucy"
if name is "Raghu":
print("Hey there Raghu")
elif name is "Lucy":
print("Hey hey, LUCEYYYYY")
else:
print("Hey there! please sign up for the site") | true |
5b87abe1523ed4403a73e19aa65520ab731d6e4d | israeljgarcia/OOP-Data-Structures | /encapsulation/_gpa.py | 2,445 | 4.375 | 4 | class GPA:
"""
The GPA class stores a student's GPA within the range of
0.0 and 4.0.
member variables: gpa
methods: __init__(), get_gpa(), set_gpa(value(float))
"""
def __init__(self):
"""
Initializes the gpa variable to 0.
return: none
"""
self._g... | true |
82a50c3979827e141f5f78904ca55cd355900534 | parasjitaliya/DataStructurePrograms | /stack.py | 1,672 | 4.125 | 4 | class Node:
# create a node
def __init__(self, data = None):
# initialize the first part of node is data
self.data = data
# initialize the second part of node is point address of next node
self.next = None
class Stack:
# head is default Null
def __init__(self):
s... | true |
8de9a315962e4c95ff00a876073dc450e520b43f | parasjitaliya/DataStructurePrograms | /queue.py | 1,571 | 4.15625 | 4 | class Node:
# create a node
def __init__(self, data = None):
# initialize the first part of node is data
self.data = data
# initialize the second part of node is point address of next node
self.next = None
class Queue:
# declaring the front,rare,count variables and initiali... | true |
1585c7c0468c3e8d710ebc3ec4c9e6b3ad9989bd | NSangita/Machine-Learning | /numpy-tutorial/ex01.py | 381 | 4.1875 | 4 | # Exercise 01: Extract elements from an array
# Declare and initialize an array as done below
# arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Then, extract all odd numbers from arr to achieve the desired output.
# Desired output:
# #> [1 3 5 7 9]
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9... | true |
ac40c43ff5057cf0b8a8c4eb67d1e68ba4b4f9cf | Ncalo19/general_python_practice | /Python_tutorial/14_classes_slash_objects.py | 1,418 | 4.34375 | 4 | # class is an object blueprint
# create an object blueprint
class class1:
name = 'Nick' # object: item inside a class
age = 23
print(class1)
# print an object
print(class1.name)
print(class1.age)
# use a period when extracting info about a class or performing an action on a script or array
# assign values to ... | true |
e689b9ebb684f88f2764418b6ea033216b88f2a4 | jainsimran/python-exercises | /strings.py | 802 | 4.28125 | 4 | #Strings are Arrays
str = "happy"
#loop
for x in str:
print(x)
# to check length
print(len(str))
# to check if a certain phrase or character is present in a string,
if "app" in str:
print("app is present in " + str)
if "tap" not in str:
print("tap is not present in " + str)
#Slicing Strings
print(st... | true |
30b54f8a93a3ccf721d40444cca9a1e1f6bae9e5 | aync19/InteractivePythonCoursera | /circle.py | 1,013 | 4.1875 | 4 | #Use buttons to increase and decrease the size of the circle
#Change color with input field
import simplegui
# Define globals - Constants are capitalized in Python
HEIGHT = 400
WIDTH = 400
RADIUS_INCREMENT = 5
ball_radius = 20
color = "Orange"
# Draw handler
def draw(canvas):
global ball_radius
canvas.draw_c... | true |
5e986e6230bae6882a92744b52f6b8102a3e9cde | deepali1232/divya-coding-classes | /basic_programs/program11.py | 573 | 4.28125 | 4 | #dictionary(key-value-pair)
d1={'apple':50,'mango':100,'guava':200,'banana':300}
print(d1)
print(type(d1))
#extracting keys
print(d1.keys())
#extracting values
print(d1.values())
#add new element in dict
d1['bag']=400
print(d1)
#change existing element or modify
d... | true |
b5d5ad2fd8f2eb6425d2684eb49b47ca4ed02d66 | deepali1232/divya-coding-classes | /basic_programs/basic32.py | 815 | 4.125 | 4 | #Python program to check if the given number is Happy Number
#Number = 32
#3^2+ 2^2 = 13
#1^2 + 3^2 = 10
#1^2 + 0^2 = 1
#isHappyNumber() will determine whether a number is happy or not
def isHappyNumber(num):
rem = sum = 0;
#Calculates the sum of squares of digits
while(num > 0): ... | true |
f969ad05d1ea8646a031ef1788c2d75075e1f627 | J-asy/Algorithms-and-Data-Structures | /boyer_moore/z_algo.py | 2,197 | 4.15625 | 4 | def z_algorithm(string):
""" Returns a z_array, such that for all i, z_array[i] contains
the length of the longest substring starting at position i of the
string that matches its prefix
:time complexity: O(n)
:space complexity: O(n), where n is the length of the string
"""
z_array =... | true |
4559c4687e3ac3c5ec8ad6c257a5fbbbb21a257d | GitBulk/datacamp | /marketing analytics with python/01 analyzing marketing campaigns with pandas/11_grouping_and_counting_by_multiple_columns.py | 1,189 | 4.1875 | 4 | '''
INTRODUCTION:
Grouping and counting by multiple columns
Stakeholders have begun competing to see whose channel had the best retention rate from the campaign. You must first determine how
many subscribers came from the campaign and how many of those subscribers have stayed on the service.
It's important to identify... | true |
08e5788255b2234ea69ddcc5b38aec34e27706ef | exfrioss/python_projects_for_beginners | /0_beginners_path/03_email_slicer.py | 1,002 | 4.40625 | 4 | """
Email slicer:
An email slicer is a very useful program for separating the username and domain name of an email address.
To create an email slicer with Python, our task is to write a program that can retrive the username and the
domain name of the email. For example: 'frioss@domain.com'.
So we need to divide the e... | true |
a9f563b4837e8cc91791bc8bc0b03a3cbea4d5c0 | johnwatterlond/playground | /matrix_printer.py | 2,290 | 4.6875 | 5 | """
Module for printing a matrix.
Matrix can be of any size and can contain numbers or words of any
length.
Matrix should be a list of rows where each row is a list.
Examples:
---------
Example 1:
In :
matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
print_matrix(matrix)
Out :
2 4 6
8 10 12
14 16 18
Exam... | true |
c8b643d16c3e97b66dc304ba2ab4323134de3430 | leoniepnzr/MyExercises | /ex18.py | 1,246 | 4.8125 | 5 | #functions: name pieces of code, take arguments, lets you do mini-scripts
#created with def
#* tells Python to take all arguments and collect them in list, like argv for functions
def print_two(*args):#make a function with "def", giving function a name, *args in parantheses to work, just like argv, start with :
ar... | true |
d566fd621c31a770484e719e9096930421f30c49 | leoniepnzr/MyExercises | /ex33.py | 399 | 4.25 | 4 | #while loops for running until Boolean expression is False
#to follow loop jumping, write print everywhere in code (top, middle, bottom) -> trying to understand
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the... | true |
976be5017743a3f36e2587676b76b4ae6bc7be8c | JuliusBoateng/data_structs_and_algs | /fundamentals/selection_sort.py | 780 | 4.125 | 4 | #!/usr/bin/env python3
import random
def find_index_of_min(arr, start):
min_element = arr[start]
min_index = start
for index in range(start + 1, len(arr)):
if arr[index] < min_element:
min_element = arr[index]
min_index = index
return min_index
def swap(arr, first, se... | true |
c1cc167c298d81f5eea15a63cbf1e0b5a0251769 | dathanwong/Dojo_Assignments | /Python/python/ForLoopBasicII.py | 2,346 | 4.15625 | 4 | #1. Biggie Size
#Given a list write a function that hanges all positive numbers to big
def biggie(list):
for x in range(len(list)):
if list[x] > 0:
list[x]="big"
return list
print(biggie([-2,3,5,-5]))
#2. Count Positives
# given a list of numbers replace the last value wiht the number of po... | true |
82818bf299d970c9bd47036bb268cc2c88330c41 | abhishekk40/Test1 | /test1.py | 423 | 4.15625 | 4 | a=6
y=0
for i in range(1,6): # Always keep the first loop for the Count of Number of lines
for j in range(1,y+1): # This loop is for Printing Space
print(" ",end=" ")
y=y+1 #This is for increasing the number of spaces everytime
for k in range(1,a): #This loop is for Printing "1"
print("1",en... | true |
18231c614f5ae04068e1b33132e31f3e16317f00 | jonvaljean/flask-course | /decorators.py | 1,102 | 4.59375 | 5 | #a decorator is a function that gets called before another function
#SAVE THESE TEMPLATES for decorators with and without parameters
import functools
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func():
print("in the decorator!")
func() #always call the func... | true |
58ec57242e5f775f110328bf2a8af557c9329c18 | HYPERTONE/EPI-Python | /Primitive Types/4.3 - Reverse Bits.py | 789 | 4.375 | 4 |
# Write a program that takes a 64-bit unsigned integer and returns the 64-bit unsigned integer consisting
# of the bits of the input in reverse order.
def reverseBit(num):
result = 0
while num:
result = (result << 1) + (num & 1)
num >>= 1
return result
# The goal here is to AND our num b... | true |
cbfc948f149cb6c96efa71a300146b902bf60b6f | HYPERTONE/EPI-Python | /Binary Trees/9.1 - Test If A Binary Tree Is Height-Balanced.py | 1,597 | 4.375 | 4 |
# A binary tree is said to be height balanced if for each node in the tree, the difference in height of its left and right subtrees
# is at most one. A perfect binary tree is height-balanced, as is a complete binary tree. A height-balanced binary tree does not have to
# be perfect or complete.
# Write a program that... | true |
5f5693cd376ba31a0f25d7882a7d34c71b255646 | HYPERTONE/EPI-Python | /Binary Trees/9.2 - Test If A Binary Tree Is Symmetric.py | 1,135 | 4.4375 | 4 |
# A binary tree is symmetric if you can draw a vertical line through the root and then the left subtree is a mirror image of the
# right subtree.
# Write a prgoram that checks whether a binary tree is symmetric.
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
... | true |
d63590eb2be1bc0891198db6fc5c4f19666a95d4 | chengjun0917/DailyQuestion | /shuaidi/question02.py | 1,650 | 4.15625 | 4 | from random import randint
from sys import exit
min_of_target = 0
max_of_target = 100
target = randint(min_of_target,max_of_target)
chances = 7
print("Welcome to guess number game!")
print(f"You have {chances} chances to guess the number, which is range from {min_of_target} to {max_of_target}.")
print("Each time you ... | true |
554532a2f891decc28fcbb9b448c4156825b1b41 | k1211/30daysHackerRank | /Day12/day12.py | 2,088 | 4.21875 | 4 | # You are given two classes, Person and Student, where Person is the base class and Student is the derived class.
# Completed code for Person and a declaration for Student are provided for you in the editor.
# Observe that Student inherits all the properties of Person.
#
# Complete the Student class by writing the foll... | true |
1e07fbc119e4d4714a20308b7d6c6a66d5f6250a | k1211/30daysHackerRank | /Day13/day13.py | 1,099 | 4.28125 | 4 | # Given a Book class and a Solution class, write a MyBook class that does the following:
#
# - Inherits from Book
# - Has a parameterized constructor taking these 3 parameters:
# - string title
# - string author
# - int price
# Implements the Book class' abstract display() method so it prints these 3 lines:... | true |
66a7797612d2d64534d42cb1a99951d8ca3ddd58 | k1211/30daysHackerRank | /Day3/day3.py | 569 | 4.5625 | 5 | # Given an integer, n , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5 , print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Complete the stub code provided in you... | true |
99d5cd5b49cf6dc7eefc30daae1d06d755c8364e | kiranraju03/PractiseCode | /HackerEarth/e-maze-in.py | 698 | 4.3125 | 4 | """
Maze display
A person is stuck in a maze at a starting position of (0,0), a route map is given as an input, find the end position
after he has traversed the route map
Route Map directions, L,R,U,D : left, right, up and down
Hint : Numberical Scale concept
Complexity:
Time : O(N) : N is the length of the route ma... | true |
e26ac036f6b8a05e4fde1e2d6e42e8dbe212272e | kiranraju03/PractiseCode | /Strings/CaesarCipher.py | 1,595 | 4.15625 | 4 | """
Caesar Cipher
Create an encrypted string using the key as the number of shifts to be made
"""
# Solution 1 : 26 characters Approach
# Time : O(1) : as we are dealing with only 26 characters, O(26), i.e., O(1) constant operation
# Space : O(n) : n is the length of the string that needs to be encrypted
def caesar_c... | true |
78cda78517737e238cdb18e820cee96de227f072 | kiranraju03/PractiseCode | /HackerRank/SockMerchant.py | 1,343 | 4.125 | 4 | """Find the number of pairs of socks from the set of socks
Input : number of socks (n) and array of socks ([])
Output : number of socks pairs available in the array
"""
from collections import Counter
def sockPairChecker(socks):
socks_count = Counter(socks)
for eachcount in socks_count:
sock_color = e... | true |
e6ab2e9ed88ef22e88e56ca8ca68640bd3d1ac88 | kiranraju03/PractiseCode | /Searching/ThreeLargeNumbers.py | 1,159 | 4.53125 | 5 | """
Find the 3 largest numbers in a array
Complexity :
Time : O(N) : N is the length of the array
Space : O(1) : Only shifting of values is involved
"""
# Helper method : Used to assign values to the three number array
# if the index is 2, then the values have to be left shifted once and so for others
def shift_updat... | true |
f9bd700a14a2def73cf25ffd208443c9f958fcd6 | a-soliman/py-hello_you | /hello.py | 605 | 4.15625 | 4 | '''
1. Ask user for name.
2. Ask user for age.
3. Ask user for city.
4. Ask user what they enjoy
5. Create output text.
6. Print output to screen
'''
from person_class import *
from sanitize import *
name = input('What is your name?: ')
name = trim(name)
name = make_lower(name)
name = make_title(name)
age ... | true |
ce8d3d9bc08854ea430b7b9b50d248d81772cf13 | hmangukia/Hack2020 | /Python/SumOfSquares.py | 581 | 4.25 | 4 | '''
This program finds the sum of square
of first n natural numbers.
Input is obtained from the user.
'''
def SumOfSquares(n):
sum = 0
for i in range(1, n+1):
sum = sum + i * i
return sum
def SquaresOfSum(n):
sum = 0
for i in range(1, n+1):
sum = sum + i
return (sum * sum)
n =... | true |
8709f9c81dbf0cff43a7b72b1bafc58dacc22669 | MoRahmanWork/Py4Fin | /LearningHowToCode/Programmiz/Functions.py | 1,374 | 4.40625 | 4 | def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not prov... | true |
3e362c72c37808bb83f742e336e7a354db4d1ee3 | carwyyn/Jumblejumble | /get_words.py | 742 | 4.375 | 4 | import pickle
#a function to retrieve the words from the text file, save them to a list of lists, and store it in pickle
def get_word(file_name, l_name):
#open the text file at the address of file_name
with open(file_name, "r+") as l_name:
#read the text file
whole = l_name.read()
#cre... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.