blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
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 correct!")
break # finish the game if true
if input_number > number:
print("Incorrect! Please try to guess a smaller number")
else:
print("Incorrect! Please try to guess a larger number")
print("You Tried", attempts, "Times to find the correct number")
| 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():
if value == 1:
unique_s += key
return unique_s
s = "zzzzzzz"
print(remove_all_duplicates(s))
| 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 a child! You can only see rated PG movies")
| 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 class
:param num_credit: How many credits the class was worth
:return: Does not return any values
"""
global current_gpa, current_credit_total
current_gpa = (current_gpa * current_credit_total + grade * num_credit) / (current_credit_total + num_credit)
current_credit_total = current_credit_total + num_credit
def gpa():
"""
This function returns the current GPA.
:return: Current GPA, rounded to 2 decimal places
"""
return round(current_gpa, 2)
def credit_total():
"""
This function returns the current credit total.
:return: Current credit total
"""
return current_credit_total
| 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 knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only topward or leftward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path top-> top -> left -> left.
-2 (K) -3 3
-5 -10 1
10 30 -5 (P)
Note:
The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-top room where the princess is imprisoned.
"""
"""
intuition:
TC:O(n^2)
SC:O(m*n)
"""
# class Solution:
# def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
r = len(dungeon)
c = len(dungeon[0])
#create dp table
dp = [[0 for _ in range (c)] for _ in range (r)]
print (dp)
#initailze the right bottom corner as 1
dp[-1][-1] = 1
# print (dp)
for i in range (r-2,-1,-1):#handling column and start from the top
print (i,c)
dp[i][c-1] = max(1,dp[i+1][c-1]-dungeon[i+1][c-1])
# print (dp)
for j in range (c-2,-1,-1):#handling row and start from the bottom row
print(j,r)
dp[r-1][j] = max(1,dp[r-1][j+1]-dungeon[r-1][j+1])
# print (dp)
for i in range (r-2,-1,-1):
for j in range (c-2,-1,-1):
print(i,j)
top = max(1,dp[i][j+1]-dungeon[i][j+1])
print (top)
left = max(1,dp[i+1][j]-dungeon[i+1][j])
print (left)
dp[i][j] = min(top,left)
print (max(1,dp[0][0]-dungeon[0][0])) | 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 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
"""
nums = [3,4,5,2]
nums.sort()#asc order
# max1 = nums[-1]-1
# max2 = nums[-2]-1
# print (max1*max2)
print ((nums[-1]-1)*(nums[-2]-1))
| 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(raw_input("Enter the number of months: "))
print "Mortgage to be paid per month is: %d" % mortgage_calculator
(months, amt, interest)
| 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 miles :", self.miles
return self
def ride(self):
k = self.miles/10
for i in range(10,self.miles,10):
#k = self.miles/10
print "Miles increased by :", i
return self
def reverse(self):
for i in reversed(range(10,self.miles,10)):
print "Reversed Miles by 10 :", i
return self
bike1 = Bike(200,'10 mph')
#print bike1.displayInfo().ride().reverse()
print bike1.displayInfo()
| 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 name", command=printName)
button_1.pack()
"""
there is another way to do this
we will deal with an evet
it is being used for smt that occurs
such as button click from the user or mouse movement or button click on the keyboard
smt that user can do
bind takes two parameters;
what event are you waiting for to occur and what function do you want to call
"""
#define a function
#we have an event at this time
def printName2(event):
print("Again, My name is Koken!")
#make sure there is no parantheses of the function
button_2 = Button(root, text="Again, Print my name")
button_2.bind("<Button-1>", printName2) #left mouse button
button_2.pack()
root.mainloop() #makes sure it is being shown continuously, on the screen
#for more info: https://www.youtube.com/watch?v=RJB1Ek2Ko_Y&t=1s&list=PL6gx4Cwl9DGBwibXFtPtflztSNPGuIB_d&index=2 | 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: GenerateMap) -> None:
self._generateMap = generateMap
@property
def generateMap(self) -> generateMap:
return self._generateMap
@generateMap.setter
def generateMap(self, generateMap: GenerateMap) -> None:
self._generateMap = generateMap
def RandomSeed(self) -> None:
print("Generating a random location of the objects:")
result = self._generateMap.randomizer([" Map size: 1212", " Enemies location: 2737", " Dungeons Location: 6574"])
print(",".join(result))
class Generator(ABC):
@abstractmethod
def randomizer(self, data: List):
pass
class WaterLand(Generator):
def randomizer(self, data: List) -> List:
return sorted(data)
class EarthLand(Generator):
def randomizer(self, data: List) -> List:
return reversed(sorted(data))
class main():
map1 = Map(WaterLand())
print("Generating a random map of water.")
map1.RandomSeed()
print()
map2 = Map(EarthLand())
print("Generating a random map of earth.")
map1.RandomSeed()
| 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
inputarray[j]=temp
print("Enter the size of input array")
size=int(input())
print("Enter the ", size ," elements of array")
inputarray=[int(x) for x in input().split()]
print("elements before sorting ",inputarray)
insertion_sort(inputarray)
print("elements after sorting ",inputarray)
| 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(operation): # + or -
# def add(n1, n2):
# return n1 + n2
# def sub(n1, n2):
# return n1 - n2
# if operation == '+':
# return add
# elif operation == '-':
# return sub
#add_function = get_math_function('+')
#sub_function = get_math_function('-')
#print(sub_function(4, 6))
# 4. Decorating a function
# def title_decorator(print_name_function):
# def wrapper():
# print("Professor:")
# print_name_function()
# return wrapper
# def print_my_name():
# print("Matt")
# def print_joes_name():
# print("Joe")
#decorated_function = title_decorator(print_joes_name)
# decorated_function()
# 5. Decorators
# def title_decorator(print_name_function):
# def wrapper():
# print("Professor:")
# print_name_function()
# return wrapper
# @title_decorator
# def print_my_name():
# print("Matt")
# @title_decorator
# def print_joes_name():
# print("Joe")
# print_my_name()
# print_joes_name()
# 6. Decorators w/ Parameters
def title_decorator(print_name_function):
def wrapper(*args, **kwargs):
print("Professor:")
print_name_function(*args, **kwargs)
return wrapper
@title_decorator
def print_my_name(name, age):
print(name + " you are " + str(age))
print_my_name("Shelby", 60)
| true |
db09cc8134b15bce20a0f6f74d73e67e2ec723ee | The-Coding-Hub/Comp-Class-Code-Notes | /Python/q1.py | 451 | 4.4375 | 4 | # Enter 3 number and print the greatest one.
n1 = int(input("Number 1: "))
n2 = int(input("Number 2: "))
n3 = int(input("Number 3: "))
if n1 > n2 and n1 > n3:
print(f"{n1} is largest")
if n2 > n1 and n2 > n3:
print(f"{n2} is largest")
if n3 > n2 and n3 > n1:
print(f"{n3} is largest")
# OR
if n1 > n2 and n1 > n3:
print(f"{n1} is largest")
elif n2 > n1 and n2 > n3:
print(f"{n2} is largest")
else:
print(f"{n3} is largest") | false |
da463aae470f86a5d4bc9a9175f6c4b32f71f323 | The-Coding-Hub/Comp-Class-Code-Notes | /Python/calculator.py | 438 | 4.4375 | 4 | # Simple Calculator
num_1 = float(input("Number 1: "))
num_2 = float(input("Number 2: "))
operator = input("Operator (+, -, *, /): ")
result = None
if (operator == "+"):
result = num_1 + num_2
elif (operator == "-"):
result = num_1 - num_2
elif (operator == "*"):
result = num_1 * num_2
elif (operator == "/"):
result = num_1/num_2
else:
result = "Operator not found!"
print(f"Result:\n{num_1} {operator} {num_2} = {result}") | false |
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 " + computer + ".")
if computer == "rock":
if user.lower() == "rock":
print("It's a tie!")
elif user.lower() == "paper":
print("Paper smothers rock. You win!")
elif user.lower() == "scissors":
print("Rock crushes scissors. You lose.")
if computer == "paper":
if user.lower() == "rock":
print("Paper smothers rock. You lose.")
elif user.lower() == "paper":
print("It's a tie!")
elif user.lower() == "scissors":
print("Scissors cut paper. You win!")
if computer == "scissors":
if user.lower() == "rock":
print("Rock crushes scissors. You win!")
elif user.lower() == "paper":
print("Scissors cut paper. You lose.")
elif user.lower() == "scissors":
print("It's a tie!")
again = input("Play again? ")
while again.lower() == "yes":
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 " + computer + ".")
if computer == "rock":
if user.lower() == "rock":
print("It's a tie!")
again = input("Play again? ")
elif user.lower() == "paper":
print("Paper smothers rock. You win!")
again = input("Play again? ")
elif user.lower() == "scissors":
print("Rock crushes scissors. You lose.")
again = input("Play again? ")
if computer == "paper":
if user.lower() == "rock":
print("Paper smothers rock. You lose.")
again = input("Play again? ")
elif user.lower() == "paper":
print("It's a tie!")
again = input("Play again? ")
elif user.lower() == "scissors":
print("Scissors cut paper. You win!")
again = input("Play again? ")
if computer == "scissors":
if user.lower() == "rock":
print("Rock crushes scissors. You win!")
again = input("Play again? ")
elif user.lower() == "paper":
print("Scissors cut paper. You lose.")
again = input("Play again? ")
elif user.lower() == "scissors":
print("It's a tie!")
again = input("Play again? ")
if again.lower() != "yes":
print("Game Over")
| true |
05e109d5d83c0e438b89cdb3e6d4f650885eae16 | jdb158/problems | /problem108-try2.py | 1,246 | 4.15625 | 4 | import math
primes = [2,3]
largestprime = 3
def main():
test = 80
pflist = primeFactors(test)
print (pflist)
def primeFactors(number):
factors = []
global largestprime # grab our largest generated prime
# check already generated primes
while (number > 1):
for i in primes:
if (number % i == 0):
number = number / i
factors.append (i)
break
# end if
# end for
# if we made it all the way through, break
if (i == largestprime):
break
# end if
# end while
# check if we need to generate new primes
if (largestprime < math.sqrt(number)):
while (largestprime < math.sqrt(number)):
largestprime += 2
# check if new largestprime is actually prime
isprime = True
for i in primes:
if (largestprime % i == 0):
isprime = False
break
# end if
# end for
# if it's prime, add it to the list
if (isprime):
primes.append(largestprime)
# also check if this is a factor of number
if (number % largestprime == 0):
number = number / largestprime
factors.append (largestprime)
# end if
# end if
# end while
# end if
if (number > 1):
factors.append(number)
# end if
return (factors)
# end primeFactors
main()
# TIDALWAVE | false |
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 1 eventually
# but this fact has not yet been proved
def juggler_sequence(n):
seq = [n]
while seq[-1] != 1:
if seq[-1] % 2 == 0:
seq.append(int(seq[-1] ** 0.5))
else:
seq.append(int(seq[-1] ** 1.5))
return seq
if __name__ == "__main__":
x = int(input("Enter a number for Juggler Sequence: "))
print(juggler_sequence(x))
| 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 list, so we will use a while loop to continually check if we can get the nth number yet.
while len(temp) < n:
# Here comes the fun part. Starting with 0, we loop through every number (i) lower than n to build the Golomb list as much as we need.
for i in range(n):
# If the list is longer than (i), we skip it.
if len(temp) > i:
continue
# If the list ISN'T longer than (i), which it shouldn't be, we do some stuff.
else:
# We set a variable for the final value in the list, so we can increment it as we go.
lastval = temp[-1]
# We grab the number at the lastval index in the list, and set that to be our range.
# We add lastval+1 (the next element in the sequence) to the list (range) times, and then move to the next (i)
for x in range(temp[lastval]):
temp.append(lastval + 1)
# Once we have extended the list to or beyond the length of n, we can now grab the number in position n in the list!
return temp[n - 1]
print(golomb(input("Enter n> ")))
| 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 Series :
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 ……
# Every 5th number is divisible by 5.
# => Every 15th number will be divisible by 10. So we only need to check if n is divisible
# by 15 or not. We do not have to calculate the nth Fib number.
def isDivisibleby_10(n):
if n % 15 == 0:
return True
return False
# time complexity - O(1) | 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 at once).
import math
def findMinNum(n):
# 2 is only even number so counting the power of 2
count = 0
ans = 1
while n % 2 == 0:
count += 1
n = int(n // 2)
# if count is not even then we must remove one 2.
if count % 2 != 0:
ans = ans * 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
count = 0
while n % i == 0:
count += 1
n = int(n // i)
if count % 2 != 0:
ans = ans*i
if n > 2:
ans = ans * n
return ans
print(findMinNum(72)) | true |
014cad9a68bf6b18ab7d860dff49d1e1393137eb | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/primeFactors.py | 401 | 4.25 | 4 | # for 12 -- print 2,2,3
import math
def primeFactors(n):
while n % 2 == 0 and n > 0:
print(2)
n = n // 2
# n becomes odd after above step.
for i in range(3, int(math.sqrt(n) + 1), 2):
while n % i == 0:
print(i)
n = n // i
# until this stage all the composite numbers have been taken care of.
if n > 2:
print(n)
primeFactors(315) | false |
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 |
119132fefe6c5cb1a977f2128e39676187b178f4 | suryaprakashgiri01/Mini-Calculator | /calc.py | 1,375 | 4.1875 | 4 |
# This is a Mini calculator
print()
print(' ------------------------------------------------------------------')
print(' | Welcome to the mini calculator |')
print(' | Code By : SP |')
print(' ------------------------------------------------------------------')
print()
con = True
while(con):
print()
print('Enter the expression as num1 sign num2 :',end=' ')
exp = input()
exp_l = exp.split(' ')
print()
if exp_l[1] == '+':
result = int(exp_l[0]) + int(exp_l[2])
print(exp+' = '+str(result))
elif exp_l[1] == '-':
result = int(exp_l[0]) - int(exp_l[2])
print(exp+' = '+str(result))
elif exp_l[1] == '*' or exp_l[1] =='×':
result = int(exp_l[0]) * int(exp_l[2])
print(exp+' = '+str(result))
elif exp_l[1] == '/' or exp_l[1] == '÷':
result = int(exp_l[0]) / int(exp_l[2])
print(exp+' = '+str(result))
elif exp_l[1] == '%':
result = int(exp_l[0]) % int(exp_l[2])
print(exp+' = '+str(result))
elif exp_l[1] == '^':
result = int(exp_l[0]) ** int(exp_l[2])
print(exp+' = '+str(result))
else:
print('Invalid Type of Input')
print('\nDo you want to continue[y/n] :',end=' ')
x = input()
if x=='n' or x=='N':
print('\nThank you for using...')
con = False
print()
| false |
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
while not res:
i += 1
if start == end:
res = start
break
median = round(end - (end-start)/2)
number_sqrt = median*median
if number_sqrt == number:
res = median
break
number_sqrt_next = (median+1)*(median+1)
if number_sqrt > number:
end = median
else:
if number_sqrt_next > number:
res = median
break
start = median
return round(res)
print("Pass" if (3 == sqrt(9)) else "Fail")
print("Pass" if (0 == sqrt(0)) else "Fail")
print("Pass" if (4 == sqrt(16)) else "Fail")
print("Pass" if (1 == sqrt(1)) else "Fail")
print("Pass" if (5 == sqrt(27)) else "Fail")
print("Pass" if (75 == sqrt(5625)) else "Fail")
print("Pass" if (123 == sqrt(15129)) else "Fail")
print("Pass" if (1234 == sqrt(1522756)) else "Fail")
print("Pass" if (274003 == sqrt(75078060840)) else "Fail")
print("Pass" if (18 == sqrt(345)) else "Fail")
| 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(' ', '').lower()
# Edge case check
if len(str1) != len(str2):
# There are differing numbers of letters
return False
count = {}
for letter in str1:
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for letter in str2:
if letter in count:
count[letter] -= 1
else:
count[letter] = 1
for k in count:
if count[k] != 0:
return False
return True
print anagram('abc', 'abc')
| 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 would be local and would be printed by "local()"
# x is not a parameter, either, only "num" is passed in
return x + num
return adder
add_5 = add_x(5)
# sets add_5 equal to the return value of add_x(5)
# the return value of add_x(5) is a function
# that returns x (which we defined as 5) + an num
#
# def adder(num):
# return 5 + num
#
# add_5 is a function
print 'add_5 is a {}.'.format(add_5.__class__)
print add_5(10)
# and another example, generating a function "add_10" with the x
# variable closed over
add_10 = add_x(10)
print 'add_10 is a {}.'.format(add_10.__class__)
print add_10(21)
# the functions add_5 and add_10 have closed over the "x"
# which is bound for each function
| 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 answer.
Parameters:
userinput : This is a string, passed by the user in command line
e.g. "3*4+12" or "mass of moon in kgs"
return_float: This is to provide the output format, when specified as true then float is returned
Execution:
calculate("3*4+12", return_float=True)
Output:
The result is either a float or a string
"""
try:
#This is to make sure user does not provide remve, delete or other sys commands in eval
#eval is used purely for numeric calculations here.
if (bool(re.match('.*[a-zA-Z].*', userinput, re.IGNORECASE))):
raise Exception ("Try with wolfram")
else:
ans = eval(userinput)
if return_float:
ans = float(re.findall(r'\d+', ans))
return ans
except Exception:
data = urllib2.urlopen('http://api.wolframalpha.com/v2/query?appid=UAGAWR-3X6Y8W777Q&input='+userinput.replace(" ","%20")+'&format=plaintext').read()
soup = BeautifulSoup.BeautifulSoup(data)
keys = soup.findAll('plaintext')
if (keys):
#Printing the first returned rresult of the query. The first result is the heading, second
#result is the actual value hence printing [1:2]
for k in keys[1:2]:
ans = k.text
else:
ans = "Sorry! No results found, try another question!"
return ans
def test_1():
assert abs(4.0 - calculate("2**2")) < 0.001
def test_2():
assert calculate("total states in US") == '50'
def test_3():
assert calculate("56*3+1000%2") == '168'
def test_4():
assert 'Alaska' in calculate("largest state in US")
def test_5():
assert '8' in calculate("planets in our solar system")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Evaluating command line expressions')
parser.add_argument('-s', action="store",help='Enter an expression to evaluate e.g. 3*4-5*6 or "mass of moon in kgs" , make sure the string is provided within quotes')
try:
results = parser.parse_args()
ans = calculate(results.s,return_float=True)
if ans=="":
ans="Sorry! No results found, try another question!"
print "You Asked: %s" %results.s
print "Answer: %s" %ans
except:
print "There is an error in your input, check help below"
parser.print_help()
| 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_dict()
'''
Question 32
Question:
Define a function which can generate a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys. The function
should just print the keys only.
'''
def print_dict2(start = 1, end = 20):
d = {}
for i in range(start, end+1):
# print(i)
d[i] = i ** 2
for j in d.keys():
print(j, end = " ")
print('\n')
for j in d.values():
print(j, end = " ")
# print_dict2()
'''
Question 33
Question:
Define a function which can generate and print a list where the values are square of
numbers between 1 and 20 (both included).
'''
def print_list(start = 1 , end = 20):
lst = []
for i in range(start, end + 1):
lst.append(i ** 2)
print(lst)
# print_list()
'''
Question 34
Question:
Define a function which can generate a list where the values are square of numbers
between 1 and 20 (both included). Then the function needs to print the first 5 elements
in the list.
'''
def print_list(start = 1 , end = 20):
lst = []
for i in range(start, end + 1):
lst.append(i ** 2)
for i in range(5):
print(lst[i], end = ' ')
# print_list()
'''
Question 35
Question:
Define a function which can generate a list where the values are square of numbers
between 1 and 20 (both included). Then the function needs to print the last 5 elements
in the list.
'''
def print_list(start = 1 , end = 20):
lst = []
for i in range(start, end + 1):
lst.append(i ** 2)
for i in range(5):
print(lst[len(lst) - i - 1], end = ' ')
# print(lst[-i:])
print(lst[-5:])
# print_list()
'''
Question 36
Question:
Define a function which can generate a list where the values are square of numbers
between 1 and 20 (both included). Then the function needs to print all values except
the first 5 elements in the list.
'''
def print_list(start = 1 , end = 20):
lst = []
for i in range(start, end + 1):
lst.append(i ** 2)
for i in range(5, len(lst)):
# print(i)
print(lst[i], end = ' ')
# print(lst[-i:])
print(lst[5:])
# print_list()
'''
Question 37
Question:
Define a function which can generate and print a tuple where the value are square of
numbers between 1 and 20 (both included).
'''
def print_tuple(start = 1, end = 20):
lst = []
for i in range(start, end + 1):
lst.append(i ** 2)
print(tuple(lst))
print_tuple()
| 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 WindowInterface:
def build(self): pass
class Window(WindowInterface):
def build(self):
print("Building Window")
class AbstractWindowDecorator(WindowInterface):
"""
Maintain a reference to a Window Object and define an interface
that conforms to Window's Interface.
"""
def __init__(self, window):
self._window = window
def build(self): pass
class BorderDecorator(AbstractWindowDecorator):
def add_border(self):
print("Adding Border")
def build(self):
self.add_border()
self._window.build()
class VerticalSBDecorator(AbstractWindowDecorator):
def add_vertical_scroll_bar(self):
print("Adding Vertical Scroll Bar")
def build(self):
self.add_vertical_scroll_bar()
self._window.build()
class HorizontalSBDecorator(AbstractWindowDecorator):
def add_horizontal_scroll_bar(self):
print("Adding Horizontal Scroll Bar")
def build(self):
self.add_horizontal_scroll_bar()
self._window.build()
| 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
while N > 1:
potential_factor += 1
if is_prime.is_prime(potential_factor):
N, exponent = repeat_divide.repeat_divide_number(N, potential_factor)
if exponent > 0:
factors.append((potential_factor, exponent))
return factors
print(obtain_prime_factorisation(2 ** 3 * 11 * 23))
print(obtain_prime_factorisation(7))
| 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("Access Mode: ")
myfile=open(fileName,accessMode)
while True:
guestName=input("Please enter your name: ")
myfile.write(guestName+" , ")
while True:
guestAge=input("Please enter your age: ")
if guestAge.isnumeric()==True:
guestAge=int(guestAge)
if guestAge>0 and guestAge<150:
myfile.write("{0}\n".format(guestAge))
break
else:
print("Incorrect input.")
else:
print("Incorrect input.")
while True:
decision=input("Want to leave? (yes/no): ")
if decision.lower()=="yes" or decision.lower()=="no" or decision.lower()=="y" or decision.lower()=="n" :
break
else:
print("please input yes or no only")
if decision.lower()=="yes" or decision.lower()=="y":
myfile.close()
break
#Your code ends on the line above
#Do not change any of the code below!
if __name__ == "__main__":
main() | 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 input is devisible by 4, 100 and 400 as needed through if logic
# 5. return value from the function if leap year or not
# 6. Assign input to a variable for year to check
# 7. Call function and assign value to a variable
# 8. print the result
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
def leapyearteller (year):
remainderFor4=year%4
remainderFor100=year%100
remainderFor400=year%400
if remainderFor4==0 and remainderFor100>0:
decision= "is a Leap year"
elif remainderFor400==0:
decision= "is a Leap year"
else:
decision= "is not a Leap year"
return decision
yeartoCheck=int(input("Please enter the year that you want to check if it is a leap year: "))
decision=leapyearteller (yeartoCheck)
print("{0} {1}".format(yeartoCheck,decision))
#Your code ends on the line above
#Do not change any of the code below!
if __name__ == "__main__":
main() | true |
0182b73ebf8268ed9fd3ecb5fb18fe3feaf0ba84 | LarisaOvchinnikova/Python | /HW11 - lottery and randoms/methods strptime and strftime.py | 1,651 | 4.15625 | 4 | from datetime import datetime, date, timedelta
today = datetime.today()
print(str(today)) # 2020-05-10 20:46:17.842205
print(type(str(today))) # <class 'str'>
# strftime - переводим время из формата datetime в строку
today = today.strftime("%B %d, %Y") # %B - полный месяц, % d - номер дня, %Y год
print(today) # "May 10, 2020
# создадим другое время
d = datetime(2020, 6, 12)
d = d.strftime("%B %d, %Y")
print(d) # June 12, 2020
# создадим другое время
d = datetime(2020, 9, 12)
d = d.strftime("%b %d, %Y") # %b - сокращенное название месяца Sep
print(d) # Sep 12, 2020
d = datetime(2020, 9, 12)
d = d.strftime("Today is %d %b, %Y") # %b - сокращенное название месяца Sep
print(d) # Today is 12 Sep, 2020
# strptime(строка, формат) ---> перевод строки в datetime
d = datetime(2020, 9, 12)
d = d.strftime("%d %b, %Y")
print(d) # "12 Sep, 2020"
# print(type(d)) # str
print(datetime.strptime(d, "%d %b, %Y")) # 2020-09-12 00:00:00
day = datetime.strptime(d, "%d %b, %Y")
print(type(day)) # <class 'datetime.datetime'>
day = datetime.strptime(d, "%d %b, %Y").date()
print(type(day)) # <class 'datetime.date'>
print(day) # 2020-09-12
today = datetime(2020, 9, 12)
print(today) # 2020-09-12 00:00:00
print(datetime.today()) # 2020-05-10 21:21:51.161005
day = date(2020, 5, 10)
print(day) # 2020-05-10
print(day.weekday()) # 6 (воскресенье)
# переведем day в строку
day = day.strftime("%A %d %b, %Y") # Sunday 10 May, 2020
print(day) | false |
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.rjust(m))
print(f"{firstName.rjust(m)}\n{middleName.rjust(m)}\n{lastName.rjust(m)}") | true |
e2b2a0b23cc2271707705eb92870c6a1a5a34d9f | LarisaOvchinnikova/Python | /HW12 (datetime)/2 - Transorm datetime into a string.py | 584 | 4.3125 | 4 | from datetime import datetime
# strftime - переводим время из формата datetime в строку
today = datetime.today()
print(today)
year = today.strftime("%Y")
print(f"year: {year}")
month = today.strftime("%m")
print(f"month: {month}")
day = today.strftime("%d")
print(f"day: {day}")
time = today.strftime("%I:%M:%S") #12-hour clock
print(f"time in 12-hour clock: {time}")
time = today.strftime("%H:%M:%S") #12-hour clock
print(f"time in 24-hour clock: {time}")
date_and_time = today.strftime("%m/%d/%Y, %H:%M:%S")
print(f"date and time: {date_and_time}") | false |
97a0e169f4df4ea8a11dd6ff0db8d627d92ffcf4 | LarisaOvchinnikova/Python | /strings/string.py | 1,032 | 4.34375 | 4 | s = "Hi "
print(s * 3)
print('*' * 5)
num = 6
num = str(num)
print(num)
print("Mary\nhas\na\nlittle\nlamb ")
print("I\'m great")
print("I have a \"good\" weight")
print(len("hello"))
name = "Lara"
print(name[0])
print(name[len(name)-1])
print(name.index("a"))
indexOfR = name.index('r')
print(indexOfR)
# Python console: help(str) --- get help
print("age="+str(6+4))
name1 = "Bob"
print("His name is %s" %name1)
age = 34
print("His age is %d" %age)
print("%s is %d years old" %(name, age)) # old code
print(f"Hello {name}, you are {age} years old")
print(f"{name} "*5)
print(name[0:2])
print(name[:-1]) # from begin to (last-1)
first = "Alice Moon"
ind = first.index(' ')
print(first[0:ind])
print(first[ind+1:])
print(first[::-1]) # reverse string - from first to last with step - 1
print(first[::2]) # step 2
print(f"{first[0]}.{first[ind+1]}.")
print(f"{first[0:ind]}\n{first[ind+1:]}")
s = "book"
print(s.rjust(10))
print(s.ljust(10))
print(s.center(10,"-"))
s = 'hello'
for i, char in enumerate(s):
print(i, char)
| false |
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) == int, f'expected type of value should be int'
def test_2(self):
"""Variable is positive number"""
assert pos_num > 0, f'expected value should be positive'
def test_3(self):
"""Variable is in valid range"""
assert 10 <= pos_num <= 200, f'expected value should be in the range from 10 to 200'
#Completed solution
pos_num = 100 | true |
855ba74add997a86ac15e0e9627cc3b1fb1ff388 | LarisaOvchinnikova/Python | /1 - Python-2/19 - arguments/from lesson.py | 752 | 4.28125 | 4 | # def func(x=10, y=20): #дефолтные значения без пробелов
# return x + y
#
# print(func(8, 5)) # 13
# print(func(12)) # 32
# print(func()) # 30
# def func(x, y, z=1): # все дефолтные справа
# return (((x, y),) * z)
#
# print(func(1,2,3)) #((1, 2), (1, 2), (1, 2))
# print(func(1,2)) # ((1, 2),)
# def func(y, x=10, z=1): # все дефолтные справа
# return (((x, y),) * z)
# print(func(1,2,3)) #((2, 1), (2, 1), (2, 1))
# print(func(1,2)) # ((2, 1),)
# print(func(5, z=5)) # ((10, 5), (10, 5), (10, 5), (10, 5), (10, 5))
#
# print(sorted([1,4,2,6,4])) # reverse by default
# print(sorted([1,4,2,6,4], reverse=True))
def func(x, y):
print(x, y)
func(y=10, x=0) #0 10 | false |
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
# it has only digits
# Print word " has digits and lowercase letters"
# if it has digits and only lowercase letters
# Print word " has digits and uppercase letters"
# if it has digits and only uppercase letters
# Print word " has all kinds of stuff"
# if it has digits and both uppercase and lowercase letters
word = input("Enter word: ")
if word.isdigit():
print("Has digits")
elif word.isalpha():
if word.islower():
print("Has lowercase")
elif word.isupper():
print("Has uppercase")
else:
print("Has upper and lower")
elif word.isalnum():
if word.islower():
print("Has lowercase and digits")
elif word.isupper():
print("Has uppercase and digits")
else:
print("Has upper and lower and digits")
help() #вызов помощи | true |
6f276eac15ebf4813598a2fc867dbac8843b69d9 | LarisaOvchinnikova/Python | /Sets/sets from lesson.py | 2,564 | 4.5 | 4 | # set is unordered(unindexed), mutable collection of data items
# (items - inmutable - numbers, strings, tuples, boolean)
# set contains only unique values
x = {1, "hello", 3, 5, "world"}
print(len(x))
# to create new empty set, use set() function
x = set()
#length of the set
print(len(x)) # ---> 0
x = {1,1,1,1}
print(x) # ----> {1}
x = {'hi', 1, 3, (3,6), "hello"}
print(x)
print(len(x)) # -->5
# x = {[1,2,3]} ---> error, lists, dict can not be element of set
y = [10,20, 30, 40]
x = set(y)
print(y)
print(x)
y = [1, 1, 20, 3, 3, 4, 3] # содержит повторяющиеся элементы
x = set(y)
print(x) # ---> {1,20,3,4} - только уникальные элементы
# итерация по set
for i in x:
print(i)
# сколько различных элементов в массиве
arr = [2,5,2,2,4,5,4]
x = set(arr)
print(x) # --> {2,4,5}
print(len(x))
# adding elements
# set.add() to add one element to set
# set.update() to add multiple elements
x = {1,2,3,4}
x.add(5)
print(x) # -->{1,2,3,4,5}
x.add("hello")
print(x)
x.add(1)
print(x)
x.update("a", "b", "c")
print(x) # ---> {1, 2, 3, 4, 5, 'hello', 'b', 'a', 'c'}
# Deleting elements
# set.remove() -to remove specified element, error when item doesn't exist in set
# set.discard() - to remove specified element, no error if element doesn't exist
x.remove("hello")
print(x)
#x.remove('w') --> error
x.discard("w") # --> no error
print(x)
# Union (объединение множеств - сетов)
set_A = {1,2,3,4}
set_B = {"a", "b", "c"}
print(set_A | set_B)
x = set_A | set_B # ---> объединение выкинет дубликаты
print(x)
x = {1,2,3}
y = {1,2, 6}
z = x | y
print(z)
z = x.union(y)
w = y.union(x)
# Intersection (пресечение множеств)
a = {1,2,3,4}
b = {4,5,6,7}
z = a & b # -->{4}
print(z)
z = a.intersection(b)
w = b.intersection(a)
print(z, w)
# Difference -- setA - setB те элементы a, которые не входят в b
setA = {1,2,3,4}
setB = {2,4,6,8}
dif = setA - setB
print(dif) # ---> {1,3}
print(setA.difference(setB)) # --> {1,3}
print(setB.difference(setA)) # --> {6,8}
# Difference between two collections
a = ['a', 'b', 'z', 'd', 'e', 'd']
b = ['a', 'b', 'j', 'j']
setA = set(a)
setB = set(b)
print(setA - setB)
print(setB - setA)
# set from string
s = "hello"
set_s = set(s)
print(set_s) # {'o', 'e', 'l', 'h'}
print(sorted((set_s))) # ['e', 'h', 'l', 'o']
# sorted превратидл set в отсортированный массив | false |
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 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
'''
class Solution:
def reverse(self, x: int) -> int:
if str(x).startswith("-"):
x = str(x)
x = str(x[1:])
rev=x[::-1]
result="-"+rev
else:
result=int(str(x)[::-1])
range1= -2**31
range2= 2**31
if result in range(range1,range2):
return result
else:
return 0
| 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 |
03b78a88aad855b84b82a2fda9673e807012bc5d | ACNoonan/PythonMasterclass | /Sets/sets.py | 2,625 | 4.375 | 4 | # # # 2 Ways to Create Sets:
# #
# # farm_animals = {'sheep', 'cow', 'hen'}
# # print(farm_animals)
# #
# # for animal in farm_animals:
# # print(animal)
# #
# # print('-' * 40)
# #
# # wild_animals = set(['lion', 'tiger', 'panther',
# # 'elephant', 'hare'])
# # print(wild_animals)
# #
# # for animal in wild_animals:
# # print(animal)
#
# # How to Create an Empty Set:
# empty_set = set()
# empty_set.add('a')
#
# # Doesn't work, adds dict
# #empty_set2 = {}
# #empty_set2.add('a')
#
# even = set(range(0, 40, 2))
# print(even)
# squares_tuple = (4, 9, 16, 25)
# squares = set(squares_tuple)
# print(squares)
# even = set(range(0, 40, 2))
# print(even)
# print(len(even))
#
# squares_tuple = (4, 9, 16, 25)
# squares = set(squares_tuple)
# print(squares)
# print(squares_tuple)
#
# print(even.union(squares))
# print(len(even.union(squares)))
#
# print('-' * 40)
# Playing with intersection() and &'s
# print(even.intersection(squares))
# print(even & squares)
# print(squares.intersection(even))
# print(squares & even)
# Creating a set from a range & a tuple
# even = set(range(0, 40, 2))
# print(sorted(even))
# squares_tuple = (4, 9, 16, 25)
# squares = set(squares_tuple)
# print(sorted(squares))
#
# .difference() = minus for sets
# print('even minus squares:')
# print(sorted(even.difference(squares)))
# print(sorted(even - squares))
# print('squares minus even')
# print(sorted(squares.difference(even)))
# print(sorted(squares - even))
#
# print('-' * 40)
# print(sorted(even))
# print(squares)
# even.difference_update(squares)
# print(sorted(even))
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuple = (4, 9, 16, 25)
squares = set(squares_tuple)
print(sorted(squares))
# Symmetric difference is the opposite of intercept
# print('symmetric minus squares')
# print(sorted(even.symmetric_difference(squares)))
#
# print('symmetric squares minus even')
# print(squares.symmetric_difference((even)))
# .discard = .remove
# squares.discard(4)
# squares.remove(16)
# squares.discard(8) # Doesn't throw an error even though there is no 8 in squares
# print(squares)
# # The following will throw an error:
# try:
# squares.remove(8)
# except KeyError:
# # print('The item 8 is not a member of this set')
even = set(range(0, 40, 2))
print(even)
squares_tuple = (4, 6, 16)
squares = set(squares_tuple)
print(squares)
if squares.issubset(even):
print('squares is subset of even')
if even.issuperset(squares):
print('even is a superset of squares')
# Frozen sets are immutabele tooo
print('-' * 40)
even = frozenset(range(0, 100, 2))
print(even)
even.add(3) | false |
e548491168889093d7cfee3532810a4af1a92051 | ACNoonan/PythonMasterclass | /Lists/tuples.py | 1,032 | 4.40625 | 4 | # # Tuples are IMMUTABLE
# # Declaring a tuple w/o parenthesis
# t = "a", "b", "c"
# print(t)
#
#
# print("a", "b", "c")
# # Declaring a tuple w/ parenthesis
# print(("a", "b", "c"))
# Tuples w/o parenthesis w/ multiple data types
welcome = 'Welcome to my Nightmare', 'Alice Cooper', 1975
bad = 'Bad Company', 'Bad Company', 1974
budgie = 'Nightglight', 'Budgie', 1981
imelda = 'More Mayhem', 'Emilda May', 2011
metallica = 'Ride the Lightning', 'Metallica', 1984
# print(metallica)
# Indexing tuples
# print(metallica[0])
# print(metallica[1])
# print(metallica[2])
# "Fixing" tuple by re-assigning & indexing
# imelda = imelda[0], 'Imelda May', imelda[2]
# print('tuple = ()')
# print(imelda)
# # Changing a list, which you cannot do with a Tuple
# print('lists = [] ')
# metallica2 = ['Ride the Lightning', 'Metallica', 1984]
# print(metallica2)
# metallica2[0] = 'Master of Puppets'
# print(metallica2)
# Extracting content out of tuple, assigning to a variable
# title, artist, year = imelda
# print(title)
# print(artist)
# print(year)
| false |
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():
label.configure(text="button is clicked !!")
bton = tkinter.Button(window, text = "Click me",bg="orange",fg="red",command=clicked)
bton.grid(column=1, row=0)
#label.grid(column=0, row=0)
#this function calls the endless loop of the window,
#so the window will wait for any user interaction till we close it.
window.mainloop() | 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 than 2, There is no Prime number before", a)
continue
except ValueError:
print("Input should be a Positive Integer Value")
check_a = 0
for x in range((a-1),1,-1):
for num in range(2,x):
if(x%num == 0):
break
else:
print("The prime number that comes first when we count backwards from" ,a, "is:",x)
break
prim(check_a,a)
'''
TEST CASE:
Sample Input : 3 || Expected Output: The prime number that comes first when we count backwards from 3 is:2
Sample Input : 15 || Expected Output: The prime number that comes first when we count backwards from 56 is:13
Sample Input : 2100 || Expected Output: The prime number that comes first when we count backwards from 2100 is:2111
Sample Input : 10000 || Expected Output: The prime number that comes first when we count backwards from 10000 is: 9973
-------------------------------------------
Input | Output
-------------------------------------------
56 | The prime number that comes first when we count backwards from 56 is: 53
-------------------------------------------
asd | Enter a positive integer value
-------------------------------------------
@#$ | Enter a positive integer value
-------------------------------------------
2.5 | Enter a positive integer value
-------------------------------------------
-2 | Please enter a value greater than 2, There is no Prime number before -2.
-------------------------------------------
0 | Please enter a value greater than 2, There is no Prime number before 0.
-------------------------------------------
'''
| true |
137820c8f3df39e0456ad149c8003925985bd0fb | infantcyril/Python_Practise | /Prime_Number.py | 1,151 | 4.15625 | 4 | check_a = 0
a = 0
def prime(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 <= 1):
check_a = 0
print("Please enter a value greater than 1, There is no Prime number before", a)
continue
except ValueError:
print("Input should be a Positive Integer Value")
check_a = 0
for i in range(2,a):
if(a % i) == 0:
print(a,"is not a Prime number")
break
else:
print (a,"is a Prime number")
prime(check_a,a)
'''
TEST CASE:
Sample Input : 3 || Expected Output: 2
Sample Input : 7 || Expected Output: 5
Sample Input : 15 || Expected Output: 13
Sample Input : 1000 || Expected Output: 997
Sample Input : 2100 || Expected Output: 2111
Sample Input : 10000 || Expected Output: 9973
Sample input: kj<space>sh || Expected Output : Input should be a positive value
Sample Input : 1<sapce>5 || Expected Output: Input should be a positive valu
'''
| false |
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 perfect length!"
if name == "Jesse":
print "Hey, Jesse!"
else:
print "You have a long name!"
| 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
numerical_value = ord(i) #unicode value of the char
if i.isupper(): #if is uppercase
adjusted = ((numerical_value + offset - 65) % 26) + 65 #uppercase A = 65 (ASCII). The %26 wraps around, so Y = A and Z = B
cipher_text += chr(adjusted) #get the correspondent char
elif numerical_value == 32: #32 = space, this intends to preserve the spaces between words
cipher_text += i
else: #if is lowercase
adjusted=((numerical_value + offset - 97) % 26) + 97 #lowercase a = 97 (ASCII)
cipher_text += chr(adjusted)
return cipher_text
print(encrypt("hello lads", 2))
print(encrypt("are we human", 2))
| 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: #the index cannot be even
e = array[n] #element with index n
oddl.append(e) #add the element in the list oddl
n += 1 #increase index by 1
elif n % 2 == 0 or n == 0: #if the index is zero or even 'skip'
continue
return oddl #return the list with elements that were in odd position
array = [25, 6, 99, 74, 20, 101]
print(range_list(array))
print(odd_index(array))
# Option 2 after watching the pseudoce video
def odd_GMIT(array):
oddG = []
while i <= len(array):
for i == 1:
oddG.append(i)
i +=2
return oddG
# Option 3 by Dominic Carr (Lecturer - Algorithmics Module)
def odd_indices(input):
output = []
for i in range(len(input)):
if (i % 2) != 0:
output.append(input[i])
return output
print(odd_indices([1, 2, 3, 4, 5]))
| 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
else:
return str1[0] + str2[0] + merge(str1[1:],str2[1:]) #first element of str1 + first element of str2 + function calling itself to continue the pattern of element str1 + str2 to result in a merged list
print(merge('dmnc', 'oii'))
| true |
4657fb179ddf454b1e09b4e501028a70fdcc3062 | rnem777/python-project | /class_try.py | 743 | 4.25 | 4 | #it is to modify between the subject and the behaviour
# the name has always to stat with cabital litter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def walk(self):#self here will give us access to name
print(self.name + ' is a student at sunderland university')
# classes nd behavior and objects
def speak(self):
print('Hello my name is ' + self.name + ' and I am ' + str(self.age) + ' years old')
ibrahim = Person('Ibrahim', 30)
sahem = Person('Sahem', 15)
print(ibrahim.name + ' ' + str(ibrahim.age))
ibrahim.speak()
ibrahim.walk()
print('---------------------')
print(sahem.name + ' ' + str(sahem.age))
sahem.speak()
sahem.walk() | false |
360bb0aae3cf4d6aa936a500cdb2e0c716dbbaac | Morgan1you1da1best/unit2 | /unitConverter.py | 439 | 4.21875 | 4 | #Morgan Baughman
#9/15/17
#unitConverter.py - COnverting Units of stuff
a = ('1) Kilotmeters to Miles')
b = ('2) Kilograms to Pounds')
c = ('3) Liters to Gallons.')
d = ('4) Celsius to Fahrenheit')
print('choose a convertion.')
print('a) Kilotmeters to Miles')
print('b) Kilograms to Pounds')
print('c) Liters to Gallons.')
print('d) Celsius to Fahrenheit')
convertionopt = (input('choose a convertion: '))
convertion = float(input('Enter' , a)
| false |
9a892afe4a0528cbd26ebba1d5861b54e358cecd | Morgan1you1da1best/unit2 | /warmUp3.py | 336 | 4.34375 | 4 | #Morgan Baughman
#9/15/17
#warmUp3.py - practicing if statements
num = int(input('Enter a number: '))
if num% 2 == 0 and num% 3 == 0:
print(num, 'is divisible by both 2 and 3')
elif num% 2 == 0:
print(num, 'is divisible by 2')
elif num% 3 == 0:
print(num, 'is divisible by 3')
else:
print(num , 'is divisble by neither 2 or 3')
| false |
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": 1, "b": 2, "c": 3}
#
# Expected output:
#
# 6
#
# ---------------------------------------------------------------------------------------------------------------------
d = {"a": 1, "b": 2, "c": 3}
sum_x=0
for key in d.keys():
sum_x = sum_x + d[key]
print(sum_x)
# I got loops on the brain this morning... Instructors solution is way more Pythonic.
# print([sum(x)for x in d.keys])
# Instructor's Solution
#
# Exercise for reference:
#
# Calculate the sum of all dictionary values.
#
# d = {"a": 1, "b": 2, "c": 3}
#
# Answer:
#
# d = {"a": 1, "b": 2, "c": 3}
# print(sum(d.values()))
#
# Explanation:
#
# d.values() returns a list-like dict_values object while the sum function calculates the sum of the dict_values items.
| 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. create another dict, to store the data like
{2[[/]]}
"""
def reads_file():
def save_words_2_list():
"""
will return list of words
"""
for lines in f:
def list_to_dict(words):
"""
words: a list of all the words
reuturns a dictionary
"""
def print_anagrams(word_dict, n_words_in_anagrams = 1):
"""
prints all the anagrams with more than n words
"""
def create_another_dict():
def prints_anagram_by_number(words_dict):
"""
create
def main():
words_list = reads_file
word_dict = list_to_dict(word_list)
#ex- 2
print_anagrams(word_dict, 2)
if __name == '__main__":
main() | 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 for
\tparam : list - the list you're searching through
\treturns : the index of where the element was found (if applicable)
"""
for index in range(0,len(list)):
if list[index] == x:
return index
def find_max(list):
"""
this function returns the maximum element in the list
\tparam : list - a list of numerical elements
\treturns : the maximum value in the list
"""
max = list[0]
for element in list:
if element >= max:
max = element
return max
def find_min(list):
"""
this function returns the minimum element in the list
\tparam : list - a list of numerical elements
\treturns : the minimum value in the list
"""
min = list[0]
for element in list:
if element <= min:
min = element
return min
| 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 |
6626cc27b8cd0fb44aa658cf215aa65a33c003ad | rivet9658/Rivet9658-Python-University-Works | /Python Final Test/python final test 第三題.py | 226 | 4.125 | 4 | #python final test 第三題
print("輸入字串:")
str=input()
print("輸入要取代的字串:")
ch=input()
print("輸入取代的字串:")
bh=input()
if ch in str:
print(str.replace(ch,bh))
else:
print("not found")
| false |
d8ca838e737250e107433c0cd070aafcbdd74c56 | Muratozturknl/8.hafta_odevler-Fonksiyonlar | /week8_11_func_ozgunelaman.py | 424 | 4.125 | 4 | # Verilen bir listenin içindeki özgün elemanları ayırıp
# yeni bir liste olarak veren bir fonksiyon yazınız.
# Örnek Liste : [1,2,3,3,3,3,4,5,5]
# Özgün Liste : [1, 2, 3, 4, 5]
def ozgunlist(a):
list = []
for i in a:
if i not in list:
list.append(i)
return list
a = [1,2,2,4,1,4,1029,5,40,41,31,5,7,6,6,9,45,88]
print('Example list', a)
print("Unique list",sorted(ozgunlist(a))) | false |
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 enter a symbol: ")
res = s.replace(s[0], symbol)
print(res)
| 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 demonstrate
changing the objects attributes.
'''
class Car():
def __init__(self, model, year, max_speed):
self.model = model
self.year = year
self.max_speed = max_speed
def __str__(self):
return f"This is a {self.year} {self.model} car that has a maximum speed of {self.max_speed}"
def increase_speed(self):
self.max_speed += 5
car1 = Car("BMW", 2021, 50)
car2 = Car("TSL", 2020, 60)
print(car1)
print(car2)
car1.increase_speed()
car2.increase_speed()
print(car1)
print(car2) | 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/proofs_with_empty_clause_for_'+\
str(num_of_propositions)+'_propositions.csv'
else:
fname = 'data/proofs_without_empty_clause_for_'+\
str(num_of_propositions)+'_propositions.csv'
fname = 'test.dat'
with open(fname) as csvfile:
csvin = csv.reader(csvfile)
for row in csvin:
#print(', '.join(row))
print(row)
"""
rows = list()
y = 0
for x in itertools.product(range(0,2), repeat=num_of_clauses):
#print(y, x)
one_row = list(x);
one_row.insert(0, y);
rows.append(one_row);
y+=1
#print(rows)
with open(fname, 'wt') as fout:
csvout = csv.writer(fout)
csvout.writerows(rows)
"""
#main
proving(2, False);
#proving(2, True);
| 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 string
reversed=''.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new string
print(reversed) #print the reversed string'''
# Python code to reverse a string
# using loop
'''def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Python"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(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_message' func by printing messages."""
def wrap(*args, **kwargs):
""" Here we can print *aregs and **kwargs and manipulate them """
print('>> Decorate before executing "greeting_message" function')
func = f(*args, **kwargs)
print('>> Decorate after executing "greeting_message" function')
return func
return wrap
@greeting_message_decorator
def greeting_message(name):
""" This function will be decorated by 'greeting_message_decorator' before execution """
print('My name is ' + name)
greeting_message('Adam') | 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 being to think about data structures and come
up with a challenge to keep you busy. Your mission: create a queue data
structure. Remember, queues are FIFO - first in first out - in nature.
Your queue should be a class that has the methods "add" and "remove".
Adding to the queue should store an element until it is removed.
"""
class queue():
def __init__(self):
self.items = []
def add(self, item):
self.items.insert(0,item)
def remove(self):
return self.items.pop()
def size(self):
return len(self.items)
newQueue = queue()
newQueue.add(35)
newQueue.add(10)
print(newQueue.size())
newQueue.remove()
print(newQueue.size())
| 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 could stand in front of the mirror to see the messages.
However, you have not slept for 3 days in a row...and haven't showered either.
Because you really don't want to see your face, you decide that you would
rather build an app that can take in a message string and return
the reversed message for you. Now you just need to come up with a
function to build your app - and don't take the shortcut using the "reverse"
method ;)Please reverse this message found in the spooky journal:
.uoy fo lla naht ynapmoc retteb a ekam nac I
.ynapmoc siht ta OEC eht eb ot evresed I
loopsstringsmedium
"""
def reverseMessage(message):
return(message[::-1])
print(reverseMessage(".uoy fo lla naht ynapmoc retteb a ekam nac I .ynapmoc siht ta OEC eht eb ot evresed I"))
| true |
26ccdbc2bae76c99ce4409f4dbaef17419d78086 | sam676/PythonPracticeProblems | /Robin/palindromeNumber.py | 1,709 | 4.3125 | 4 | """
Sheltered at home, you are so bored out of your mind that you start thinking
about palindromes. A palindrome, in our case, is a number that reads the
same in reverse as it reads normally. Robin challenges you to write a
function that returns the closest palindrome to any number of your choice.
If your number is exactly in between two palindromes, return the smaller
number. If the number you chose IS a palindrome, return itself. Have fun!
"""
def palindromeNum(number):
number = str(number)
reverse = number
reverse = reverse[::-1]
#if the given number is the same going forwards as is backwards
#return the number
if str(number) == reverse:
return(number)
else:
#otherwise divide the number in half
half = len(number) // 2
#convert the number from an int to a string
number = str(number)
#if the length of the number is odd, add one to the legth
if (len(number) % 2):
half += 1
#store the firt half of the number
start = number[:half]
#store the seconf half of the number minus the middle number
end = start[0:half-1]
#reverse the second half of the number
end = end[::-1]
#combine both parts of the number to make a palindrome
newNumber = start + end
else:
#if the number is even, divide it in half
newNumber = number[:half]
#reverse the beginning and combine both parts of the number to
#make a palindrome
newNumber += newNumber[::-1]
return(newNumber)
#drivers
print(palindromeNum(123456))
print(palindromeNum(1234567))
| true |
095000b97fa3e4993fef3682cb33e688586eb4ae | sam676/PythonPracticeProblems | /Robin/isMagic.py | 1,199 | 4.53125 | 5 | """
You've heard about Magic Squares, right?
A magic square is one big square split into separate squares
(usually it is nine separate squares, but can be more), each containing a unique number.
Each horizontal, vertical, and diagonal row MUST add up to the same number
in order for it to be considered a magic square.
Now, it's up to you to write a function that accepts a two-dimensional
array and checks if it is a magic square or not.
Examples:
isMagic([
[6, 1, 8],
[7, 5, 3],
[2, 9, 4]
]) ➞ true
isMagic([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]) ➞ false
"""
def isMagic(array):
magic = True
sumEach = []
rowNumber = 0
colNumber = 0
for row in range (len(array)):
for column in range (len(array)):
rowNumber += array[row][column]
colNumber += array[column][row]
sumEach.append(rowNumber)
sumEach.append(colNumber)
rowNumber = 0
colNumber = 0
for x in range(1, len(sumEach)):
if sumEach[x] != sumEach[x-1] :
magic = False
return magic
#driver
print(isMagic([
[6, 1, 8],
[7, 5, 3],
[2, 9, 4]
]))
print(isMagic([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])) | true |
57a76e4402bad59476588863a63a67e89e5d5bd0 | sam676/PythonPracticeProblems | /Robin/numScanner.py | 1,174 | 4.25 | 4 | """
How are our lovely number people doing today?
We're going to have an exclusive numbers-only party next week.
You can bring any type of friends that wear "String" clothes as long as they are real number.
As we expect the infinite number of numbers to come to the party,
we should rather build a scanner that will scan every guest and validate whether
they are a real numbers. If any number brings a fake guest, it will be kicked out of our world!
Can your team build a special function that will be used in the scanner?
Please remember, all guests will be wearing string clothes.
For example,
numScanner("2.2") ➞ true
numScanner("1208") ➞ true
numScanner("number") ➞ false
numScanner("0x71e") ➞ false
numScanner("2.5.9") ➞ false
"""
def numScanner(input):
count = 0
if input.isdigit():
return True
for x in input:
if x.isalpha():
return False
if x == '.':
count += 1
if count > 1:
return False
return True
#driver
print(numScanner("2.2"))
print(numScanner("1208"))
print(numScanner("number"))
print(numScanner("0x71e"))
print(numScanner("2.5.9"))
| true |
a4b9901488a005c10a02c477fa009b2131fa8906 | sam676/PythonPracticeProblems | /Robin/addPositiveDigit.py | 501 | 4.125 | 4 | """
Beginner programmer John Doe wants to make a program that adds and outputs each positive digit
entered by the user (range is int). For instance, the result of 5528 is 20 and the result of 6714283 is 31.
"""
def addPositiveDigit(n):
total = 0
if n >= 0:
for x in str(n):
total += int(x)
else:
return "Please enter a positive number!"
return total
#driver
print(addPositiveDigit(5528))
print(addPositiveDigit(6714283))
print(addPositiveDigit(-6714283))
| true |
245316d9ddeaa983b1e6047eb83085bd33d3c6ae | gas8310/python_git | /sequence_data.py | 481 | 4.1875 | 4 | #시퀀스 자료형
#문자열, 리스트, 튜플 등 인덱스를 가지는 자료형
#기본적 사용법?
#1.
string = "hello - world"
list = ['h', 'e', 'l', 'l', 'o', '-', 'w', 'o', 'r', 'l', 'd']
tuple = ('h', 'e', 'l', 'l', 'o', '-', 'w', 'o', 'r', 'l', 'd')
print(string[0:5])
print(list[0:5])
print(tuple[0:5])
for i in string:
# print(string[i])
print(i)
print(len(string))
#조건문의 사용.
if 'h' in string:
print("h가 포함되어있습니다.")
| false |
e241aa2106c8e48c37c3531b6d7fa8bdbbf216e7 | amirrulloh/python-oop | /leetcode/2. rverse_integer.py | 863 | 4.1875 | 4 | #Definition
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which 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.
"""
class Solution:
def reverse(self, x):
negFlag = 1
if x < 0:
negFlag = -1
strx = str(x)[1:]
else:
strx = str(x)
x = int(strx[::-1])
return 0 if x > pow(2, 31) else x * negFlag
test = Solution()
print(test.reverse(123))
print(test.reverse(-123))
print(test.reverse(120)) | true |
ac5807601d45d4f350e0b0efb8cd2c7395d5eb3d | DDan7/CoffeeMachine | /Problems/Palindrome/task.py | 396 | 4.125 | 4 | user_input = input()
def palindrome(a):
backward = a[::-1]
if backward == a:
print("Palindrome")
else:
print("Not palindrome")
palindrome(user_input)
# def palindrome(a):
# backward = ''
# for i in a:
# backward += i
# if backward == a:
# print("Palindrome")
# else:
# print("Not palindrome")
#
#
# palindrome(user_input)
| false |
c097cfa78f6c8bc2a62eb04cd86023c51f221b5d | miller9/python_exercises | /17.py | 1,337 | 4.625 | 5 | print ('''
17. Write a version of a palindrome recognizer that also accepts phrase palindromes
such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?",
"Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil",
"Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori",
"Rise to vote sir", or the exclamation "Dammit, I'm mad!".
Note that punctuation, capitalization, and spacing are usually ignored.
Palindrome examples:
"Go hang a salami I'm a lasagna hog.",
"Was it a rat I saw?",
"Step on no pets",
"Sit on a potato pan, Otis",
"Lisa Bonet ate no basil",
"Satan, oscillate my metallic sonatas",
"I roamed under it as a tired nude Maori",
"Rise to vote sir",
"Dammit, I'm mad!".
''')
def palindrome_recognizer():
print ('---')
str1 = str( input('Please enter the phrase to verify if its palindrome or not: ') )
phrase = str1.lower()
phrase = phrase.strip('¿?.,\'¡!')
print (phrase)
print ()
str2 = ""
subs = -1
i = 0
for index, character in enumerate(phrase):
str2 += phrase[len(phrase) + subs]
subs -= 1
if str2[index] == phrase[len(phrase) + subs]:
print (True, '--> The phrase is palindrome!')
else:
print (False, '--> The phrase is not a palindrome!')
print ('---')
print ()
palindrome_recognizer()
| true |
571f2c597feb3192b9d5f7cf72e6403ef8b332c9 | miller9/python_exercises | /12.py | 384 | 4.21875 | 4 | print ('''
12. Define a procedure histogram() that takes a list of integers and prints a histogram to the screen.
For example, histogram( [ 4, 9, 7 ] ) should print the following:
****
*********
*******
''')
def histogram(l):
for value in l:
print ("*" * value)
int_list = [4, 9, 7]
print ('The histogram of the list:', int_list, 'is:')
histogram(int_list)
print ()
| true |
111e530378568654c44b14627fe5f11fe8493a43 | miller9/python_exercises | /10.py | 1,024 | 4.34375 | 4 | print ('''
10. Define a function overlapping() that takes two lists and
returns True if they have at least one member in common, False otherwise.
You may use your 'is_member()' function, or the 'in' operator,
but for the sake of the exercise, you should (also) write it using two nested for-loops.
''')
def overlapping(a_list, b_list):
print ('The first list is: ', a_list)
print ('The second list is: ', b_list)
i = 0
x1 = []
x2 = []
if (len(a_list) > len(b_list)):
x1 = a_list
x2 = b_list
else:
x1 = b_list
x2 = a_list
while i < len(x1):
for num in x1:
# Using the 'in' operator to verify if the member belongs to the other list
# if num in x2:
if (num == x2[i]):
print ('\nThere is at least 1 member repeated -->', num)
return True
i += 1
return False
list_1 = ['python', 963, 'abc', 321, 954810, 3]
list_2 = [12, 'py', 'bwqeqweqwc', 9, 1, 2, 4, 5, 6, 7, 8, 963]
ans = overlapping(list_1, list_2)
print ('Have both lists at least 1 member in common?', ans)
print () | true |
aff950e6eb663d1dc7defdf7a8e1b19c480da3fd | yogeshwaran01/Python-Scripts | /Scripts/anagram.py | 540 | 4.1875 | 4 | """
What is an anagram?
Two words are anagrams of each other
if they both contain the same letters.
For example:
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
"""
def is_anagram(a: str, b: str) -> bool:
"""
>>> is_anagram("xyxyc", "xyc")
False
>>> is_anagram("abba", "ab")
False
>>> is_anagram("abba", "bbaa")
True
"""
return bool(len(a) == len(b) and set(a) == set(b))
if __name__ == "__main__":
import doctest
doctest.testmod()
| false |
e14c143ea086ca19b10c2f4f9cb59e0d4d55f651 | benjaminhuanghuang/ben-leetcode | /0306_Additive_Number/solution.py | 2,106 | 4.21875 | 4 | '''
306. Additive Number
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers,
each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
'''
class Solution(object):
def isAdditiveNumber(self, nums):
"""
:type num: str
:rtype: bool
"""
if not nums or len(nums) < 3:
return False
n = len(nums)
for i in xrange(1, n):
for j in xrange(i + 1, n):
if self.dfs(0, i, j, n, nums):
return True
return False
def dfs(self, start, first, second, n, num):
first_num, second_num = num[start:first], num[first:second]
if (len(first_num) > 1 and first_num[0] == '0') or (len(second_num) > 1 and second_num[0] == '0'):
return False
temp_sum = int(first_num) + int(second_num)
if temp_sum == int(num[second:]) and num[second] != '0':
return True
max_len = max(first - start, second - first)
if second + max_len <= n:
status = False
if temp_sum == int(num[second:second + max_len]):
status = self.dfs(first, second, second + max_len, n, num)
if not status and second + max_len + 1 <= n and temp_sum == int(num[second:second + max_len + 1]):
status = self.dfs(first, second, second + max_len + 1, n, num)
return status
return False
| true |
a4ff52bf767bec2d17ad4e192855aa4380807c6b | benjaminhuanghuang/ben-leetcode | /0398_Random_Pick_Index/solution.py | 1,366 | 4.125 | 4 | '''
398. Random Pick Index
Given an array of integers with possible duplicates, randomly output the index of a given target number.
You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
'''
import random
# passed at first try!
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
self.dict = {}
for i in xrange(len(nums)):
if nums[i] in self.dict:
self.dict[nums[i]].append(i)
else:
self.dict[nums[i]] = [i]
def pick(self, target):
"""
:type target: int
:rtype: int
"""
# You can assume that the given target number must exist in the array.
indexes = self.dict[target]
return indexes[random.randint(0, len(indexes) - 1)]
s = Solution([1, 2, 3, 3, 3])
print s.pick(3)
print s.pick(1)
| true |
fc6127107d0807ee269b4505543ee30741c4695a | benjaminhuanghuang/ben-leetcode | /0189_Rotate_Array/solution.py | 1,649 | 4.1875 | 4 | '''
189. Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
'''
class Solution(object):
def rotate_lazy(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
# !! Do not use nums = nums[n - k:] + nums[:n - k]
nums[:] = nums[n - k:] + nums[:n - k]
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
# time O(n) space O(1)
def rotate(self, nums, k):
if not nums:
return
if k <= 0:
return
n = len(nums)
k %= n
# reverse first part
self.reverse(nums, 0, n - k - 1)
# reverse second part
self.reverse(nums, n - k, n - 1)
# reverse whole list
self.reverse(nums, 0, n - 1)
# time O(kn) space O(1)
def rotate_3(self, nums, k):
if not nums:
return
if k <= 0:
return
n = len(nums)
k %= n
t = 0
while t < k:
last = nums[-1]
for i in xrange(n - 1, 0, -1):
nums[i] = nums[i - 1]
nums[0] = last
t += 1
s = Solution()
nums = [1, 2, 3, 4, 5, 6, 7]
s.rotate_3(nums, 3)
print nums
| true |
45929efac6474bb344733cd8130f9c2ea68f7bcd | benjaminhuanghuang/ben-leetcode | /0414_Third_Maximum_Number/solution.py | 2,003 | 4.1875 | 4 | '''
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist,
return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
'''
MIN_INT = -2 ** 31
class Solution(object):
def thirdMax_my(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_1 = MIN_INT - 1 # for case [1,2,MIN_INT]
max_2 = MIN_INT - 1
max_3 = MIN_INT - 1
for n in nums:
if n >= max_1:
if n > max_1:
max_3 = max_2 # Note the order!!!
max_2 = max_1
max_1 = n
elif n >= max_2:
if n > max_2:
max_3 = max_2
max_2 = n
elif n >= max_3:
max_3 = n
if max_3 == MIN_INT - 1:
return max_1
return max_3
def thirdMax_better(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_1 = MIN_INT - 1 # for case [1,2,MIN_INT]
max_2 = MIN_INT - 1
max_3 = MIN_INT - 1
for n in nums:
if n > max_1:
max_3 = max_2 # Note the order!!!
max_2 = max_1
max_1 = n
elif max_1> n and n > max_2:
max_3 = max_2
max_2 = n
elif max_2 > n and n > max_3:
max_3 = n
if max_3 == MIN_INT - 1:
return max_1
return max_3
s = Solution()
n = s.thirdMax([2, 2, 3, 1])
print n
| true |
e6cdd47a3fe566991b401e000debe99d16451178 | benjaminhuanghuang/ben-leetcode | /0031_Next_Permutation/solution.py | 1,715 | 4.125 | 4 | '''
31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 -> 1,3,2
3,2,1 -> 1,2,3
1,1,5 -> 1,5,1
'''
class Solution(object):
# https://www.hrwhisper.me/leetcode-permutations/
#
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j, k = len(nums) - 2, len(nums) - 1
# from right to left, find out the "first" number it is less than the adjacent number at right side
while j >= 0:
if nums[j] < nums[j + 1]:
break
j -= 1
# if all number arranges descending, sort (ascending order) and return
if j < 0:
nums.sort()
return
# The right section of the numbers are in descending order
# find smallest number (bigger than nums[j])in the right section of the numbers
while k > j:
if nums[k] > nums[j]:
break
k -= 1
nums[j], nums[k] = nums[k], nums[j]
# reverse the right section
nums[:] = nums[:j + 1] + nums[:j:-1]
s = Solution()
input = [1, 3, 0, 6, 5]
s.nextPermutation(input)
print input
input = [1, 2, 3, 4]
s.nextPermutation(input)
print input
input = [3, 2, 1]
s.nextPermutation(input)
print input
| true |
b8f6e39447a33973e6a3d806cc407b73b372f7be | walokra/theeuler | /python/euler-1_fizzbuzz.py | 413 | 4.125 | 4 | # Problem 1
# 05 October 2001
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# Answer: 233168
#
#!/usr/bin/python
sum = 0
max = 1000
for i in range(1,max):
if i%3 == 0 or i%5 == 0:
sum = sum + i
print 'sum of 3/5 modulos < ' + str(max) + ': ' + str(sum)
| true |
8eeb3b9fb2593f8a3c84b80cb7bd220d2b221ccb | dipnrip/Python | /Python/Labs/lab2.py | 294 | 4.15625 | 4 | weight = int(input("Enter weight: "),10)
height = int(input("Enter height: "),10)
bmi = (weight/(height**2))*703
if(bmi < 18.5):
print("underweight")
if(bmi > 18.5 and bmi < 24.9):
print("normal")
if(bmi < 29.5 and bmi > 25.0):
print("overweight")
if(bmi >= 30):
print("obese")
| false |
d8b1d9e71ccb9fd29781aa4eb62ae3b175921fb0 | yansolov/gb | /gb-python/lesson03/ex06.py | 967 | 4.1875 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и
# возвращающую его же, но с прописной первой буквой.
# Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка
# из слов, разделенных пробелом. Каждое слово состоит из латинских
# букв в нижнем регистре. Сделать вывод исходной строки, но каждое
# слово должно начинаться с заглавной буквы. Необходимо использовать
# написанную ранее функцию int_func().
def int_func(a):
return a.title()
print(int_func("small"))
print(int_func("small latin letters"))
| false |
364b39ae12c52f969ec99a0d0111042efbca5cf5 | yansolov/gb | /gb-python/lesson04/ex06.py | 917 | 4.125 | 4 | # Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
from itertools import count, cycle
def count_func(start, stop):
for el in count(start):
if el > stop:
break
else:
print(el)
def repeat_func(my_list, iteration):
i = 0
num = cycle(my_list)
while i < iteration:
print(next(num))
i += 1
count_func(start=int(input("Введи стартовое число: ")), stop=int(input("Введи последнее число: ")))
repeat_func(my_list=[10, -20, None, 'text'], iteration=int(input("Введи количество итераций: ")))
| false |
503423d6683506ce9ff4fde7f73cfbd7b1cb5145 | tolaoner/Python_Exercises | /different_numbers.py | 613 | 4.125 | 4 | '''Create a sequence of numbers and determine whether
all the numbers of it are different from each other'''
import random
list_numbers=[]
different=True
for i in range(5):
list_numbers.append(random.randrange(1,10,1))
print(list_numbers[i])
for i in range(5):
for j in range(5):
if i==j:
continue
if list_numbers[i]==list_numbers[j]:
different=False
print('All numbers are different!'if different else 'There are same numbers!')
'''Correct solution.
Better Solution:
with set() method! set() sorts the iterables and removes repeating
elements! In dictionary, only keys remain after conversion!''' | true |
399474bdd93e47d000ed9ae9734dd2e5b85fe660 | Siddhant6078/Placement-Programs | /Python/factors_of_a_num.py | 214 | 4.25 | 4 | # Python Program to find the factors of a number
def print_factors(n):
print 'Factors of {0} are:'.format(n)
for x in xrange(1,n+1):
if n % x == 0:
print x
n1 = int(input('Enter a n1: '))
print_factors(n1) | true |
92f4bea4efbe1c7549407a44b85bf03ceeb25104 | Siddhant6078/Placement-Programs | /Python/swap two variables.py | 663 | 4.34375 | 4 | # Python program to swap two variables using 3rd variable
x = input('Enter value of x: ')
y = input('Enter value of y: ')
print 'The value of x: Before:{0}'.format(x)
print 'The value of y: Before:{0}'.format(y)
temp = x
x = y
y = temp
print 'The value of x: After:{0}'.format(x)
print 'The value of y: After:{0}'.format(y)
# Python program to swap two variables without using 3rd variable
a = input('Enter value of a: ')
b = input('Enter value of b: ')
print 'The value of a: Before:{0}'.format(a)
print 'The value of b: Before:{0}'.format(b)
a = a+b
b = a-b
a = a-b
print 'The value of a: After:{0}'.format(a)
print 'The value of b: After:{0}'.format(b) | true |
e3f91759b3e4661e53e1c5bb42f6525cef89b2d5 | Siddhant6078/Placement-Programs | /Python/Positive or Negative.py | 319 | 4.5 | 4 | # Program to Check if a Number is Positive, Negative or 0
# Using if...elif...else
num = float(input('Enter a Number: '))
if num > 0:
print 'Positive'
elif num == 0:
print 'Zero'
else:
print 'Negative'
# Using Nested if
if num >= 0:
if num == 0:
print 'Zero'
else:
print 'Positive'
else:
print 'Negative' | true |
73fed6743975942f340fc78009c16b9e2cf7b875 | abhinavkuumar/codingprogress | /employeeDict.py | 1,049 | 4.1875 | 4 | sampleDict = {
'emp1': {'name': 'John', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Tim', 'salary': 6500}
}
while 1:
answer = input("Do you want to add or remove an employee? Select q to quit (a/r/q) ")
newlist = list(sampleDict.keys())
if answer == 'a':
name = input("Please enter the name ")
salary = int(input("Please enter the salary "))
value = newlist[-1]
newID=(int(value[-1]) + 1)
employeeID = "emp" + str(newID)
sampleDict[employeeID] = {'name': name, 'salary': salary}
print(str(sampleDict))
print("Employee sucessfully added to database")
if answer == 'r':
empID = input("Please enter the employee ID (ex: emp45) ")
if empID in newlist:
print("Employee found")
del sampleDict[empID]
print("Employee removed from database")
else:
print("Employee not found")
if answer == 'q':
break
print("Thank you for using our system!")
| true |
2da72ad227e82145ffd64f73b39620330c83c21d | greenhat-art/guess-the-number | /guessingGame.py | 604 | 4.3125 | 4 | import random
print("Number guessing game")
number = random.randint(1, 9)
chances = 0
print("Guess a number between 1 to 9:")
while chances < 5:
guess = int(input("Enter your guessed number:- "))
if guess == number:
print("Congratulation you guessed the right number!")
break
elif guess < number:
print("Your guess was low...Choose a higher number than", guess)
else:
print("Your guess was too high: Guess a number lower than", guess)
chances += 1
if not chances < 5:
print("Sorry, you lost. The number is", number) | true |
d347de34c5058cfabd6dfc1ad64bebde56569461 | Solannis/Python-Examples | /list_test.py | 549 | 4.125 | 4 | #!/usr/bin/python
class test:
def __init__(self):
self.name = ""
self.code = ""
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
print len(list)
list2 = []
print list2
list2.append("Test")
print list2
list2.append(49)
print list2
list3 = []
print len(list3)
myTest = test()
myTest.name = "Fred"
myTest.code = "HPL1"
list3.append(myTest)
print len(list3)
newTest = list3[0]
print newTest.code | false |
957d95428e0af1b303930e7071dfbe710f84f99b | anasm-17/DSA_collaborative_prep | /Problem_sets/fizzbuzz/fizzbuzz_jarome.py | 1,879 | 4.3125 | 4 | from test_script.test import test_fizzbuzz
"""
A classic Data Structures an algorithms problem, you are given an input array of integers from 1 to 100 (inclusive).
You have to write a fizzbuzz function that takes in an input array and iterates over it. When your function receives
a number that is a factor of 3 you should store 'Fizz' in the output array, if the number is a factor of 5 then you
should store 'Buzz' in the output array. Additionally, if the number is a factor of both 3 and 5, you must store
'FizzBuzz' in the output array. For all other cases, you must store the numbers as they are. Return the output array
from your function.
"""
def jaybuzz(some_input):
""" This function consumes a LIST of integers from 1 to 100 (inclusive) and produces a LIST with values
corresponding to the following rules:
For a number that is a factor of 3, output 'Fizz'
For a number that is a factor of 5, output 'Buzz'
For a number that is a factor of 3 and 5, output 'Fizzbuzz'
For all other numbers return them as is
Paramaters:
some_input - A list
Example:
jaybuzz([1,2,3,5,15]) = [1,2,'Fizz', 'Buzz', 'Fizzbuzz']
"""
result = []
if len(some_input) == 0:
return result
for i in some_input:
assert(type(i)== int), "Invalid input provided. Numbers must be integers"
assert(1 <= i <= 100),"Invalid input provided. Function should consume an array of integers from 1 to 100 (inclusive)"
if i % 15 == 0:
result.append('FizzBuzz')
continue
elif i % 3 == 0:
result.append('Fizz')
continue
elif i % 5 == 0:
result.append('Buzz')
continue
else:
result.append(i)
return result
if __name__ == '__main__':
test_fizzbuzz(jaybuzz) | true |
dd80e66757066ef8d97911680ffb0e47411d9c25 | jineshshah101/Python-Fundamentals | /Casting.py | 580 | 4.3125 | 4 | # variable example
x = 5
print(x)
# casting means changing one data type into another datatype
# casting the integer x into a float
y = float(x)
print(y)
# casting the integer x into a string
z = str(x)
print(z)
# Note: Cannot cast a string that has letters in it to a integer. The string itself must be numbers
# Casting string to an integer
t = int("55")
print(t)
# for boolen if you have the value be 0 it will be false. Any other value except for 0 will come out as true
h = bool(0)
print(h)
j = bool(1)
print(j)
k = bool(-5)
print(k) | true |
6141bb86224dbc1c19efca92f530682d1a04e570 | jineshshah101/Python-Fundamentals | /Calendar.py | 1,448 | 4.46875 | 4 | import calendar
#figuring things out with calendar
# printing out the week headers
# using the number 3 so we can get 3 characters for the week header
week_header = calendar.weekheader(3)
print(week_header)
print()
# print out the index value that represents a weekday
# in this case we are getting the index of the first weekday
# [0,1,2,3,4,5,6] correlates to Mon, Tue, Wed, Thu, Fri, Sat, Sun
weekday_index = calendar.firstweekday()
print(weekday_index)
print()
# print out the march month of 2019
# w stands for the number of characters shown for the week header
march_month = calendar.month(2019, 3, w=3)
print(march_month)
print()
# print out the days of a month in a matrix format
# in this case this is for march 2019
matrix_month_march = calendar.monthcalendar(2019, 3)
print(matrix_month_march)
print()
# print out the calendar for the entire year of 2020
entire_year = calendar.calendar(2020, w=3)
print(entire_year)
print()
# prints out the day of the week based on specific specifications in index format
day_of_the_week = calendar.weekday(2020, 1, 15)
print(day_of_the_week)
print()
# will tell you if a certain year is a leap year or not
leap_year = calendar.isleap(2020)
print(leap_year)
print()
# print out the number of leapdays within the specified years
# note: year 2 is not included in this search
leap_days_amount = calendar.leapdays(2000, 2021)
print(leap_days_amount) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.