blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
32ecb9b4cfe42fc63007e72ac3c8778fa8121ad5 | huang-zp/pyoffer | /my_queue.py | 646 | 4.125 | 4 | class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack_in.append(x)
def pop(self)... | true |
aee36a7523ad8fc3de06ef7b047aff60fa3ab0d6 | ADmcbryde/Collatz | /Python/recursive/coll.py | 2,842 | 4.25 | 4 | # CSC330
# Assignment 3 - Collatz Conjecture
#
# Author: Devin McBryde
#
#
#
def collatzStep(a):
counter = 0
if (a == 1):
return counter
elif ( (a%2) == 1) :
counter = collatzStep(a*3+1)
else:
counter = collatzStep(a/2)
counter = counter + 1
return counter
#The program is programmed as a function sinc... | true |
0d075a750c9745eb97a2577db4b7c7cf2407d903 | ergarrity/coding-challenges | /missing-number/missing.py | 1,009 | 4.21875 | 4 | """Given a list of numbers 1...max_num, find which one is missing in a list."""
def missing_number(nums, max_num):
"""Given a list of numbers 1...max_num, find which one is missing.
*nums*: list of numbers 1..[max_num]; exactly one digit will be missing.
*max_num*: Largest potential number in list
>... | true |
8717208247c2d4f9eb24522c1b54ec33ce41789c | kwozz48/Test_Projects | /is_num_prime.py | 613 | 4.1875 | 4 | #Asks the user for a number and determines if the number is prime or not
number_list = []
def get_integer(number = 'Please enter a number: '):
return int(input(number))
def is_number_prime():
user_num = get_integer()
number_list = list(range(2, user_num))
print (number_list)
i = 0
a = 0
... | true |
0eb55829a0aee6d7136f91550e89b9bb738f4e73 | Scertskrt/Ch.08_Lists_Strings | /8.1_Months.py | 722 | 4.40625 | 4 | '''
MONTHS PROGRAM
--------------
Write a user-input statement where a user enters a month number 1-13.
Using the starting string below in your program, print the three month abbreviation
for the month number that the user enters. Keep repeating this until the user enters 13 to quit.
Once the user quits, print "Goodby... | true |
539fadb2fc145e48a70950cd77d804d77c9cec07 | roachaar/Python-Projects | /national debt length.py | 1,937 | 4.5 | 4 | ##############################################################################
# Computer Project #1: National Debt
#
# Algorithm
# prompt for national debt and denomination of currency
# user inputs the above
# program does simple arithmetic to calculate two pieces of informati... | true |
3597d031334cadd8da79740431f5941c2adb38c5 | BeryJAY/Day4_challenge | /power/power.py | 531 | 4.34375 | 4 | def power(a,b):
#checking data type
if not((isinstance(a,int) or isinstance(a,float)) and isinstance(b,int)):
return "invalid input"
#The condition is such that if b is equal to 1, b is returned
if(b==1):
return(a)
#If b is not equal to 1, a is multiplied with the power function and call... | true |
511d35743234e26a4a93653af24ee132b3a62a7a | AntoanStefanov/Code-With-Mosh | /Classes/1- Classes.py | 1,465 | 4.6875 | 5 | # Defining a list of numbers
numbers = [1, 2]
# we learned that when we use the dot notation, we get access to all methods in list objects.
# Every list object in Python has these methods.
# numbers.
# Wouldn't that be nice if we could create an object like shopping_cart and this object would have methods
# like this:... | true |
a8f7dceb7daec1a665e215d9d99eeb620e73f398 | AntoanStefanov/Code-With-Mosh | /Exceptions/7- Cost of Raising Exceptions.py | 1,849 | 4.5 | 4 | # As I explained in the last lecture, when writing your own functions,
# prefer not to raise exceptions, because those exceptions come with a price.
# That's gonna show you in this lecture.
# From the timeit module import function called timeit
# with this function we can calculate the execution time of some code.
# ... | true |
1f7f8382c688f22fe10e8057185ce55307c90b1d | AntoanStefanov/Code-With-Mosh | /Exceptions/4- Cleaning Up.py | 706 | 4.375 | 4 | # There are times that we need to work with external resources like files,
# network connections, databases and so on. Whenever we use these resources,
# after, after we're done we need to release them.
# For example: when you open a file, we should always close it after we're done,
# otherwise another process or anoth... | true |
a12230a5edc331e0989940c8ecd1243b9415aba9 | daria-andrioaie/Fundamentals-Of-Programming | /a12-911-Andrioaie-Daria/main.py | 2,983 | 4.46875 | 4 | from random import randint
from recursive import recursive_backtracking
from iterative import iterative_backtracking
def print_iterative_solutions(list_of_numbers):
"""
The function calls the function that solves the problem iteratively and then prints all the found solutions.
:param list_of_num... | true |
41891f9a090ead7873bf5c006f423238a48f05db | daria-andrioaie/Fundamentals-Of-Programming | /a12-911-Andrioaie-Daria/iterative.py | 2,158 | 4.5 | 4 | from solution import is_solution, to_string
def find_successor(partial_solution):
"""
The function finds the successor of the last element in the list.
By "successor" of an element we mean the next element in the list [0, +, -].
:param partial_solution: array containing the current partial so... | true |
48f7e3ee1d356eda254447e928321e6d7a8402c8 | samsolariusleo/cpy5python | /practical02/q07_miles_to_kilometres.py | 661 | 4.3125 | 4 | # Filename: q07_miles_to_kilometres.py
# Author: Gan Jing Ying
# Created: 20130207
# Modified: 20130207
# Description: Program that converts miles to kilometres and kilometres to miles
# before printing the results
# main
# print headers
print("{0:6s}".format("Miles") + "{0:11s}".format("Kilometres") +
"{0:11s... | true |
2e1e1897d6e0c4f92ee6815c9e1bb607dee10024 | samsolariusleo/cpy5python | /practical02/q12_find_factors.py | 562 | 4.4375 | 4 | # Filename: q12_find_factors.py
# Author: Gan Jing Ying
# Created: 20130207
# Modified: 20130207
# Description: Program that displays the smallest factors of an integer.
# main
# prompt for integer
integer = int(input("Enter integer: "))
# define smallest factor
factor = 2
# define a list
list_of_factors = []
# fi... | true |
750d0ff689da9aa8aea56e2e9b248df47ed51057 | samsolariusleo/cpy5python | /practical02/q05_find_month_days.py | 956 | 4.625 | 5 | # Filename: q05_find_month_days.py
# Author: Gan Jing Ying
# Created: 20130207
# Modified: 20130207
# Description: Program that displays number of days in the month of a particular
# year.
# main
# prompt for month
month = int(input("Enter month: "))
# prompt for year
year = int(input("Enter year: "))
# define list... | true |
cce715b6938e2f5c16d6ee158ebfa7e15b4e0645 | samsolariusleo/cpy5python | /practical02/q11_find_gcd.py | 725 | 4.28125 | 4 | # Filename: q11_find_gcd.py
# Author: Gan Jing Ying
# Created: 20130207
# Modified: 20130207
# Description: Program to find the greatest common divisor of two integers.
# main
# prompt user for the two integers
integer_one = int(input("Enter first integer: "))
integer_two = int(input("Enter second integer: "))
# fin... | true |
8254638df080d0a3b76a0dddd42cf41e393dfed7 | samsolariusleo/cpy5python | /practical01/q1_fahrenheit_to_celsius.py | 453 | 4.28125 | 4 | # Filename: q1_fahrenheit_to_celsius.py
# Author: Gan Jing Ying
# Created: 20130122
# Modified: 20130122
# Description: Program to convert a temperature reading from Fahrenheit to Celsius.
#main
# prompt to get temperature
temperature = float(input("Enter temperature (Fahrenheit): "))
# calculate temperat... | true |
8e1570c6e03ec4817ab65fdba077df7bad1e97da | justintrudell/hootbot | /hootbot/helpers/request_helpers.py | 490 | 4.46875 | 4 | import itertools
def grouper(iterable, n):
"""
Splits an iterable into groups of 'n'.
:param iterable: The iterable to be split.
:param n: The amount of items desired in each group.
:return: Yields the input list as a new list, itself containing lists of 'n' items.
"""
"""Splits a list int... | true |
73d37bf82e89c293e0e0fd86e99d74ec79b3b275 | SRAH95/Rodrigo | /input_statement.py | 1,748 | 4.15625 | 4 | """message = input("Tell me something, and I will repeat it back to you: ")
print(message)"""
########################################################################################
'''name = input("Please enter your name: ")
print("Hi, " + name.title() + "!")'''
####################################################... | true |
ba982e9794b3cbaaa034584cbb1f2017068f5ce5 | Pranalihalageri/Python_Eduyear | /day5.py | 516 | 4.125 | 4 | 1.
list1 = [5, 20, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Even numbers in the list: ", even_count)
print("Odd numbers in the lis... | true |
b0398f9d1751611c505aa530849336dbb7f3ef00 | Ran05/basic-python-course | /ferariza_randolfh_day4_act2.py | 1,153 | 4.15625 | 4 | '''
1 Write a word bank program
2 The program will ask to enter a word
3 The program will store the word in a list
4 The program will ask if the user wants to try again. The user will input
Y/y if yes and N/n if no
5 If yes, refer to step 2.
6 If no, Display the total number of words and all the words that user enter... | true |
92151c4a1ceca1910bd60785b2d5d030559cd241 | niteshrawat1995/MyCodeBase | /python/concepts/classmethods.py | 1,481 | 4.125 | 4 | # Class methods are methods wich take class as an argument (by using decorators).
# They can be used as alternate constructors.
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
sel... | true |
5f109dfef4214b33302401e473d9b115a65bffa5 | niteshrawat1995/MyCodeBase | /python/concepts/getters&setters&deleters.py | 1,284 | 4.15625 | 4 | # getters,setters and deleters can be implemented in python using property decorators.
# property decorators allows us to define a mehtod which we can access as an attribute.
# @property is the pythonic way of creating getter and setter.
class Employee(object):
def __init__(self, first, last, pay):
self.... | true |
e78334b2ae75714172fad80bf81e8c76497f7cb5 | scantea/hash-practice | /hash_practice/exercises.py | 2,554 | 4.3125 | 4 |
def grouped_anagrams(strings):
""" This method will return an array of arrays.
Each subarray will have strings which are anagrams of each other
Time Complexity: O(n)
Space Complexity: O(1)
"""
freq_hash = {}
for word in strings:
key = ''.join(sorted(word))
... | true |
5b119b5d6ee2dfeb455b174a2b2332de7cd7a6a7 | sivaram143/python_practice | /conditions/ex_01.py | 202 | 4.3125 | 4 | #!/usr/bin/python
# program to check whether a given no is even or ood
num = input("Enter any number:")
if num % 2 == 0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num)) | true |
fdc9e5dc5a169d1178cf3efa9e1f70a2f42576a1 | rcoady/Programming-for-Everyone | /Class 1 - Getting Started with Python/Assignment4-6.py | 982 | 4.375 | 4 | # Assignment 4.6
# Write a program to prompt the user for hours and rate per hour using raw_input to
# compute gross pay. Award time-and-a-half for the hourly rate for all hours worked
# above 40 hours. Put the logic to do the computation of time-and-a-half in a function
# called computepay() and use the function to do... | true |
73b0b07826794a242dde684f94f946581c180949 | Dszymczk/Practice_python_exercises | /06_string_lists.py | 803 | 4.40625 | 4 | # Program that checks whether a word given by user is palindrome
def is_palindrome(word):
return word == word[::-1]
word = "kajak" # input("Give me some word please: ")
reversed_word = []
for index in range(len(word) - 1, -1, -1):
reversed_word.append(word[index])
palindrome = True
for i in range(l... | true |
6fcd96b8c44668ccac3b4150d9b6c411b325bcc0 | mm/adventofcode20 | /day_1.py | 2,436 | 4.375 | 4 | """AoC Challenge Day 1
Find the two entries, in a list of integers, that sum to 2020
https://adventofcode.com/2020/day/1
"""
def find_entries_and_multiply(in_list, target):
"""Finds two entries in a list of integers that sum to a
given target (also an integer), and then multiply those afterwards.
"""
... | true |
7252e716f0bb533d1a612728caf027276883e0ef | git4rajesh/python-learnings | /String_format/dict_format.py | 800 | 4.5625 | 5 | ### String Substitution with a Dictionary using Format ###
dict1 = {
'no_hats': 122,
'no_mats': 42
}
print('Sam had {no_hats} hats and {no_mats} mats'.format(**dict1))
### String Substitution with a List using Format ###
list1 = ['a', 'b', 'c']
my_str = 'The first element is {}'.format(list1)
print(my_str)
... | true |
79618644a020eaa269bc7995d650afed3043b411 | ravitej5226/Algorithms | /backspace-string-compare.py | 1,312 | 4.15625 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# Example 1:
# Input: S = "ab#c", T = "ad#c"
# Output: true
# Explanation: Both S and T become "ac".
# Example 2:
# Input: S = "ab##", T = "c#d#"
# Output: true
# Explanation: Both S and ... | true |
08815d5371e53a75f10ec4d2b0b9bba1747a6fa6 | ravitej5226/Algorithms | /zigzag-conversion.py | 1,458 | 4.15625 | 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 thi... | true |
5fa0a0ab95042208eb2bef0dc47498c34056dda6 | arthuroe/codewars | /6kyu/sort_the_odd.py | 2,963 | 4.25 | 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
sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
'''
import sys
def sort_arr... | true |
78576dc109ab336280899a740fbc2f3797563e52 | bryansilva10/CSE310-Portfolio | /Language_Module-Python/Shopping-Cart_Dictionary/cart.py | 1,423 | 4.21875 | 4 | #var to hold dictionary
shoppingCart = {}
#print interface
print("""
Shopping Options
----------------
1: Add Item
2: Remove Item
3: View Cart
0: EXIT
""")
#prompt user and turn into integer
option = int(input("Select an option: "))
#while user doesn't exit program
while opt... | true |
9b72b3dd6d3aba0798f18f06ab37bdf0c39a339a | xu2243051/learngit | /ex30.py | 858 | 4.125 | 4 | #!/usr/bin/python
#coding:utf-8
#================================================================
# Copyright (C) 2014 All rights reserved.
#
# 文件名称:ex30.py
# 创 建 者:许培源
# 创建日期:2014年12月09日
# 描 述:
#
# 更新日志:
#
#================================================================
import sys
reload(sys)
sys.se... | true |
3c4cb233be63715f662d6f81f76feae91e51ac85 | cupofteaandcake/CMEECourseWork | /Week2/Code/lc1.py | 1,787 | 4.375 | 4 | #!/usr/bin/env python3
"""A series of list comprehensions and loops for creating sets based on the bird data provided"""
__appname__ = 'lc1.py'
__author__ = 'Talia Al-Mushadani (ta1915@ic.ac.uk)'
__version__ = '0.0.1'
__license__ = "License for this code"
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.... | true |
0b4d452a26c2b44684c2eae50ba622c56dd97f4f | kriti-ixix/python2batch | /python/Functions.py | 614 | 4.125 | 4 | '''
Functions are of two types based on input:
- Default
- Parameterised
Based on return type:
- No return
- Some value is returned
'''
'''
#Function definition
def addTwo(first, second):
#first = int(input("Enter first number: "))
#second = int(input("Enter second number: "))
third = ... | true |
2bbe8852b53fe5d099afbbd8a310704c04c0423b | mecosteas/Coding-Challenges | /count_words.py | 1,260 | 4.375 | 4 | """
Given a long text string, count the number of occurrences of each word. Ignore case. Assume the boundary of a word is whitespace - a " ", or a line break denoted by "\n". Ignore all punctuation, such as . , ~ ? !. Assume hyphens are part of a word - "two-year-old" and "two year old" are one word, and three differen... | true |
507e4a5ea9054c11509e8d6f678d74aa6c3f545e | sleepingsaint/DS-ALG | /DS/linkedList.py | 2,724 | 4.21875 | 4 | # defining stack element object
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
# defining stack object
class Stack(object):
def __init__(self, head=None):
self.head = head
# helper class functions
# function to add elements
def append... | true |
d5891584688ff83c60bf74fc7611c625f57b14db | Sukanyacse/Assignment_2 | /assignment 2.py | 254 | 4.1875 | 4 | numbers=(1,2,3,4,5,6,7,8,9)
count_even=1
count_odd=-1
for value in range(1,10):
if(value%2==0):
count_even=count_even+1
else:
count_odd=count_odd+1
print("Number of even numbers:",count_even)
print("Number of odd numbers:",count_odd)
| true |
e644585b9b3a99f72e3ed4fc948ecb26ca0465f0 | moheed/python | /languageFeatures/python_using_list_as_2d_array.py | 1,976 | 4.5625 | 5 | #NOTE: creating list with comprehension creates many
#pecularities.. as python treats list with shallow copy...
#for example
arr=[0]*5 #=== with this method, python only creates one integer object with value 5 and
#all indices point to same object. since all are zero initially it doesn't matter.
arr[0]=5 #when we ... | true |
92a753e7e633025170d55b3ebdb9f2487b3c4fa0 | HayleyMills/Automate-the-Boring-Stuff-with-Python | /Ch6P1_TablePrinter.py | 1,352 | 4.4375 | 4 | ##Write a function named printTable() that takes a list of lists of strings
##and displays it in a well-organized table with each column right-justified.
##Assume that all the inner lists will contain the same number of strings.
##For example, the value could look like this:
##tableData = [['apples', 'oranges', '... | true |
e317905dca19712d90a62f463a4f782bd22668e5 | Ahmad-Magdy-Osman/IntroComputerScience | /Classes/bankaccount.py | 1,195 | 4.15625 | 4 | ########################################################################
#
# CS 150 - Worksheet #11 --- Problem #1
# Purpose: Practicing User-Defined Classes.
#
# Author: Ahmad M. Osman
# Date: December 9, 2016
#
# Filename: bankaccount.py
#
########################################################################
cla... | true |
b19db0ac2fef12e825b63552fbd0b298fcb632ec | Ahmad-Magdy-Osman/IntroComputerScience | /Turtle/ex10.py | 859 | 4.65625 | 5 | ######################################
#
# CS150 - Interactive Python; Python Turtle Graphics Section, Exercise Chapter - Exercise 10
# Purpose: Drawing a clock with turtles
#
# Author: Ahmad M. Osman
# Date: September 22, 2016
#
# Filename: ex10.py
#
#####################################
#Importing turtle module
imp... | true |
bbcefac3f0243ed8df81ed8a4875626b78ab3ca4 | iangraham20/cs108 | /labs/10/driver.py | 976 | 4.5 | 4 | ''' A driver program that creates a solar system turtle graphic.
Created on Nov 10, 2016
Lab 10 Exercise 5
@author: Ian Christensen (igc2) '''
import turtle
from solar_system import *
window = turtle.Screen()
window.setworldcoordinates(-1, -1, 1, 1)
ian = turtle.Turtle()
ss = Solar_System()
ss.add_sun(Sun("SUN", 8.... | true |
0e75d78ea6d8540a5417a8014db80c0b84d32cc9 | iangraham20/cs108 | /projects/07/find_prefix.py | 1,677 | 4.125 | 4 | ''' A program that finds the longest common prefix of two strings.
October 25, 2016
Homework 7 Exercise 7.3
@author Ian Christensen (igc2) '''
# Create a function that receives two strings and returns the common prefix.
def common_prefix(string_one, string_two):
''' A function that compares two strings, determines... | true |
50b03235f4a71169e37f3ae57654b7a37bcb9d10 | adamsjoe/keelePython | /Week 3/11_1.py | 246 | 4.125 | 4 | # Write a Python script to create and print a dictionary
# where the keys are numbers between 1 and 15 (both included) and the values are cube of keys.
# create dictonary
theDict = {}
for x in range(1, 16):
theDict[x] = x**3
print(theDict) | true |
86e3aa25fd4e4878ac12d7d839669eda99a6ea1c | adamsjoe/keelePython | /Week 1/ex3_4-scratchpad.py | 964 | 4.125 | 4 | def calc_wind_chill(temp, windSpeed):
# check error conditions first
# calc is only valid if temperature is less than 10 degrees
if (temp > 10):
print("ERROR: Ensure that temperature is less than or equal to 10 Celsius")
exit()
# cal is only valid if wind speed is above 4.8
if (windS... | true |
d3ab5cfe7bb1ff17169b2b600d21ac2d7fabbf70 | adamsjoe/keelePython | /Week 8 Assignment/scratchpad.py | 1,193 | 4.125 | 4 | while not menu_option:
menu_option = input("You must enter an option")
def inputType():
global menu_option
def typeCheck():
global menu_option
try:
float(menu_option) #First check for numeric. If this trips, program will move to except.
if float(menu_option).is_integer(... | true |
8a527fd405d5c59c109252f58527d9b4d5e73eeb | sahaib9747/Random-Number-Picker | /App_Manual.py | 607 | 4.125 | 4 | # starting point
import random
number = random.randint(1, 1000)
attempts = 0
while True: # infinite loop
input_number = input("Guess the number (berween 1 and 1000):")
input_number = int(input_number) # converting to intiger
attempts += 1
if input_number == number:
print("Yes,Your guess is c... | true |
19eff193956da31d7bf747a97c0c0a7fe5da9f91 | Sukhrobjon/Codesignal-Challenges | /challenges/remove_duplicates.py | 433 | 4.1875 | 4 | from collections import Counter
def remove_all_duplicates(s):
"""Remove all the occurance of the duplicated values
Args:
s(str): input string
Returns:
unique values(str): all unique values
"""
unique_s = ""
s_counter = Counter(s)
for key, value in s_counter.items():
... | true |
e18278d472ab449a3524864656540432b7efbfb9 | robinsuhel/conditionennels | /conditionals.py | 365 | 4.34375 | 4 | name = input("What's your name: ")
age = int(input("How old are you: "))
year = str(2017-age)
print(name + " you born in the year "+ year)
if age > 17:
print("You are an adult! You can see a rated R movie")
elif age < 17 and age > 12:
print("You are a teenager! You can see a rated PG-13 movie")
else:
print("You are... | true |
43264f35f210963e7b6aeda37a534bc52302fec5 | wscheib2000/CS1110 | /gpa.py | 966 | 4.21875 | 4 | # Will Scheib wms9gv
"""
Defines three functions to track GPA and credits taken by a student.
"""
current_gpa = 0
current_credit_total = 0
def add_course(grade, num_credit=3):
"""
This function adds a class to the gpa and credit_total variables, with credits defaulting to 3.
:param grade: Grade in the ... | true |
583480d2f366d7fcbf1a9f16c03c40c8e3f1248b | SeanLuTW/codingwonderland | /lc/lc174.py | 2,254 | 4.15625 | 4 | """
174. Dungeon Game
The demons had captured the princess (P) and imprisoned her in the bottom-top corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The... | true |
30a665a286f0dcd8bd5d60d78fae0d1669f2e0c1 | SeanLuTW/codingwonderland | /lc/lc1464.py | 761 | 4.25 | 4 | """
1464. Maximum Product of Two Elements in an Array
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from ... | true |
a0f06e65c70862194f25bee20a4ad1eed82ae586 | dharmit/Projects | /Numbers/mortgage.py | 460 | 4.25 | 4 | #!/usr/bin/env python
def mortgage_calculator(months, amount, interest):
final_amount = amount + ((amount * interest)/100)
return int(final_amount / months)
if __name__ == "__main__":
amt = int(raw_input("Enter the amount: "))
interest = int(raw_input("Enter the interest rate: "))
months = int(ra... | true |
baf234ed556488a5d5a8f1229b5bf69958b232e1 | krakibe27/python_objects | /Bike.py | 802 | 4.125 | 4 | class Bike:
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 200
#self.miles = self.miles + self.miles
def displayInfo(self):
print "Price :", self.price
print "max_speed :" + self.max_speed
print "total ... | true |
832a79bbaf9f1961dc580f064efbf1903057d803 | OnurcanKoken/Python-GUI-with-Tkinter | /6_Binding Functions to Layouts.py | 1,154 | 4.3125 | 4 | from tkinter import * #imports tkinter library
root = Tk() #to create the main window
#binding a function to a widget
#define a function
def printName():
print("My name is Koken!")
#create a button that calls a function
#make sure there is no parantheses of the function
button_1 = Button(root, text="Print my na... | true |
36c4a847bad96bae252543ca9c12fb6ac5dc1abc | Juan55Camarillo/pattern-designs | /strategy.py | 1,433 | 4.625 | 5 | '''
Strategy pattern designs example
it allows make an object can behave in different ways
(which will be define in the moment of its instantiation or make)
'''
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Map():
def __init__(self, generateMap: Ge... | true |
a34063f6b6ba6e086b633508fad186b4e9622df7 | sachinsaini4278/Data-Structure-using-python | /insertionSort.py | 622 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 07:18:31 2019
@author: sachin saini
"""
def insertion_sort(inputarray):
for i in range(size):
temp=inputarray[i]
j=i
while(inputarray[j-1]>temp and j >=1):
inputarray[j]=inputarray[j-1];
j=j-1
i... | true |
9259a3b6575504831a6c9a4601035771b48e1ced | mattwright42/Decorators | /decorators.py | 1,560 | 4.15625 | 4 | # 1. Functions are objects
# def add_five(num):
#print(num + 5)
# add_five(2)
# 2. Functions within functions
# def add_five(num):
# def add_two(num):
# return num + 2
#num_plus_two = add_two(num)
#print(num_plus_two + 3)
# add_five(10)
# 3. Returning functions from functions
# def get_math_function(operati... | true |
f5edb7b29e99421eff0a071312619d011e833038 | lucipeterson/Rock-Paper-Scissors | /rockpaperscissors.py | 2,800 | 4.125 | 4 | #rockpaperscissors.py
import random
print("~~ Rock, Paper, Scissors ~~")
weapon_list = ["rock", "paper", "scissors"]
user = input("Rock, paper, or scissors? ")
while user.lower() not in weapon_list:
user = input("Rock, paper, or scissors? ")
computer = random.choice(weapon_list)
print("Computer chooses " + comput... | true |
ef949c39755d56c5dbf3ef5bd9212bfb36a2df92 | aseemchopra25/Integer-Sequences | /Juggler Sequence/juggler.py | 706 | 4.21875 | 4 | # Program to find Juggler Sequence in Python
# Juggler Sequence: https://en.wikipedia.org/wiki/Juggler_sequence
# The juggler_sequence function takes in a starting number and prints all juggler
# numbers starting from that number until it reaches 1
# Keep in mind that the juggler sequence has been conjectured to reach... | true |
f013a0c4604d3a39edf17405d34a5a1ff4722167 | aseemchopra25/Integer-Sequences | /Golomb Sequence/Golomb.py | 1,460 | 4.25 | 4 | # A program to find the nth number in the Golomb sequence.
# https://en.wikipedia.org/wiki/Golomb_sequence
def golomb(n):
n = int(n)
if n == 1:
return 1
# Set up a list of the first few Golomb numbers to "prime" the function so to speak.
temp = [1, 2, 2, 3, 3]
# We will be modifying the li... | true |
0b8cfda80341f33b7ec168156f82dcc2dc32e618 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/fibMultpleEff.py | 695 | 4.21875 | 4 | # Efficient way to check if Nth fibonacci number is multiple of a given number.
# for example multiple of 10.
# num must be multiple of 2 and 5.
# Multiples of 2 in Fibonacci Series :
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 ….
# every 3rd number - is divisible by 2.
# Multiples of 5 in Fibonacci ... | true |
87e12cbe64f2cfcdf00157e8bc34e39485f64773 | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/makePerfectSq.py | 842 | 4.1875 | 4 | # Find minimum number to be divided to make a number a perfect square.
# ex - 50 dividing it by 2 will make it perfect sq. So output will be 2.
# A number is the perfect square if it's prime factors have the even power.
# all the prime factors which has the odd power should be multiplied and returned(take 1 element ... | true |
bc28541b378f69e1b7ef435cff0f4094c4ca75e2 | PSDivyadarshini/C-97 | /project1.py | 298 | 4.21875 | 4 | myString=input("enter a string:")
characterCount=0
wordCount=1
for i in myString :
characterCount=characterCount+1
if(i==' '):
wordCount=wordCount+1
print("Number of Word in myString: ")
print(wordCount)
print("Number of character in my string:")
print(characterCount)
| true |
8aff8f034cb41fa3efa60a2441b29e8cd056d3aa | katteq/data-structures | /P2/problem_1.py | 1,315 | 4.34375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number == 0 or number == 1:
return number
start = 0
end = number
res = 0
i = 0
whil... | true |
23766aad682eccf45ca95ba6cd539d82568a7192 | blbesinaiz/Python | /displayFormat.py | 286 | 4.125 | 4 | #Program Title: Formatted Display
#Program Description: Program takes in a string, and outputs the text
# with a width of 50
import sys
string = input("Please enter a string: ")
for i in range(10):
sys.stdout.write('['+str(i)+']')
print(string)
| true |
e2b69836a22a3feda9a41bdc13c7a7761a276faf | tomcusack1/python-algorithms | /Arrays/anagram.py | 841 | 4.125 | 4 | def anagram(str1, str2):
'''
Anagram function accepts two strings
and returns true/false if they are
valid anagrams of one another
e.g. 'dog' and 'god' = true
:string str1:
:string str2:
:return: boolean
'''
str1 = str1.replace(' ', '').lower()
str2 = str2.replace(' ', '').l... | true |
b66019522fe2066decb573e28901a0014f73f41d | guilmeister/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 274 | 4.15625 | 4 | #!/usr/bin/python3
def uppercase(str):
result = ''
for letters in str:
if ord(letters) >= 97 and ord(letters) <= 122:
result = result + chr(ord(letters) - 32)
else:
result = result + letters
print("{:s}".format(result))
| true |
dac58c8d8c1ad1f712734e2d33407c270ba38aae | cloudavail/snippets | /python/closures/closure_example/closure_example.py | 1,039 | 4.375 | 4 | #!/usr/bin/env python
# objective: create and explain closures and free variables
def add_x(x):
def adder(num):
# closure:
# adder is a closure
#
# free variable:
# x is a free variable
# x is not defined within "adder" - if "x" was defined within adder
# if... | true |
293ae711c7822c3d67b20ae236d6c9d4445b4ee7 | sonalisharma/pythonseminar | /CalCalc.py | 2,514 | 4.3125 | 4 | import argparse
import BeautifulSoup
import urllib2
import re
def calculate(userinput,return_float=False):
"""
This methos is used to read the user input and provide and answer. The answer is computed dircetly
using eval method if its a numerical expression, if not the wolfram api is used to get the appropriate ans... | true |
e06b35be36c3eed153be97a95a5aa802b9c33008 | khanma1962/Data_Structure_answers_Moe | /100 exercises/day10.py | 2,799 | 4.34375 | 4 | '''
Question 31
Question:
Define a function which can print a dictionary where the keys are numbers between
1 and 20 (both included) and the values are square of keys.
'''
def print_dict(start = 1, end = 20):
d = {}
for i in range(start, end+1):
# print(i)
d[i] = i ** 2
print(d)
# print_d... | true |
3e19b68db20afb1391f15588b5b559546479eb76 | 3l-d1abl0/DS-Algo | /py/Design Patterns/Structural Pattern/decorator.py | 1,356 | 4.25 | 4 | '''
Decorator Pattern helps us in adding New features to an existing Object Dynamically,
without Subclassing.
The idea behind Decorator Patter is to Attach additional responsibilities to an object Dynamically.
Decorator provide a flexible alternative to subclassing for extending Functionality.
'''
class WindowInterf... | true |
a9c3eaf87fb86da5486d03a66ca702d6d27f083e | Nikoleta-v3/rsd | /assets/code/src/find_primes.py | 697 | 4.3125 | 4 | import is_prime
import repeat_divide
def obtain_prime_factorisation(N):
"""
Return the prime factorisation of a number.
Inputs:
- N: integer
Outputs:
- a list of prime factors
- a list of the exponents of the prime factors
"""
factors = []
potential_factor = 1
... | true |
4923d24d114c3ce22708e6f941fe5cc89e660547 | EmonMajumder/All-Code | /Python/Guest_List.py | 1,399 | 4.125 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Data_to_file
"""
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
fileName=input("File Name: ")
accessMode=input("A... | true |
e1457e85ef66c4807ffcb5446b89813e27644908 | EmonMajumder/All-Code | /Python/Leap_Year.py | 1,319 | 4.4375 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Leap_year
"""
#Pseudocode
# 1. Define name of the function
# 2. Select variable name
# 3. Assign values to 3 variable for input %4, 100 & 400
# 4. determine if inpu... | true |
a595f993f1f05e9bd3552213aca426ca69610ab1 | LarisaOvchinnikova/Python | /HW2/5 - in column.py | 401 | 4.3125 | 4 | # Print firstname, middlename, lastname in column
firstName = input("What is your first name? ")
middleName = input("What is your middle name? ")
lastName = input("What is your last name? ")
m = max(len(firstName), len(lastName), len(middleName))
print(firstName.rjust(m))
print(middleName.rjust(m))
print(lastName.rjus... | true |
ef36ed78ceee68ae2d14c1bb4a93605c164c9795 | LarisaOvchinnikova/Python | /1 - Python-2/10 - unit tests/tests for python syntax/variable assignment1.py | 682 | 4.15625 | 4 | # Name of challenger
# Variable assignment
# Create a variable with the name `pos_num` and assign it the value of any integer positive number in the range from 10 to 200, both inclusive.
#Open test
class TestClass(object):
def test_1(self):
"""Type of variable is int"""
assert type(pos_num) == in... | true |
04f9664ad8d43e67c386a917ee8b28127b32315d | LarisaOvchinnikova/Python | /1 - Python-2/4 - strings functions/Determine the properties of a string.py | 1,124 | 4.25 | 4 | #Print word " has lowercase letters" if it has only lowercase alphabet characters
# Print word " has uppercase letters"
# if it has only uppercase alphabet characters
# Print word " has so many letters. Much wow."
# if it has both uppercase and lowercase alphabet characters but no digits
# Print word " has digits" if
#... | true |
703bd7118ff467dc98f9b6a3802ca1b74df9e2a5 | itsmesanju/pythonSkills | /leetCode/7.reverseInteger.py | 912 | 4.15625 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Example ... | true |
132c2bba74dfd857faaf3ed42033376e3e9dfb0c | ACNoonan/PythonMasterclass | /ProgramFlow/aachallenge.py | 287 | 4.21875 | 4 | number = 5
multiplier = 8
answer = 0
# iterate = 0
# add your loop after this comment
# My Soultion:
# while iterate < multiplier:
# answer += number
# iterate += 1
# The solution she told you not to worry about
for i in range(multiplier):
answer += number
print(answer)
| true |
915de4df06984d86f0237064bb6d0bf015a1d893 | v2webtest/python | /app.py | 307 | 4.25 | 4 | print("Starting programme..")
enType: int = int(input("\n\nEnter program type.. ").strip())
print(enType)
# Checking of Type and printing message
if enType == 1:
print("-- Type is First.")
elif enType == 2:
print("-- Type is Second.")
else:
print("-- Unknown Type!")
print("End of program.")
| true |
b9be0492e6edd04f2f5bf78d3ea0ec63915baed4 | Ayon134/code_for_Kids | /tkinter--source/evet.py | 649 | 4.3125 | 4 | #handling button click
#when you press button what will happen
import tkinter
#create a window
window = tkinter.Tk()
window.title("Welcome to Tkinter World :-)")
window.geometry('500x500')
label = tkinter.Label(window, text = "Hello Word!", font=("Arial Bold", 50))
label.grid(column=0, row=0)
def clicked():
... | true |
9df7f613f1f637be2df86dd57d4b255abd91b932 | infantcyril/Python_Practise | /Prime_Count_Backwards.py | 2,061 | 4.1875 | 4 | check_a = 0
a = 0
def prim(check,a):
check_a = 0
while (check_a == 0):
try:
check_a = 1
a = int(input("Enter the Number from where you want to start searching: "))
if (a <= 2):
check_a = 0
print("Please enter a value greater t... | true |
722d462d7142bc66c5abcbcf23867507d5f116cb | r4isstatic/python-learn | /if.py | 417 | 4.4375 | 4 | #!/usr/bin/env python
#This takes the user's input, stores it in 'name', then runs some tests - if the length is shorter than 5, if it's equal to, and if it equals 'Jesse'.
name = raw_input('Please type in your name: ')
if len(name) < 5:
print "Your name is too short!"
elif len(name) == 5:
print "Your name is the ... | true |
1c9ec18cd80266e53d4e2f01d73dc0c9fb0099f0 | npradaschnor/algorithms_module | /caesar_cipher.py | 960 | 4.34375 | 4 | # Based on Caesar's Cipher
#Substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number (offset) of positions down the alphabet.
#In this case is upper in the alphabet
def encrypt(plain_text, offset):
cipher_text = ""
for i in plain_text: #for every char in text inputted
... | true |
3bbce6604801ae9019975edc3ce0e07ea347b90c | npradaschnor/algorithms_module | /odd_position_elements_array.py | 1,141 | 4.15625 | 4 | #Write an algorithm that returns the elements on odd positions in an array.
#Option 1 using 2 functions
def range_list(array):
array = range(0,len(array))
i = []
for e in array:
i.append(e)
return i
def odd_index(array):
oddl = []
a = range_list(array)
for n in a:
if n%2 != 0: #... | true |
ea07e7f7353344e90bbc9e4b0ccdff5ebc22a87f | npradaschnor/algorithms_module | /merge.py | 561 | 4.1875 | 4 | #recursive function that returns a merged list (1 element of str1 + 1 element of str2...and so on)
def merge(str1,str2):
if len(str1) == 0: #if the number of element in the str1 is zero, return str2
return str2
elif len(str2) == 0: # if the number of element in the str2 is zero, return str1
return str1
... | true |
7ca02e4f2af417d3a67f16cd90e3f87c722515c2 | Necron9x11/udemy_pythonWorkbook100Exercises | /ex-20/ex-20.py | 1,065 | 4.15625 | 4 | #!/usr/bin/env python3
#
# Python Workbook - 100 Exercises
# Exercise # NN
#
# Points Value: NN
#
# Author: Daniel Raphael
#
# ---------------------------------------------------------------------------------------------------------------------
#
# Question: Calculate the sum of all dictionary values.
#
# d = {"a"... | true |
7db32d46a6e1435dd916719ac8093b32206e4688 | hfu3/text-mining | /Session12/anagrams.py | 945 | 4.375 | 4 | """
1. read the file, save the words into a list
2. (option 1) count letters for each word
'rumeer' -> 6
'reemur' - 6
'kenzi' -> 5
(option2) sort the word
'rumeer' -> 'eemrru' sig
'reemur' - 'eemrru' sig
'kenzi' -> 'ekinz' sig
create empty list for each signature
expected:
['rumeer', 'reemur']
['kenzi']
4. creat... | true |
54861c9c20c34fb60f1507432dec0e7db836758a | kalebinn/python-bootcamp | /Week-1/Day 3/linear_search.py | 1,164 | 4.25 | 4 | # TODO: Write a function that takes a integer and a list as the input.
# the function should return the index of where the integer was found
# on the list
def search(x, list):
"""
this function returns the index of where the element x was found
on the list.
\tparam : x - the element you're searching fo... | true |
c9f4678ea364b027e5577856fe95ac2fd07c23e0 | kalebinn/python-bootcamp | /Week-1/Day 1/4-loops.py | 265 | 4.1875 | 4 | counter = 0
while counter <= 0:
print(counter)
counter += 1
# range(start, stop, increment)
print("using three inputs to range()")
for number in range(0,5,1):
print(number)
print("using one input to range()")
for number in range(5):
print(number) | true |
e05b380f577208e1df340765ae6a0232b7c5b7f4 | Katezch/Python_Fundamentals | /python_fundamentals-master/02_basic_datatypes/2_strings/02_07_replace.py | 382 | 4.34375 | 4 | '''
Write a script that takes a string of words and a symbol from the user.
Replace all occurrences of the first letter with the symbol. For example:
String input: more python programming please
Symbol input: #
Result: #ore python progra##ing please
'''
s = input(" please input words here: ")
symbol = input("please ... | true |
8b8af177b6a6b2af1f96d5d9c75d7b166f1e15ab | Katezch/Python_Fundamentals | /python_fundamentals-master/07_classes_objects_methods/07_01_car.py | 852 | 4.4375 | 4 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and dem... | true |
14d06fa26fb51aecf4a59fa232e410742d8c0487 | nietiadi/svm4r | /old/proving.py | 1,023 | 4.125 | 4 | #!/usr/bin/python3
"""
using ctl-rp to prove all proofs and give the answer, which is either 'sat' or 'unsat'
"""
import itertools
import csv
def proving(num_of_propositions=2, with_empty_clause=False):
"""
create the csv file containing the results from ctl-rp
"""
if with_empty_clause:
fname = 'data/pro... | true |
caa45bf56cd1b83f43c9ee05ebd9c618b74f8527 | rtejaswi/python | /rev_str_loop.py | 794 | 4.34375 | 4 | '''str = "Python"
reversedString=[]
index = len(str) # calculate length of string and save in index
while index > 0:
reversedString += str[ index - 1 ] # save the value of str[index-1] in reverseString
index = index - 1 # decrement index
print(reversedString) # reversed string'''
'''str = 'Python' #initial s... | true |
6c1b6b9a6c235826ace320eae96868b1a754a05d | gregorybutterfly/examples | /Decorators/1-python-decorator-example.py | 886 | 4.46875 | 4 | #!/usr/bin/python
""" A very simple example of how to use decorators to add additional functionality to your functions. """
def greeting_message_decorator(f):
""" This decorator will take a func with all its contents and wrap it around WRAP func.
This will create additional functionality to the 'greeting_mess... | true |
3f78094152b4c5759fa4776296a4dd47e48d4b61 | sam676/PythonPracticeProblems | /Robin/desperateForTP.py | 1,004 | 4.28125 | 4 | """
You've just received intel that your local market has received a huge
shipment of toilet paper! In desperate need, you rush out to the store.
Upon arrival, you discover that there is an enormously large line of
people waiting to get in to the store. You step into the queue and start
to wait. While you wait, you bei... | true |
269910439e357f1e3e9b1576e08dc319918b9406 | sam676/PythonPracticeProblems | /Robin/reverseMessage.py | 1,083 | 4.21875 | 4 | """
Today's question
You are a newbie detective investigating a murder scene in the boardroom
at the Macrosoft Corp. While searching for clues, you discover a red notebook.
Inside of the notebook are long journal entries with inverted messages.
At that moment, you remembered from your profiler father’s advice that
you ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.