blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5a1938c114dc6daacc49ca886cdc455fdf332334 | GDG-Buea/learn-python | /chpt8/Check_password.py | 984 | 4.25 | 4 | # This program prompts the user to enter a password and displays valid password if the rules are followed
# or invalid password otherwise.
# The password rules are as follows:
# A password must have at least eight characters.
# A password must consist of only letters and digits.
# A password must contain at least two digits
class Password:
def __init__(self, password=''):
self.__pass = password
def get_password(self):
self.__pass = input("Enter your password: ")
def check_password(self):
if self.__pass.__len__() == 8 and self.__pass.isalnum() and len([b for b in self.__pass if b.isdigit()]) == 2:
print("Valid password")
print()
else:
print("Invalid password\nPassword should contain atleast eight characters\nIt should contain letters and "
" at least two digits")
def main():
client1 = Password()
client1.get_password()
client1.check_password()
main()
| true |
a83a38b670291513114780332f49468854cc6d31 | GDG-Buea/learn-python | /chpt4/Two_rectangles.py | 2,806 | 4.1875 | 4 | # This program prompts the user to enter the center x-, y-coordinates, width, and height of two rectangles and determines
# whether the second rectangle is inside the first or overlaps with the first
import turtle
x1, y1 = eval(input("Enter the center of the first rectangle x1, y1: "))
width1, height1 = eval(input("Enter the width and height of the first rectangle width1, height1: "))
x2, y2 = eval(input("Enter the center of the second rectangle x2, y2: "))
width2, height2 = eval(input("Enter the width and height of the first rectangle width2, height2: "))
# rectangle 1
turtle.penup()
turtle.goto(height1, width1)
turtle.pendown()
turtle.right(90)
turtle.goto(height1, -width1)
turtle.right(90)
turtle.goto(height1, -width1)
turtle.right(90)
turtle.goto(-height1, -width1)
turtle.right(90)
turtle.goto(-height1, width1)
turtle.right(90)
turtle.goto(height1, width1)
# rectangle 2
turtle.penup()
turtle.goto(height2, width2)
turtle.pendown()
turtle.goto(height2, width2)
turtle.right(90)
turtle.goto(height2, -width2)
turtle.right(90)
turtle.goto(height2, -width2)
turtle.right(90)
turtle.goto(-height2, -width2)
turtle.right(90)
turtle.goto(-height2, width2)
turtle.right(90)
turtle.goto(-height2, width2)
turtle.right(90)
turtle.goto(height2, width2)
# Display the status
turtle.penup()
# Pull the pen up
turtle.goto(x1 - 70, y1 - height1 - 20)
turtle.pendown()
if (int((y2 - y1 ** 2) ** 0.5) + height2 // 2 <= height1 // 2) and \
(int((x2 - x1 ** 2) ** 0.5) + width2 // 2 <= width1 // 2) and\
(height1 // 2 + height2 // 2) <= height1 and (width1 // 2 + width2 // 2) <= width1:
print("r2 is inside r1")
elif (x1 + width1 // 2 > x2 - width2) or (y1 + height1 // 2 > y2 - height2):
print("r2 overlaps r1")
else:
print("r2 doe not overlap r1")
turtle.done()
# w2 = w2 / 2;
# h2 = h2 / 2;
#
# // Calculating
# range
# of
# r1 and r2
# double
# x1max = x1 + w1;
# double
# y1max = y1 + h1;
# double
# x1min = x1 - w1;
# double
# y1min = y1 - h1;
# double
# x2max = x2 + w2;
# double
# y2max = y2 + h2;
# double
# x2min = x2 - w2;
# double
# y2min = y2 - h2;
#
# if (x1max == x2max & & x1min == x2min & & y1max == y2max
# & & y1min == y2min) {
# // Check if the two are identicle
# System.out.print("r1 and r2 are indentical");
#
# } else if (x1max <= x2max & & x1min >= x2min & & y1max <= y2max
# & & y1min >= y2min) {
# // Check if r1 is in r2
# System.out.print("r1 is inside r2");
# } else if (x2max <= x1max & & x2min >= x1min & & y2max <= y1max
# & & y2min >= y1min) {
# // Check if r2 is in r1
# System.out.print("r2 is inside r1");
# } else if (x1max < x2min | | x1min > x2max | | y1max < y2min
# | | y2min > y1max) {
# // Check if the two overlap
# System.out.print("r2 does not overlaps r1");
# } else {
# System.out.print("r2 overlaps r1"); | true |
a80354862b38a8c557076e1e33163e901f8cc80d | GDG-Buea/learn-python | /chpt6/chessboard.py | 1,260 | 4.1875 | 4 | # This program displays two chessboards side by side
# # Draw one chessboard whose upper-left corner is at
# # (startx, starty) and bottom-right corner is at (endx, endy)
# def drawChessboard(startx, endx, starty, endy):
import turtle
def draw_chessboard(x, y):
# Draw chess board borders
turtle.speed(50)
turtle.pensize(3)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color("green")
for i in range(4):
turtle.forward(240)
turtle.left(90)
# Draw chess board inside
turtle.color("black")
for j in range(-120, 90, 60):
for i in range(-120, 120, 60):
turtle.penup()
turtle.goto(i, j)
turtle.pendown()
# Draw a small rectangle
turtle.begin_fill()
for k in range(4):
turtle.forward(30)
turtle.left(90)
for j in range(-90, 120, 60):
for i in range(-90, 120, 60):
turtle.penup()
turtle.goto(i, j)
turtle.pendown()
# Draw a small rectangle
turtle.begin_fill()
for k in range(4):
turtle.forward(30)
turtle.left(90)
turtle.end_fill()
draw_chessboard(-120, -120)
| false |
4af65b5572ff0ff6c98117246857974206f61aa5 | manosxatz/python | /lesson09/string.operators.py | 551 | 4.34375 | 4 | string = "Hello "
concatenation = string + string
print(f"Concatenation(+): {concatenation}")
multiplication = string * 5
print(f"Multiplication(*): {multiplication}")
string += "World!" # string = string + "World!"
print(f"Increment: {string}")
print(f"Char in string: 'W' in {string}: {'W' in string}")
print(f"Char not in string: 'W' not in {string}: {'W' not in string}")
comparison = "abc" < "abd" # also: >, <=, >=
print(f"Comparison: {comparison}")
equality = "aa" == "AA".lower() # also not equal: !=
print(f"Equality: {equality}") | false |
705f4f1369a7d92aacc156e8e8279b62037f17e8 | manosxatz/python | /lesson06/exercise3.py | 214 | 4.1875 | 4 | N = 27
if N == 0 or N == 1:
print("It's not prime")
else:
for i in range(2,N):
if N % i == 0:
print("It's not prime")
break
else:
print("It's prime")
| false |
352d66e90fa946cfaaae03ad913bb144e10de84b | manosxatz/python | /lesson08/exercise09.04.py | 1,913 | 4.1875 | 4 | from random import seed
from random import randrange
from datetime import datetime # all 3 at the beginning
seed(datetime.now()) # once, before randint call
round = 0
score = [0, 0] # Player, computer
history = []
while True:
round += 1
print("Round " + str(round))
# Eisodos xristi
player_input = int(input("Choose (0-rock, 1-scissors, 2-paper: "))
while player_input not in [0,1,2]:
print("Wrong input. Choices: rock, scissors, paper")
player_input = int(input("Choose (0-rock, 1-scissors, 2-paper: "))
# Epilogi ipologisti
computer_random = randrange(3)
if computer_random == 0:
computer_choice = "rock"
elif computer_random == 1:
computer_choice = "scissors"
else:
computer_choice = "paper"
# Elegxos toy poios nikise
diff = player_input - computer_choice
if diff == -1 or diff == 2:
winner = "player"
elif diff == 1 or diff == -2:
winner = "computer"
else:
winner = "no winner"
# Diorthosi tou skor
if winner == "player":
score[0] += 1
elif winner == "computer":
score[1] += 1
# enimerwsi tou istorikou
history.append("Round " + str(round) + ": Player: " + player_input + ", Computer: " + computer_choice + ", Score: " + str(score[0]) + "-" + str(score[1]))
# Ektypwsi toy nikiti kai tou skor
print("Computer picks: " + computer_choice)
print("Player-Computer: " + str(score[0]) + "-" + str(score[1]))
if score[0] == 3:
print("Player wins! ")
print("")
for history_item in history:
print(history_item)
break
elif score[1] == 3:
print("Computer wins! ")
print("")
for history_item in history:
print(history_item)
break
print("====================\n") | true |
53343258641933282aeef488ca1c2a329a75dcd7 | manosxatz/python | /lesson09/exercise03.py | 2,278 | 4.1875 | 4 | from random import seed
from random import randrange
from datetime import datetime # all 3 at the beginning
seed(datetime.now()) # once, before randint call
round = 0
score = [0, 0] # Player, computer
history = []
while True:
round += 1
print(f"Round {round}")
# Eisodos xristi
player_input = input("Choose: ")
while player_input not in ["rock", "scissors", "paper"]:
print("Wrong input. Choices: rock, scissors, paper")
player_input = input("Choose: ")
# Epilogi ipologisti
computer_random = randrange(3)
if computer_random == 0:
computer_choice = "rock"
elif computer_random == 1:
computer_choice = "scissors"
else:
computer_choice = "paper"
# Elegxos toy poios nikise
if player_input == "rock":
if computer_choice == "rock":
winner = "no winner"
elif computer_choice == "paper":
winner = "computer"
else:
winner = "player"
elif player_input == "paper":
if computer_choice == "rock":
winner = "player"
elif computer_choice == "paper":
winner = "no winner"
else:
winner = "computer"
else: # player_input == scissors
if computer_choice == "rock":
winner = "computer"
elif computer_choice == "paper":
winner = "player"
else:
winner = "no winner"
# Diorthosi tou skor
if winner == "player":
score[0] += 1
elif winner == "computer":
score[1] += 1
# enimerwsi tou istorikou
history.append(f"Round {round}: Player: {player_input}, Computer: {computer_choice}, Score: {score[0]}-{score[1]}")
# Ektypwsi toy nikiti kai tou skor
print(f"Computer picks: {computer_choice}")
print(f"Player-Computer: {score[0]}-{score[1]}")
if score[0] == 3:
print("Player wins! ")
print("")
for history_item in history:
print(history_item)
break
elif score[1] == 3:
print("Computer wins! ")
print("")
for history_item in history:
print(history_item)
break
print("====================\n") | false |
ca99e07c006d41918121a8725892eb31a61c8edf | mba-mba/HacktoberFest2020-1 | /Python/listandtuple.py | 504 | 4.4375 | 4 | def ListandTuple():
l = []#This is a empty list (mutable)
t = ()#This is a empty tuple (its not mutable)
#now we are taking input from user and adding that input to list and tuples(as we know tuple is not mutable so we are converting that list into tuple by typecasting)
print("Please Enter Element of list like ex. 1 23 4 5 ")
user = list(map(int,input()))
print(user)#This will print list of entered element
print(tuple(user))#This will print tuple
ListandTuple()#Calling above function
| true |
be676a79178775b630695ea1cc0c1eeeb70107f6 | Yuvaganesh-K/Hangman-game-using-python | /hangman.py | 2,612 | 4.1875 | 4 | # library that we use in order to choose on random words from a list of words
import random
# Here the user is asked to enter the name first
name = input("What is your name?")
print("Good Luck {0} !! ".format(name))
words = list()
WORDLIST = 'wordlist.txt'
f = open(WORDLIST, 'r')
for item in f:
item = item.strip().lower()
words.append(item)
# Function will choose one random word from this list of words
word = random.choice(words)
guesses = ''
# any limits for the number of turns can be set here
while True:
turns = int(input('Enter number of chances you want [min:2,max:12]:'))
if turns < 2 or turns > 12:
print('Please enter within the specified values!')
else:
break
print("Game has begun. Guess the characters:-")
while turns > 0:
# counts the number of times a user fails
failed = 0
# all characters from the input word taking one at a time.
for char in word:
# comparing that character with the character in guesses
if char in guesses:
print(char, end='')
else:
print('_', end='')
# for every failure 1 will be incremented in failure
failed += 1
if failed == 0:
# user will win the game if failure is 0 and 'You Win' will be given as output
print('\r')
print("You Win")
# this prints the correct word. Not mandatory to include this line.
print("The word is '{0}'".format(word))
break
print('\r')
# if user has input the wrong alphabet then it will ask user to enter another alphabet#
guess = input("guess a character:")
guess = guess.lower()
# every input character will be stored in guesses
guesses += guess
# check input with the character in word
if guess in word:
print('Right')
print('You have {0} more guesses'.format(turns))
elif guess not in word:
turns -= 1
# if the character doesn’t match the word then “Wrong” will be given as output
print("Wrong")
# this will print the number of turns left for the user
print('You have {0} more guesses'.format(turns))
if turns == 0:
print("You Loose!! Better luck next time!!")
print('The word is "{0}"'.format(word))
| true |
27258bc048a377045e215565e0962973413a8039 | 0x424D/BSc-Ethical-Hacking-Cybersecurity | /Palindrome.py | 471 | 4.1875 | 4 | # Write a recursive function called isPalindrome.
# The function should take one input, S, which is assumed a string.
# It should produce a Boolean output depending
# - True if the string is a palindrome
# - False if not.
def isPalindrome(S):
"""Takes a string S. Returns True if S is a palindrome, False otherwise"""
if len(S) == 0:
return True
if S[0] != S[-1]:
return False
return isPalindrome(S[1:len(S) - 1])
print(isPalindrome("a"))
| true |
2b3c36f445cfce20e8ff9c4e4fa8de1e1c961c62 | vanessakoch/ppi-2 | /exerciciosPpi/103ex.py | 1,834 | 4.1875 | 4 | ###
# Exercicios
###
# 1) Extraia o titulo do livro da string
# 2) Salve o titulo de cada livro em uma variável
# 3) Quantos caracteres cada título tem?
# 4) Imprima com a formatacao: {Titulo} - {Autor}, {Ano}
book1 = 'Homo Deus by Yuval Noah Harari, 2015'
book2 = 'Antifragile by Nassim Nicholas Taleb, 2012'
book3 = 'Fooled by Randomness by Nassim Nicholas Taleb, 2001'
# 5) Verifique se uma palavra é uma palindrome perfeita.
# Palindrome perfeito sao palavras que ao serem escritas em ordem reversa,
# resultam na mesma palavra.
# Ignore espacos e caixa alta
palindrome_one = 'ovo'
palindrome_two = 'Natan'
palindrome_three = 'luz azul'
palindrome_four = 'caneta azul'
# 1
quebra1 = book1.split('by')
quebra2 = book2.split('by')
quebra3 = book3.split('by')
print(quebra1[0])
print(quebra2[0])
print(quebra3[0])
# 2
titulo1 = quebra1[0]
titulo2 = quebra2[0]
titulo3 = quebra3[0]
# 3
tamanhoBook1 = len(titulo1)
print(tamanhoBook1)
tamanhoBook2 = len(titulo2)
print(tamanhoBook2)
tamanhoBook3 = len(titulo3)
print(tamanhoBook3)
# 4
quebra1 = book1.split(', ')
ano = quebra1[1]
quebra2 = book1.split('by')
titulo = quebra2[0]
autor = book1[13:30]
print("{} - {} , {} ".format(titulo, autor, ano))
# 5
# one
strLimpa = ''.join(palindrome_one.split())
isPalindrome = False
if strLimpa.lower() == strLimpa[::-1].lower():
isPalindrome = True;
print(isPalindrome)
# two
strLimpa = ''.join(palindrome_two.split())
isPalindrome = False
if strLimpa.lower() == strLimpa[::-1].lower():
isPalindrome = True;
print(isPalindrome)
# three
strLimpa = ''.join(palindrome_three.split())
isPalindrome = False
if strLimpa.lower() == strLimpa[::-1].lower():
isPalindrome = True;
print(isPalindrome)
# four
strLimpa = ''.join(palindrome_four.split())
isPalindrome = False
if strLimpa.lower() == strLimpa[::-1].lower():
isPalindrome = True;
print(isPalindrome) | false |
c7eb124b0c94c01b6e3d14b3ba20ec7db6d736a9 | michelle-liu7/hash-map-concordance-program | /word_count.py | 2,704 | 4.375 | 4 | # Author: Michelle Liu
# Class: CS 261
# Date: 6/10/2020
# word_count.py
# ===================================================
# Implement a word counter that counts the number of
# occurrences of all the words in a file. The word
# counter will return the top X words, as indicated
# by the user.
# ===================================================
import re
from hash_map import HashMap
"""
This is the regular expression used to capture words. It could probably be endlessly
tweaked to catch more words, but this provides a standard we can test against, so don't
modify it for your assignment submission.
"""
rgx = re.compile("(\w[\w']*\w|\w)")
def hash_function_2(key):
"""
This is a hash function that can be used for the hashmap.
"""
hash = 0
index = 0
for i in key:
hash = hash + (index + 1) * ord(i)
index = index + 1
return hash
def top_words(source, number):
"""
Takes a plain text file and counts the number of occurrences of case insensitive words.
Returns the top `number` of words in a list of tuples of the form (word, count).
Args:
source: the file name containing the text
number: the number of top results to return (e.g. 5 would return the 5 most common words)
Returns:
A list of tuples of the form (word, count), sorted by most common word. (e.g. [("a", 23), ("the", 20), ("it", 10)])
"""
keys = set()
ht = HashMap(2500, hash_function_2)
# This block of code will read a file one word as a time and
# put the word in `w`. It should be left as starter code.
with open(source) as f:
for line in f:
words = rgx.findall(line)
for w in words:
# if a link with the key w exists in the table, update increment its value
if ht.contains_key(w.lower()):
ht.put(w.lower(), ht.get(w.lower()) + 1)
# otherwise add w to the hash table as a new link with count of 1
else:
ht.put(w.lower(), 1)
# call the list_of_links() method of the hash table to get a list of tuples of all links in the table
word_list = ht.list_of_links()
# sort the list of tuples from highest to lowest according to count
word_list.sort(key=get_count, reverse=True)
# return the first however many words requested by the user in a list of tuples
return word_list[:number]
def get_count(element):
"""
Returns the second element of a tuple
"""
return element[1]
# print(top_words("alice.txt",10)) # COMMENT THIS OUT WHEN SUBMITTING TO GRADESCOPE
| true |
e93e84cf534f3e4f02e3743b201ecef3a3522122 | Ekta-751/Assignment | /assignment10.py | 2,025 | 4.21875 | 4 | #Perform Inheritance
class animal:
def animal_attribute(self):
print("Animal")
class tiger(animal):
pass
a=tiger()
a.animal_attribute()
#Write The Output of a Code
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print (a.f(), b.f())
print (a.g(), b.g())
#Create a Class Cope and Initialize it
class Cop:
def __init__(self,copname,copage,work_experience,designation):
self.copname=copname
self.copage=copage
self.work_experience=work_experience
self.designation=designation
def display(self):
print("Details:")
print(self.copname)
print(self.copage)
print(self.work_experience)
print(self.designation)
def update(self,copname,copage,work_experience,designation):
self.copname=copname
self.copage=copage
self.work_experience=work_experience
self.designation=designation
class Mission(Cop):
fighter_planes=4
tankers=7
def add_mission_details(self):
print("number of fighter planes:",self.fighter_planes)
print("number of tankers:",self.tankers)
copname=input("Name:")
copage=int(input("Age:"))
work_experience=input("Work Experience:")
designation=input("Designation:")
a=Mission(copname,copage,work_experience,designation)
print("")
a.display()
print("")
a.add_mission_details()
print("")
a.update(input("Name:"),int(input("Age:")),input("Work Experience:"),input("Designation:"))
print("")
a.display()
#Create The Class Shape And Initialize It Initialize it
class Shape:
def __init__(self,len,bre):
self.len=len
self.bre=bre
def area(self):
self.result=self.len*self.bre
class Rectangle(Shape):
def arearectangle(self):
print("area of rectangle:",self.result)
class Square(Shape):
def areasquare(self):
print("area of square:",self.result)
len=int(input("enter the len:"))
bre=int(input("enter the bre:"))
c=Rectangle(len,bre)
b=Square(len,bre)
if len==bre:
b.area()
b.areasquare()
else:
c.area()
c.arearectangle()
| true |
6b95c953f818cbf08e03a7804ffe026f1f4b3a41 | MTrajK/coding-problems | /Arrays/reverse_array.py | 1,449 | 4.40625 | 4 | '''
Reverse array
Reverse an array, in constant space and linear time complexity.
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
=========================================
Reverse the whole array by swapping pair letters in-place (first with last, second with second from the end, etc).
Exist 2 more "Pythonic" ways of reversing arrays/strings (but not in-place, they're creating a new list):
- reversed_arr = reversed(arr)
- reversed_arr = arr[::-1]
But I wanted to show how to implement a reverse algorithm step by step so someone will know how to implement it in other languages.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def reverse_arr(arr):
start = 0
end = len(arr) - 1
while start < end:
# reverse the array from the start index to the end index by
# swaping each element with the pair from the other part of the array
swap(arr, start, end)
start += 1
end -= 1
return arr
def swap(arr, i, j):
# swapping two elements from a same array
arr[i], arr[j] = arr[j], arr[i]
'''same as
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
'''
###########
# Testing #
###########
# Test 1
# Correct result => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(reverse_arr([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Test 2
# Correct result => [5, 4, 3, 2, 1]
print(reverse_arr([1, 2, 3, 4, 5])) | true |
3c595033086482c9ef83494660c074f7d12e0281 | MTrajK/coding-problems | /Math/calculate_area_of_polygon.py | 1,078 | 4.28125 | 4 | '''
Calculate Area of Polygon
Given ordered coordinates of a polygon with n vertices. Find area of the polygon.
Here ordered mean that the coordinates are given either in clockwise manner or anticlockwise from first vertex to last.
Input: [(0, 0), (3, 0), (3, 2), (0, 2)]
Output: 6.0
Output explanation: The polygon is a 3x2 rectangle parallel with the X axis. The area is 6 (3*2).
=========================================
Use Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula).
abs( 1/2 ((X1Y2 + X2Y3 + ... + Xn-1Yn + XnY1) - (X2Y1 + X3Y2 + ... + XnYn-1 + X1Yn)) )
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def calculate_area_of_polygon(polygon):
n = len(polygon)
prev = polygon[-1]
area = 0
for curr in polygon:
area += (prev[0] + curr[0]) * (prev[1] - curr[1])
prev = curr
return abs(area / 2) # return absolute value
###########
# Testing #
###########
# Test 1
# Correct result => 6.0
print(calculate_area_of_polygon([(0, 0), (3, 0), (3, 2), (0, 2)])) | true |
3bbf56e085820a89fb5308e74dbb2ea53bab6a7b | MTrajK/coding-problems | /Other/river_sizes.py | 2,116 | 4.15625 | 4 | '''
River Sizes
You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s.
Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are
either horizontally or vertically adjacent (but not diagonally adjacent).
The number of adjacent 1s forming a river determine its size.
Write a function that returns an array of the sizes of all rivers represented in the input matrix.
Note that these sizes do not need to be in any particular order.
Input:
[
[1, 0, 0, 1],
[1, 0, 1, 0],
[0, 0, 1, 0],
[1, 0, 1, 0]
]
Output: [2, 1, 3, 1]
=========================================
This problem can be solved using DFS or BFS.
If 1 is found, find all horizontal or vertical neighbours (1s), and mark them as 0.
Time Complexity: O(N*M)
Space Complexity: O(N*M) , because of recursion calls stack
'''
############
# Solution #
############
def river_sizes(matrix):
n = len(matrix)
m = len(matrix[0])
results = []
for i in range(n):
for j in range(m):
if matrix[i][j] != 0:
# find the river size
size = dfs((i, j), matrix)
# save the river size
results.append(size)
return results
def dfs(coord, matrix):
(i, j) = coord
if i < 0 or j < 0:
# invalid position
return 0
n = len(matrix)
m = len(matrix[0])
if i == n or j == m:
# invalid position
return 0
if matrix[i][j] == 0:
# not a river
return 0
# update the matrix, the matrix is passed by reference
matrix[i][j] = 0
# this position is part of river
size = 1
# directions: down, left, up, right
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
# check all 4 directions
for d in dirs:
size += dfs((i + d[0], j + d[1]), matrix)
return size
###########
# Testing #
###########
# Test 1
# Correct result => [2, 1, 3, 1]
matrix = [
[1, 0, 0, 1],
[1, 0, 1, 0],
[0, 0, 1, 0],
[1, 0, 1, 0]
]
print(river_sizes(matrix)) | true |
1ebe773746be8e8cf777e0eedb4aa85e133396bd | MTrajK/coding-problems | /Arrays/min_swaps.py | 1,451 | 4.40625 | 4 | '''
Min Swaps
You have a list of numbers and you want to sort the list.
The only operation you have is a swap of any two arbitrary numbers.
Find the minimum number of swaps you need to do in order to make the list sorted (ascending order).
- The array will contain N elements
- Each element will be between 1 and N inclusive
- All the numbers will be different
Input: [4, 1, 3, 2]
Output: 2
Output explanation: swap(4, 1) = [1, 4, 3, 2], swap(4, 2) = [1, 2, 3, 4]
=========================================
According to the description, all elements will have their position in the array,
for example, K should be located at K-1 in the array.
Itterate the array and check if each position has the right element,
if not, put that element in the right position and check again.
Time Complexity: O(N) , the solution looks like O(N^2) but that's not possible, at most O(2*N) operations can be done
Space Complexity: O(1)
'''
############
# Solution #
############
def min_swaps(a):
n = len(a)
swaps = 0
for i in range(n):
# swap the elements till the right element isn't found
while a[i] - 1 != i:
swap = a[i] - 1
# swap the elements
a[swap], a[i] = a[i], a[swap]
swaps += 1
return swaps
###########
# Testing #
###########
# Test 1
# Correct result => 2
print(min_swaps([4, 1, 3, 2]))
# Test 2
# Correct result => 3
print(min_swaps([4, 1, 2, 3])) | true |
859bccc7916edb43dac72c62d8dc5d7b738cdb4c | MTrajK/coding-problems | /Arrays/sort_rgb_array.py | 2,411 | 4.15625 | 4 | '''
Sort RGB Array
Given an array of strictly the characters 'R', 'G', and 'B', segregate
the values of the array so that all the Rs come first, the Gs come second, and the Bs come last.
You can only swap elements of the array.
Do this in linear time and in-place.
Input: ['G', 'B', 'R', 'R', 'B', 'R', 'G']
Output: ['R', 'R', 'R', 'G', 'G', 'B', 'B']
=========================================
Play with pointers/indices and swap elements. (only one iteration)
Save the last R, G and B indices, when adding some color, move the rest indices by 1.
Time Complexity: O(N)
Space Complexity: O(1)
Count R, G, B and populate the array after that. (2 iterations)
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def sort_rgb_array(arr):
n = len(arr)
# indexes/pointers of the last element of each color
r, g, b = 0, 0, 0
for i in range(n):
# swap the element and move the pointer
if arr[i] == 'R':
swap(arr, i, r)
r += 1
# move pointer
if r > g:
g = r
# swap the element and move the pointer
if arr[i] == 'G':
swap(arr, i, g)
g += 1
# move pointer
if g > b:
b = g
# swap the element and move the pointer
if arr[i] == 'B':
swap(arr, i, b)
b += 1
return arr
def swap(arr, i, j):
# swaps two elements in an array
arr[i], arr[j] = arr[j], arr[i]
##############
# Solution 2 #
##############
def sort_rgb_array_2(arr):
rgb = {
'R': 0,
'G': 0,
'B': 0
}
# count colors
for c in arr:
rgb[c] += 1
# adjust the intervals
rgb['G'] += rgb['R']
rgb['B'] += rgb['G']
# assign colors
for i in range(len(arr)):
if i < rgb['R']:
arr[i] = 'R'
elif i < rgb['G']:
arr[i] = 'G'
else:
arr[i] = 'B'
return arr
###########
# Testing #
###########
# Test 1
# Correct result => ['R', 'R', 'R', 'G', 'G', 'B', 'B']
print(sort_rgb_array(['G', 'B', 'R', 'R', 'B', 'R', 'G']))
print(sort_rgb_array_2(['G', 'B', 'R', 'R', 'B', 'R', 'G']))
# Test 2
# Correct result => ['R', 'R', 'G', 'G', 'B', 'B', 'B']
print(sort_rgb_array(['B', 'B', 'B', 'G', 'G', 'R', 'R']))
print(sort_rgb_array_2(['B', 'B', 'B', 'G', 'G', 'R', 'R'])) | true |
60283a6d5c1f79696668b90ae3f5cbe9d82a03c2 | MTrajK/coding-problems | /Strings/swap_first_and_last_word.py | 2,196 | 4.15625 | 4 | '''
Swap the frst and the last word
Given an string, you need to swap the first and last word in linear time.
Everything between should stay in same order.
Sample input: 'i like this program very much'
Sample output: 'much like this program very i'
=========================================
Reverse the whole string, after that reverse only first and only last word,
in the end reverse everything between first and last word. (using IN-PLACE reversing)
In Python, the string manipulation operations are too slow (string is immutable), because of that we need to convert the string into array.
In C/C++, the Space complexity will be O(1) (because the strings are just arrays with chars).
Time complexity: O(N) , O(N + N) = O(2 * N) = O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
def swap_first_and_last_word(sentence):
arr = [c for c in sentence] # or just arr = list(sentence)
first_idx = 0
last_idx = len(arr) - 1
# reverse the whole array, in this way I'll change the first and the last word
reverse_array(arr, first_idx, last_idx)
# find positions of the first and the last space char
first_space = first_idx
while arr[first_space] != ' ':
first_space += 1
last_space = last_idx
while arr[last_space] != ' ':
last_space -= 1
# reverse only the first word
reverse_array(arr, first_idx, first_space - 1)
# reverse only the last word
reverse_array(arr, last_space + 1, last_idx)
# reverse everything between (with this reversing, all words between will have the same order as the starting one)
reverse_array(arr, first_space + 1, last_space - 1)
return ''.join(arr)
def reverse_array(arr, start, end):
# reverse the array from the start index to the end index
while start < end:
arr[start], arr[end] = arr[end], arr[start] # swap
start += 1
end -= 1
###########
# Testing #
###########
# Test 1
# Correct result => 'practice makes perfect
print(swap_first_and_last_word('perfect makes practice'))
# Test 2
# Correct result => 'much like this program very i'
print(swap_first_and_last_word('i like this program very much')) | true |
f774fe30a9f472ea1ef1812c4e7552838419305a | MTrajK/coding-problems | /Arrays/secret_santa.py | 1,577 | 4.125 | 4 | '''
Secret Santa
Secret Santa is a game in which a group of friends or colleagues exchange Christmas presents anonymously,
each member of the group being assigned another member for whom to provide a small gift.
You're given a list of names, make a random pairs (each participant should have another name as pair).
Return an array with pairs represented as tuples.
Input: ['a', 'b', 'c']
Output: This is a nondeterministic algorithm, more solutions exists, here are 2 possible solutions:
[('a', 'b'), ('b', 'c'), ('c', 'a')], [('a', 'c'), ('c', 'b'), ('b', 'a')]
=========================================
Shuffle the array (this algorithm is explained in shuffle_array.py) and pair the current element
with the next element (neighbouring).
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
from random import randint
def secret_santa(names):
# or use shuffle method from random module (from random import shuffle)
shuffle_array(names)
pairs = []
n = len(names)
prev = names[-1] # or names[n - 1]
for curr in names:
pairs.append((prev, curr))
prev = curr
return pairs
def shuffle_array(arr):
n = len(arr)
for i in range(n):
rand = randint(i, n - 1) # or randint(0, i) it's same
arr[i], arr[rand] = arr[rand], arr[i] # swap elements
# the original arr is already changed
return arr
###########
# Testing #
###########
# Test 1
# Correct result => nondeterministic algorithm, many solutions exist
print(secret_santa(['a', 'b', 'c'])) | true |
0de8f07677af5852b2383ee04ffc493a9f17b838 | MTrajK/coding-problems | /Arrays/find_el_smaller_left_bigger_right.py | 2,463 | 4.15625 | 4 | '''
Find the element before which all the elements are smaller than it, and after which all are greater
Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it.
Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element.
Input: [5, 1, 4, 3, 6, 8, 10, 7, 9]
Output: 6
=========================================
Traverse the array starting and check if the current element is smaller than the wanted one. If it's smaller then reset the result.
In meantime keep track of the maximum value till the current position. This maximum value will be used for finding a new "middle" element.
If the maximum value
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def find_element_smaller_left_bigger_right(arr):
n = len(arr)
curr_max = arr[0]
result = -1
for i in range(1, n):
curr_el = arr[i]
if result == -1 and curr_el >= curr_max and i != n - 1:
result = curr_el
elif curr_el < result:
result = -1
if curr_el > curr_max:
curr_max = curr_el
return result
###########
# Testing #
###########
# Test 1
# Correct result => 6
print(find_element_smaller_left_bigger_right([5, 1, 4, 3, 6, 8, 10, 7, 9]))
# Test 2
# Correct result => -1
print(find_element_smaller_left_bigger_right([5, 1, 4, 4]))
# Test 3
# Correct result => 7
print(find_element_smaller_left_bigger_right([5, 1, 4, 6, 4, 7, 14, 8, 19]))
# Test 4
# Correct result => 5
print(find_element_smaller_left_bigger_right([4, 2, 5, 7]))
# Test 5
# Correct result => -1
print(find_element_smaller_left_bigger_right([11, 9, 12]))
# Test 6
# Correct result => 234
print(find_element_smaller_left_bigger_right([177, 234, 236, 276, 519, 606, 697, 842, 911, 965, 1086, 1135, 1197, 1273, 1392, 1395, 1531, 1542, 1571, 1682, 2007, 2177, 2382, 2410, 2432, 2447, 2598, 2646, 2672, 2826, 2890, 2899, 2916, 2955, 3278, 3380, 3623, 3647, 3690, 4186, 4300, 4395, 4468, 4609, 4679, 4712, 4725, 4790, 4851, 4912, 4933, 4942, 5156, 5186, 5188, 5244, 5346, 5538, 5583, 5742, 5805, 5830, 6010, 6140, 6173, 6357, 6412, 6414, 6468, 6582, 6765, 7056, 7061, 7089, 7250, 7275, 7378, 7381, 7396, 7410, 7419, 7511, 7625, 7639, 7655, 7776, 7793, 8089, 8245, 8622, 8758, 8807, 8969, 9022, 9149, 9150, 9240, 9273, 9573, 9938]))
| true |
519c3c8ffe2380cbecd169c7bbb7634f0ad18a75 | tankasalamanisha/codechef | /smallfactorial.py | 357 | 4.15625 | 4 | #!usr/bin/env python
def factorial(num):
fact=1
while(num!=0):
if(num==0):
return 1
elif(num==1):
return 1
else:
fact=num*factorial(num-1)
return fact
r=int(input())
factl=[]
for i in range(r):
num=int(input())
factl.append(factorial(num))
for j in factl:
print(j)
| true |
3e30b03a5f6ae8d7e97a294be9d9b5f440c291c7 | Kellysmith7/Module3 | /format_output/average_score_2.py | 451 | 4.1875 | 4 | """
Program: average_score_2.py
Author: Kelly Smith
Last date updated: 09/09/2019
Program to find the average of three numbers
"""
def average(scores):
score_1 = input("enter first score")
score_2 = input("enter second score")
score_3 = input("enter third score")
x = int(score_1)
y = int(score_2)
z = int(score_3)
scores = [x, y, z]
return sum(scores) / len(scores)
def scores(args):
pass
print(average(scores))
| true |
c8511c71f69a1d080f5d0ea9c0682226ed5f5bdb | SWeszler/programming_problems | /lists/common_elements/common_elements.py | 712 | 4.25 | 4 | def common_elements(list1, list2):
""" Returns a list of common elements between list1 and list2 """
p1 = 0
p2 = 0
result = []
while p1 < len(list1) and p2 < len(list2):
print(list1[p1], list2[p2])
if list1[p1] == list2[p2]:
result.append(list1[p1])
p1 += 1
p2 += 1
elif list1[p1] > list2[p2]:
p2 += 1
else:
p1 += 1
return result
def common_elements_naive(list1, list2):
""" NAIVE approach, not recommended. Returns a list of common elements between list1 and list2 """
result = []
for item1 in list1:
if item1 in list2:
result.append(item1)
return result | true |
2d7e96ad8df2e1efb6abaf96187832ca8d3bf6ed | mattdhol/Unit3Lab1 | /exercise-5.py | 656 | 4.40625 | 4 | # exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
# 2. Print each term and number as follows:
# term: 0 / number: 0
# term: 1 / number: 1
# term: 2 / number: 1
# term: 3 / number: 2
# term: 4 / number: 3
# term: 5 / number: 5
# etc.
num1 = 0
num2 = 1
# num3 = num1 + num2
print ("term: 0 / 50: 0")
print ("term: 1 / 50: 1")
for number in range(2, 51):
num3 = num1 + num2
num1 = num2
num2 = num3
print ("term:", number,"/ 50:", num3)
# Hint: The next number is found by adding the two numbers before it
| true |
3caa7fdfc6682103ec90a26d6f1db3404f67ce82 | yvlee/Univeristy-Project | /Sorting Algorithms/QuickSort.py | 1,541 | 4.15625 | 4 | def quickSort(alist):
recursive_quick(alist,0,len(alist)-1)
return alist
def recursive_quick(alist,first,last):
if first<last:
mid = partition(alist,first,last)
recursive_quick(alist,first,mid-1)
recursive_quick(alist,mid+1,last)
def partition(alist,first,last):
pivot = alist[first] #pivot value
left = first+1 #left index
right = last #right index
check = False
while not check:
while left <= right and alist[left] <= pivot: #while left index <= right index and alist[left index] <= pivot value
left = left + 1 #left index + 1, move index one position to the right
while alist[right] >= pivot and right >= left: #while alist[right index] >= pivot value and right index >= left index
right = right -1 # right index move one position to the left
if right < left: #means sorted list
check = True
else:
temp = alist[left]
alist[left] = alist[right]
alist[right] = temp
temp = alist[first]
alist[first] = alist[right]
alist[right] = temp
return right
if __name__ == '__main__':
#Below are examples of inputs to try with the quicksort algorithm.
unsortedList = [54,26,93,17,77,31,44,55,20]
unsortedTable = [("acdb",4), ("abdc",3), ("adcb",5), ("abcd",2), ("aaaa",1)]
unsortedList = ["acdb", "abdc","adcb","abcd","aaaa"]
print(quickSort(unsortedTable))
| true |
bc98a82351aa41a5526aab91865b9c3d359b0d4a | FiftyBillion/CS-Python | /Employee.py | 932 | 4.21875 | 4 | #Po-I Wu, Cheng Yi Tsai
#11/8/2016
#Homework 4-3
#This program read employees' hours and tell the total
#Employee 1
days = int(input("Employee 1: How many days? "))
total = 0 #so the hours can be added together, cumulatively
for day in range (0, days):
hrs = float(input ("Hours? "))
if hrs > 8:
hrs = 8
total = total + hrs
per_day = total / days
print("Employee 1's total hours = ",int(total), \
" (", format(per_day, '.2f')," hrs / day)", sep='')
#Employee 2
days = int(input("\nEmployee 2: How many days? "))
total_2 = 0
for day in range (0, days):
hrs = float(input ("Hours? "))
if hrs > 8:
hrs = 8
total_2 = total_2 + hrs
per_day = total_2 / days
print("Employee 2's total hours = ",int(total_2), \
" (", format(per_day, '.2f')," hrs / day)", sep='')
total_both = total + total_2
print("\nTotal hours for both =", int(total_both))
input("\nPress enter to continue.")
| false |
b2c6159d86c7865cbeb79c0253ea16d9caff0964 | OblackatO/OffensiveSecurity | /Hashing/atbash_cipher_encryption.py | 563 | 4.125 | 4 | from string import ascii_lowercase
alphabet = ascii_lowercase
inverted_alphabet = ''
for x in range(len(alphabet)):
x = x + 1 # because it start in 0, and when we are starting at the opposite side of a string, 0 does not count.
char = alphabet[-x]
inverted_alphabet += char
def translate_atbash(message):
translation_function = bytes.maketrans(alphabet.encode(),inverted_alphabet.encode())
return message.translate(translation_function)
message = 'This is a test to be translated to atbash cipher.'.lower().encode()
print(translate_atbash(message))
| true |
1f74eabe5f69c4316bd8c87e003a5a1ee2a3d0c6 | whoophee/DCP | /162.py | 1,039 | 4.15625 | 4 | # Good morning! Here's your coding interview problem for today.
# This problem was asked by Square.
# Given a list of words, return the shortest unique prefix of each word. For example, given the list:
# • dog
# • cat
# • apple
# • apricot
# • fish
# Return the list:
# • d
# • c
# • app
# • apr
# • f
####
def shortest_prefix(arr):
letters = {chr(cur):{} for cur in range(ord('a'), ord('z')+1)}
ret = []
# generate a prefix counter for all the words.
for word in arr:
for i, c in enumerate(word):
letters[c][i] = letters[c].get(i, 0) + 1
# the point at which a character from a word appears to be unique,
# can be assumed to be the unique prefix end point
for word in arr:
for i, c in enumerate(word):
if letters[c][i] == 1:
break
# min to avoid exceeding word size if no unique prefix found
ret.append(word[:min(i+1, len(word))])
return ret
####
print(shortest_prefix(['dog', 'cat', 'apple', 'apricot', 'fish']))
| true |
b9913953b12bfcb9d98277f9459e9ca9105934fe | whoophee/DCP | /161.py | 468 | 4.125 | 4 | # This problem was asked by Facebook.
# Given a 32-bit integer, return the number with its bits reversed.
# For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000,
# return 0000 1111 0000 1111 0000 1111 0000 1111.
####
def reverse32(x):
ret = 0
for _ in range(32):
ret = (ret<<1) + (x&1)
x >>= 1
return ret
####
t = int('10110000111100001111000011110001', 2)
print("{:b}".format(t))
print("{:b}".format(reverse32(t)))
| true |
d3b27e10469f718164053d8f0183430520e69817 | whoophee/DCP | /228.py | 815 | 4.28125 | 4 | # This problem was asked by Twitter.
# Given a list of numbers, create an algorithm that arranges them in
# order to form the largest possible integer. For example, given
# [10, 7, 76, 415], you should return 77641510.
####
def largest_possible(numlist):
strlist = [str(num) for num in numlist]
maxlen = len(max(strlist, key=lambda x: len(x)))
# Key is used because using comparator functions isn't good Pythonic practice.
# This function repeats the last character to maximum length
# eg: 7 becomes 777
# 76 becomes 766
# This gives a method to ascertain the effective priority of one number over another
def transform(x):
return x + (maxlen - len(x))*x[-1]
return sorted(strlist, key = transform, reverse = True)
####
print(largest_possible([10, 7, 76, 415])) | true |
e6f2a656d9afbe0e469015f612c16702054ed4fa | whoophee/DCP | /114.py | 797 | 4.28125 | 4 | # This problem was asked by Facebook.
# Given a string and a set of delimiters, reverse the words in the string while
# maintaining the relative order of the delimiters. For example, given "hello/world:here", return "here/world:hello"
# Follow-up: Does your solution work for the following cases: "hello/world:here/",
# "hello//world:here"
####
import re
def reverse_words(arr, delim):
re_delimiter = '|'.join(delim)
words = re.split(re_delimiter, arr)
seq_delims = re.findall(re_delimiter, arr)
words = words[::-1]
final_string = words[0]
for word, delim in zip(words[1:], seq_delims):
final_string += delim + word
return final_string
####
print(reverse_words("hello//world:here", ['/',':']))
print(reverse_words("hello/world:here/", ['/',':']))
| true |
ab75f215a72bb0e8ccd9f2cca4b8247d4b59afbd | whoophee/DCP | /148.py | 1,240 | 4.15625 | 4 | # This problem was asked by Apple.
# Gray code is a binary code where each successive value differ in only one bit,
# as well as when wrapping around. Gray code is common in hardware so that we don't
# see temporary spurious values during transitions.
# Given a number of bits n, generate a possible gray code for it.
# For example, for n = 2, one gray code would be [00, 01, 11, 10].
####
# The idea behind generating this sequence is pretty simple.
# 1. Generate this sequence for n-1 bits.
# 2. Add a '0' to the end of each element of the n-1 bit gray code
# 3. Add a '1' to the end of each element of a reversed n-1 bit gray code
# 4. Concatenate the two arrays
# Here, since the leading bit changes at the middlemost indices of the generated
# array, and the rest consists of the reverse, there is perfect continuity between
# whatever pattern was generated by the n-1 bit gray code.
# When this is stopped at n=1, a perfect recursive subproblem is created.
# Caching this would make it DPish and result in lesser time for successive calls.
def gray_code(n):
if n == 1:
return ['0', '1']
tmp = gray_code(n-1)
return ['0'+x for x in tmp] + ['1'+x for x in reversed(tmp)]
####
print(gray_code(2))
print(gray_code(3))
| true |
075c3b4bb296e29022791cc11d15b867ab2f30b7 | RishabhJain-dev/cybersecuritybase-project | /application/model.py | 2,581 | 4.125 | 4 | """Initializes sqlite database and creates a table"""
import sqlite3
from application import db
connection = sqlite3.connect('application/info.db', check_same_thread=False)
cursor = connection.cursor()
class User(db.Model):
__tablename__ = 'passwords'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), index=False, unique=True, nullable=False)
password = db.Column(db.String(50), index=False, unique=False, nullable=False) # If passwords are hashed, low
# password limit like (50) doesn't make sense, should be high
# Passwords are also in plaintext which is a big no-no
def __repr__(self):
return f'<User {self.username}'
class Comments(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
comment = db.Column(db.Text, unique=False, nullable=False)
def user_phonenumber_query(search_string):
# The SQL injection happens in this sql query, try --> jaime" or "1" ="1
cursor.execute(f'SELECT first_name, last_name, phone_number FROM Users WHERE first_name="{search_string}"')
# The fix for the above query is
# cursor.execute('SELECT first_name, last_name, phone_number FROM Users WHERE first_name=:firstname',
# {'firstname': search_string})
rows = cursor.fetchall()
return rows
def db_init():
cursor.execute('DROP TABLE IF EXISTS Users')
cursor.execute('CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT,'
' first_name VARCHAR(20), last_name VARCHAR(20), phone_number TEXT, current_address TEXT)')
cursor.execute(
'INSERT INTO Users ("first_name", "last_name", "phone_number", "current_address") VALUES (?, ?, ?, ?)',
('Jaime', 'Lannister', '+35864682', 'Riverlands'))
cursor.execute(
'INSERT INTO Users ("first_name", "last_name", "phone_number", "current_address") VALUES (?, ?, ?, ?)',
('Tyrion', 'Lannister', '+35858424', 'Meereen'))
cursor.execute(
'INSERT INTO Users ("first_name", "last_name", "phone_number", "current_address") VALUES (?, ?, ?, ?)',
('Doran', 'Martell', '+35862334', 'Sunspear'))
cursor.execute(
'INSERT INTO Users ("first_name", "last_name", "phone_number", "current_address") VALUES (?, ?, ?, ?)',
('Petyr', 'Baelish', '+35896393', 'Vale of Arryn'))
cursor.execute(
'INSERT INTO Users ("first_name", "last_name", "phone_number", "current_address") VALUES (?, ?, ?, ?)',
('Shadrich', 'The Mad Mouse', '+35809057', 'Vale of Arryn'))
connection.commit()
| true |
5f3498c0e864138e640e7b6f55fcb937858c6c4a | Youngjun-Kim-02/ICS3U-Unit5-04-python | /cylinder_volume.py | 713 | 4.3125 | 4 | #!/usr/bin/env python3
# created by Youngjun Kim
# created on May 2021
# This program uses user defined functions
import math
def calculate_volume(radius, height):
# this function calculates volume of a cylinder
# process
volume = math.pi * radius * radius * height
return volume
def main():
# this function gets radius and height
# input
radius_value = int(input("Enter the radius of a cylinder: "))
height_value = int(input("Enter the height of a cylinder: "))
print("")
# call functions
calculated_volume = calculate_volume(radius_value, height_value)
print("The volume is {0} cm³".format(calculated_volume))
if __name__ == "__main__":
main()
| true |
ae43855250ed2ed7b5fa96ead5119f4156c08961 | dzungdvd/Techkids | /Session 5/ex4_draw_star_Hiep.py | 572 | 4.53125 | 5 | from turtle import *
speed(-1)
def draw_star(x, y, length):
penup()
setpos(x, y)
pendown()
for i in range(5):
forward(length)
right(144)
print("random.randint(a, b) is a function that returns a random integer between a & b (a <= x <= b).")
print("In this case it is used to generate a random location and length of the next star")
speed(0)
color('blue')
for i in range(100):
import random
x = random.randint(-300, 300)
y = random.randint(-300, 300)
length = random.randint(3, 10)
draw_star(x, y, length)
input()
| true |
78782a640da4badfc53bfc517dcfb7ba14cc61a3 | dzungdvd/Techkids | /Session 5/ex1_draw_square.py | 457 | 4.25 | 4 | ##Write a Python function that draws a square, named draw_square,
##takes 2 input parameters: length and color, where length is
##the length of its side and color is the color of its bound (line color)
from turtle import *
speed(-1)
def draw_square(length, color):
pencolor(color)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
draw_square(100, "red")
input()
| true |
7f3f70d4b693bed3288e755e182abcc5f76a22df | matuse/PythonKnights | /ch5/Exercise_5.3.2.py | 839 | 4.375 | 4 | def check_fermat(a, b, c, n):
if a%1 == 0 and b%1 == 0 and c%1 == 0:
if a >= 0 and b >= 0 and c >= 0:
if n > 2:
# Check Fermat
if a ** n + b ** n == c ** n:
print "Holy smokes, Fermat was wrong!"
else:
print "No, that doesn't work."
else:
print "n has to be greater than 2"
else:
print "a, b, and c have to be positive"
else:
print "a, b, and c have to integers"
print 'Please input a, b, c, and n so we can check Fermat.'
a = int(raw_input('a:\n'))
b = int(raw_input('b:\n'))
c = int(raw_input('c:\n'))
n = int(raw_input('n:\n'))
print 'Checking ' + str(a) + '^' + str(n) + " + " + str(b) + '^' + str(n) + " = " + str(c) + '^' + str(n)
check_fermat(a, b, c, n)
| false |
804e64294d2608110a25a535018626a4773a760e | gurkandyilmaz/courses-and-tutorials | /python_programming/ObjectOriented/chapter_5/Decorators.py | 1,121 | 4.5 | 4 | """Demonstraing the use of property method and decorators. The two classes
work the same. The first uses property, the second uses decorators as another
way of defining properties."""
class Colors:
def __init__(self, rgb_value, name):
self.rgb_value = rgb_value
self._name = name
def _set_name(self, name):
print("_set_name method.")
if not name:
raise ValueError("Invalid Name.")
self._name = name
def _get_name(self):
print("_get_name method.")
return self._name
name = property(_get_name, _set_name)
class Colours:
def __init__(self, rgb_value, name):
self.rgb_value = rgb_value
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
if __name__ == "__main__":
colors = Colors(rgb_value = 255, name = "red")
print(colors.name)
colors.name = "Blue"
print(colors.name)
colours = Colours(rgb_value = 255, name = "red")
print(colours.name)
colours.name = "Blue"
print(colours.name)
| true |
32093faf93ec3b108edb166588535a61b70e1ecf | Plextora/Username-Input | /main.py | 236 | 4.25 | 4 | username = input("Type a username: ")
if len(username) < 3:
print("Name must be at least 3 characters.")
elif len(username) > 10:
print("Name must be a maximum of 10 characters.")
else:
print("That username looks snazzy!") | true |
cd4bcb663cbfa4afb54906a2a6b2fba5947857eb | Aloha137/Homework | /bot/wordcount.py | 702 | 4.4375 | 4 | # Добавить команду /wordcount котрая считает слова в присланной фразе.
# Например на запрос /wordcount "Привет как дела" бот должен посчитать
# количество слов в кавычках и ответить: 3 слова
def wordcount(args):
if args:
# args = [word for word in args.split(' ') if word]
print(args)
return "Фраза состоит из " + str(len(args)) + " слов/а"
else:
return "Введи что-нибудь по-братски,а ?!"
if __name__ == '__main__':
print(wordcount(input("Введите фразу: ")))
| false |
740f01b8ac9841c1547ffab75e6be6e7b378806a | XenXenOfficial/Playing-With-Python | /Time.py | 1,856 | 4.25 | 4 | import time #Imports the Time module.
TimeStart = int(time.strftime("%M")) #Grabs the systems current time
print(TimeStart) #prints it
while True:
TimeSavedVal = TimeStart #Saves the previous time Value
TimeCompareVal = int(time.strftime("%M")) #Constantly updates the value with the system time
if TimeCompareVal == TimeSavedVal + 1: #Checks if the constantly updated value has went up by 1
print(TimeCompareVal) #Prints the updated value
break #Gets out of the loop
'''
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.
'''
| true |
b7f7c128ff0b09b94189cac6ed313aa5cd9a88b4 | miqdad279/Belajar-Phython | /method.py | 637 | 4.1875 | 4 | # Belajar Membuat Method / Function
# => tempat kita menyimpan kode blok
# dimana, kode blok ini akan dieksekusi ketika kita memanggilnya
# Belum menggunakan method
nama = []
nama.append("Atikah")
print("============")
for data in nama:
print(data)
nama.append("Amel")
print("============")
for data in nama:
print(data)
nama.append("Farah")
print("============")
for data in nama:
print(data)
# Menggunakan method
nama = []
def print_nama():
print("============")
for data in nama:
print(data)
nama.append("Atikah")
print_nama()
nama.append("Amel")
print_nama()
nama.append("Farah")
print_nama()
| false |
3fc1855c77175b9bfc1ea27a62bde76f8eddd630 | Adiel30/Windows | /venv/Comprehensions.py | 957 | 4.1875 | 4 | # Will put a list on evrey letter in th word
lst = [x for x in 'word'] # x in 'word' PRINT W O R D # x for x Crete the , fo the list
print(lst)
# Example 2
lst = [x**2 for x in range(0,11)] # # in Range of 0-10 Make A list of evrey number in power of 2
print(lst)
#Example 3
lst = [x for x in range(11) if x % 2 == 0] # In range of 0-10 make a list just for modlue = 0 # כלומר תעשה את הפעולה רק כאשר המשתנה יהיה שווה ל...
print(lst)
# Example 4
lst = [x for x in range(11) if x % 2 != 0]
print(lst)
#Example 5
# Convert Celsius to Fahrenheit
celsius = [0,10,20.1,34.5]
fahrenheit = [((9/5)*temp + 32) for temp in celsius ] # Divid 9/5*temp(varlible) + 32 FOR EACH value in Celsius List
print(fahrenheit)
#Example 6
# Nasted FOR INSIDE FOR
lst = [ x**2 for x in [x**2 for x in range(11)]] #Start For Inside # X in power of 2 in range 0-10 List # once Again X power of 2 for evrey number in the first list
print(lst) | false |
f4e51d97a2eedb2fc51d4d1f15c7dcec3ef54597 | Dinesh1121/repo12 | /palindrome.py | 324 | 4.1875 | 4 | number=int(input("Please Enter any Number: "))
reverse=0
temp=number
while(temp>0):
Reminder=temp % 10
reverse=(reverse*10)+Reminder
temp=temp//10
print("Reverse =%d"%reverse)
if(number==reverse):
print("%d is a Palindrome Number"%number)
else:
print("%d is not a Palindrome Number"%number)
| true |
34310c1484f4cc87650b3ac072c034d69936d338 | n-sarraf/bootcamp | /exercise14.py | 1,187 | 4.3125 | 4 |
def longest_common_substring(str1, str2):
"""To evaluate the longest common substring between two given strings."""
if len(str1) <= len(str2):
shortstr=str1
longstr=str2
else:
longstr=str1
shortstr=str2
short_str = shortstr
# for i, _ in enumerate(shortstr):
# while shortstr not in longstr:
# shortstr = shortstr[:-1]
# else:
# shortstr1 = shortstr
ident_string = ""
for i, _ in enumerate(shortstr):
if short_str in longstr:
shortstr2 = short_str
if len(shortstr2) > len(ident_string):
ident_string = shortstr2
else:
short_str = short_str[i:-1]
ident_string_2 = ""
for i, _ in enumerate(shortstr):
if short_str in longstr:
shortstr2 = short_str
if len(shortstr2) > len(ident_string):
ident_string_2 = shortstr2
else:
short_str = short_str[1:i]
if len(shortstr1) >= len(shortstr2):
return "The longest common string is " + shortstr1
else:
return "The longest common string is " + shortstr2
| false |
f23245dec8504f08c677aab074619bfc6bc801df | astilleman/MI | /07-number_formatter.py | 601 | 4.25 | 4 | """
Write a program that reads an integer between 1000 and 999999 from the user, and prints
it with a comma separating the thousands:
Example:
Please enter an integer between 1000 and 999999: 23456
The formatted number is: 23,456
Hint: use the : operator for strings
"""
# Ask input from user
number = input("Please enter a number between 1000 and 999999: ")
# Calculations
part_after_comma = int(number[len(number)-3: len(number)])
part_before_comma = (int(number) - part_after_comma) / 1000
# Print result
print("The formatted number is: %d,%d" % (part_before_comma, part_after_comma))
| true |
311d8fc2d1ab1465e383bc721a9339cf2f4850e2 | astilleman/MI | /04-seconds_converter.py | 1,012 | 4.15625 | 4 | """
Write a program that reads a number of seconds and then converts this to the number of days, hours,
minutes and seconds and prints this to the user. Notice that this exercise can be solved using if-else-
statements, however, try not to use these statements to solve this exercise.
Example:
Time in seconds: 86491
1 days, 0 hours, 1 minutes, 31 seconds
Hint: you will need the integer division (//) and modulo operator (%)
"""
# Ask input from user
amount_of_seconds = int(input("Enter an amount of seconds: "))
# Calculation of hours, minutes and seconds
amount_of_days = amount_of_seconds // (3600 * 24)
amount_of_seconds = amount_of_seconds % (3600 * 24)
amount_of_hours = amount_of_seconds // 3600
amount_of_seconds = amount_of_seconds % 3600
amount_of_minutes = amount_of_seconds // 60
amount_of_seconds = amount_of_seconds % 60
# Print result in the correct format
print("%d days, %d hours, %d minutes, %d seconds" %(amount_of_days, amount_of_hours, amount_of_minutes, amount_of_seconds))
| true |
1c5eb4e107ca24d46f60b541406d060e5e413747 | astilleman/MI | /05-cartesian_to_polar-sol.py | 430 | 4.5 | 4 | from math import sqrt, atan, degrees
x_coordinate = float(input("Enter the x-coordinate: "))
y_coordinate = float(input("Enter the y-coordinate: "))
x_squared = x_coordinate ** 2
y_squared = y_coordinate ** 2
radius = sqrt(x_squared + y_squared)
theta_in_radians = atan(y_coordinate / x_coordinate)
theta_in_degrees = degrees(theta_in_radians)
print("The radius is: " + str(radius))
print("Theta is: " + str(theta_in_degrees))
| true |
1b081d8f4e572d743e6206f6636e1c93ce69ad0b | astilleman/MI | /faculteit_met_while.py | 666 | 4.125 | 4 | '''
Ask a user for
a value n (integer)
Write a program, with a while loop, to calculate n!
Write a program, with a for loop, to calculate n!
'''
n = int(input("Geef een waarde waarvan we de faculteit gaan berekenen: "))
originele_n = n
while n < 0:
print("Geen geldige waarde! Voer een positieve waarde in!")
n = int(input("Geef een waarde waarvan dwe de faculteit gaan berekenen: "))
n_off = n
faculteit1 = 1
while n > 0:
faculteit1 = faculteit1 * n
n = n - 1
faculteit2 = 1
for i in range(1, n_off+1):
faculteit2 *= i
print("De faculteit van", originele_n, "is", faculteit1)
print("De faculteit van", originele_n, "is", faculteit2)
| false |
f3c9277c1ddb9aee3e02f6f2bfb203e521c31cde | astilleman/MI | /6_palindroom.sol.py | 1,119 | 4.28125 | 4 | """
Een palindroom is een string die hetzelfde leest van links naar
rechts, als omgekeerd. Enkele voorbeelden van palindromen zijn:
- kayak
- racecar
- was it a cat I saw
Schrijf een recursieve functie die een string vraagt aan de gebruiker en
nakijkt of deze string al dan niet een palindroom is. Indien de
ingevoerde string een palindroom is, moet de functie True teruggeven,
anders geeft de functie False terug.
Je mag ervan uitgaan dat de gegeven string geen spaties bevat.
Let op: Zorg ervoor dat je functie niet hoofdlettergevoelig is.
"""
def is_palindroom(string):
if not string:
return True
elif len(string) == 1:
return True
else:
if string[0].lower() == string[-1].lower():
return is_palindroom(string[1:-1])
else:
return False
# TESTS
assert is_palindroom("")
assert is_palindroom("a")
assert is_palindroom("aa")
assert not is_palindroom("ab")
assert is_palindroom("aba")
assert not is_palindroom("aab")
assert is_palindroom("kayak")
assert not is_palindroom("racehorse")
assert is_palindroom("racecar")
assert is_palindroom("wasitacatIsaw")
assert is_palindroom(123) | false |
0a99ffd869b81c2280ab02b1599b2220b25640d2 | clarkkarenl/codingdojo_python_track | /fun-with-functions.py | 1,659 | 4.4375 | 4 | # Assignment: Fun with Functions
# Karen Clark
# 2018-06-03
# Assignment: Fun with Functions
# Create a series of functions based on the below descriptions.
# Odd/Even:
# Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
def odd_even():
for x in range(1, 2001):
if x % 2 != 0:
print "Number is " + str(x) + ". This is an odd number."
else:
print "Number is " + str(x) + ". This is an even number."
# Multiply:
# Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
# The function should multiply each value in the list by the second argument
def multiply(list_in, multiplier):
new_list = list()
for i in list_in:
if isinstance(i, int) or isinstance(i, float) or isinstance(i, long) or isinstance(i, complex):
new_list.append(i * multiplier)
else:
print "List must contain only numbers"
exit()
return new_list
# Hacker Challenge:
# Write a function that takes the multiply function call as an argument. Your new function should return the multiplied list as a two-dimensional list. Each internal list should contain the 1's times the number in the original list.
def layered_multiples(fun):
outer_list = []
for i in fun:
inner_list = []
n = 0
while n < i:
inner_list.append(1)
n += 1
outer_list.append(inner_list)
return outer_list
| true |
12f5365bd9e5f4068b1df62ce0d2a3e0f5bda07b | clarkkarenl/codingdojo_python_track | /foo-and-bar.py | 1,717 | 4.21875 | 4 | # Assignment: Foo and Bar (optional)
# Karen Clark
# 2018-06-04
# Optional Assignment: Foo and Bar
# Write a program that prints all the prime numbers and all the perfect
# squares for all numbers between 100 and 100000.
# For all numbers between 100 and 100000 test that number for whether it is
# prime or a perfect square. If it is a prime number, print "Foo". If it is
# a perfect square, print "Bar". If it is neither, print "FooBar". Do not use
# the python math library for this exercise. For example, if the number you
# are evaluating is 25, you will have to figure out if it is a perfect
# square. It is, so print "Bar".
def foo_and_bar():
def is_prime(n):
count = 0
for i in range(2, n):
if n % i == 0:
count += 1
if count > 0:
return False
else:
return True
def integer_sqrt(n):
# Calculation uses Babylonian Method to test for perfect square
# Adapted from a blog post about Babylonian Method from: http://www.koderdojo.com/blog/python-program-square-roots-babylonian-method
# The calling function is pre-populated with non-negative values between 100 and 99999, so no need to test
guess = 5
epsilon = 0.001
while True:
difference = guess**2 - n
if abs(difference) <= epsilon:
break
guess = (guess + n / guess) / 2.0
return round(guess,4)
# Print the appropriate messages based on result
for i in range(100,100000):
if is_prime(i):
print "Foo"
elif (i / integer_sqrt(i)) == integer_sqrt(i):
print "Bar"
else:
print "FooBar" | true |
0e73979ff88b42408f63786b4555400680a264de | Dmitriy-Skvortsov/My-Training-Python | /03_If.py | 955 | 4.21875 | 4 | # 1.Напишите код печати результата сравнения двух целочисленных переменных.
# 2.Напишите код определения делимости числа на 3.
# 3.Создайте две логические переменные. Напишите код, распечатывающий, сколько переменных имеют значение False: обе, одна или ни одной.
g = 33
s = 24
if g == s:
print("Переменные равны")
elif g < s:
print("g меньше s")
elif g > s:
print("g больше s")
else:
print("Не должно быть напечатано")
print("")
if g%3 == 0:
print("g не чётное число")
else:
print("g чётное число")
print("")
g = False
s = False
if g and s:
print("g и s")
elif g or s:
print("Один из g или s")
else:
print("Ничего")
| false |
2ca114eee3e4eaf3be766c0c2ce0810a1c04876d | kiraheta/interview-technical-questions | /firecode/findmissingnumber.py | 726 | 4.1875 | 4 | #!/usr/bin/python
"""
Given an list containing 9 numbers ranging from 1 to 10, write a function to
find the missing number. Assume you have 9 numbers between 1 to 10 and only
one number is missing.
Example:
input_list: [1, 2, 4, 5, 6, 7, 8, 9, 10]
find_missing_number(input_list) => 3
"""
def find_missing_number(list_numbers):
for num in list_numbers:
if num + 1 != list_numbers[num]:
return num + 1
def find_missing_number(list_numbers):
return [i for i in range(1, 10) if i not in list_numbers][0]
def find_missing_number(list_numbers):
return sum(range(11)) - sum(list_numbers)
if __name__ == '__main__':
lst = [1, 2, 4, 5, 6, 7, 8, 9, 10]
print(find_missing_number(lst))
| true |
81546542e2eb84cd341b5527cee16d7bd691ebbc | kiraheta/interview-technical-questions | /firecode/ispalindrome.py | 918 | 4.1875 | 4 | #!/bin/usr/python
"""
A palindrome is a string or sequence of characters that reads the same backward
and forward. For example, "madam" is a palindrome.
Write a function that takes in a string and returns a Boolean -> True if the
input string is a palindrome and False
if it is not. An empty string is considered a palindrome. You also need to
account for the space character. For example, "race car" should return False
as read backward it is "rac ecar".
Examples:
is_palindrome("madam") -> True
is_palindrome("aabb") -> False
is_palindrome("race car") -> False
is_palindrome("") -> True
"""
def is_palindrome(input_string):
reverse = input_string[::-1]
if input_string == reverse:
return True
else:
return False
def is_palindrome(input_string):
return input_string == input_string[::-1]
if __name__ == '__main__':
a_str = "race car"
print(is_palindrome(a_str))
| true |
5dc09cf72695d3d131acaeda0b9179f9c31467fa | seakr1948/CTCI-Exercises | /1.4 Palindrome.py | 1,151 | 4.1875 | 4 | def check_permutation(string):
chartable = {}
# Counts all characters and puts them in a hashtable
print(string)
for index in range(len(string)):
if chartable.get(string[index]) == None:
chartable[string[index]]=1
else:
chartable[string[index]] += 1
# Identifies which strings can be palindromes based on string
# length and char counts
if len(string) % 2 == 0:
for keys in chartable:
if (chartable[keys] % 2) != 0:
print("Is not a Palindrome")
return
print("Is A Palindrome")
else:
odd_counter = 0
for keys in chartable:
if (chartable[keys] % 2) != 0:
odd_counter += 1
if odd_counter > 1:
print("Not a Palindrome")
else:
print("Is a Palindrome")
print("")
stringlist = ["amanaplanacanalpanama","strawwarts", "atoyotasatoyota",
"man", "Chandooorgmakesyouawesome", "dammitimmad", "topspot",
"borroworrob", "godsaveevasdog", "neverafoottoofareven"]
for test in stringlist:
check_permutation(test)
| true |
ca81601e81477be67525faacb6a3c43706c3f41d | gomoslaw/DesignPatterns | /02Fabryka/Students/2017/TyczynskiMichal/factory_wytwarzanie.py | 2,653 | 4.21875 | 4 | from abc import ABC, abstractmethod
class CarsSeller():
def __init__(self):
self.berStore = BerlinCarStore()
self.chicagoStore = ChicagoCarStore()
car = self.berStore.assemblyCar("Audi")
print("Hans bought " + car.getType() + "\n")
car = self.chicagoStore.assemblyCar("Ford")
print("Jack ordered a " + car.getType() + "\n")
class CarStore(ABC):
@abstractmethod
def createCar(self, item):
pass
def assemblyCar(self, type):
self.car = self.createCar(type)
print("--- Assembling a " + self.car.getType() + " car ---")
self.car.assemble()
self.car.paintCar()
self.car.ship()
self.car.sell()
return self.car
class Car(ABC):
def __init__(self):
self.body = ''
self.topSpeed = ''
self.paint = ''
self.price = ''
def assemble(self):
print("Assembling " + self.body)
def paintCar(self):
print ("Painting car.")
def ship(self):
print ("Shipping to destination country")
def sell(self):
print ("Ready for pickup.")
def getType(self):
return self.body
# Chicago
class ChicagoCarStore(CarStore):
def __init__(self):
pass
def createCar(self, item):
if item == "BMW":
return ChicagoEuropeanCar()
elif item == "Ford":
return ChicagoAmericanCar()
else:
return None
class ChicagoEuropeanCar(Car):
def __init__(self):
self.body = 'SEDAN'
self.topSpeed = '300'
self.paint = 'red'
self.price = '300 000'
class ChicagoAmericanCar(Car):
def __init__(self):
self.body = 'PICKUP'
self.topSpeed = '200'
self.paint = 'green'
self.price = '100 000'
def ship(self):
print ("Local Car, no need to ship abroad. using local shipment.")
# Berlin
class BerlinCarStore(CarStore):
def __init__(self):
pass
def createCar(self, item):
if item == "Audi":
return BerlinEuropeanCar()
elif item == "Corvette":
return BerlinAmericanCar()
else:
return None
class BerlinEuropeanCar(Car):
def __init__(self):
self.body = 'SUV'
self.topSpeed = '220'
self.paint = 'yellow'
self.price = '223 000'
def ship(self):
print ("Local Car, no need to ship abroad. using local shipment.")
class BerlinAmericanCar(Car):
def __init__(self):
self.body = 'SEDAN'
self.topSpeed = '200'
self.paint = 'blue'
self.price = '110 000'
cars = CarsSeller() | false |
ee66984d84245f8873ce7ee7fe1d160f63534d42 | lemon89757/homework | /chapter2.3.py | 839 | 4.40625 | 4 | #! /usr/bin/env python #这一行是必须写的,它能够引导程序找到 Python 的解析器,也就是说,不管你这个文件保存在什么地方,这个程序都能执行,而不用制定 Python 的安装路径。(unix系统而言)
#coding:utf-8 #这一行是告诉 Python,本程序采用的编码格式是 utf-8,只有有了上面这句话,后面的程序中才能写汉字,否则就会报错了
print("请输入任意一个整数数字:")
number=int(input())
if number==10:
print("您输入的数字是:%d"%number)
print("you are smart.")
elif number>10:
print("您输入的数字是:%d"%number)
print("this number is more than 10.")
elif number<10:
print("您输如的数字是:%d"%number)
print("this number is less than 10.")
else:
print("are you a human?")
| false |
8d3708d7580d4f274238a620b1223fe89ec97abe | Future-Aperture/Python | /exercícios_python/exercíciosMiguel/Curso_Em_Vídeo/Exercícios_91-115/Mundo_3_Ex_113/leitura.py | 656 | 4.1875 | 4 | def leiaInt():
while True:
#Input
num = input("Digite um número inteiro:\n> ")
try:
return int(num)
except ValueError:
print("\nO valor é possivel usar strings/floats, tente novamente.\n")
except Exception as erro:
print(erro.__class__)
def leiaFloat():
while True:
#Input
num = input("Digite um número real:\n> ")
try:
return float(num)
except ValueError:
print("\nO valor é possivel usar strings, tente novamente.\n")
except Exception as erro:
print(erro.__class__) | false |
0155befa2ef3874dcb49b7bb42010a09d8e25564 | yangmaosheng66/Python01 | /day03/07-字符串的替换.py | 531 | 4.1875 | 4 | # my_str.replace(old_str, new_str, count) 字符串的替换,将my_str 中的old_str 替换成new_str
# old_str: 将要被替换的字符串
# new_str: 替换成的新字符串
# count: 替换的次数,默认全部替换
# 返回值:得到一个新的字符串,不会改变原来的字符串
my_str = 'hello world python and hi python'
my_str1 = my_str.replace('python', 'java')
print('my_str :', my_str)
print('my_str1:', my_str1)
my_str2 = my_str.replace('python', 'java', 1) # 替换一次
print('my_str2:', my_str2)
| false |
801f28d72df94f5a36c12760b98d0db7787d64e8 | code-drops/coding-ninjas | /Basics of data science and machine learning/4. Strings , List and 2D list/2. print all substrings.py | 322 | 4.25 | 4 | '''Given a String S of length n, print all its substrings.
Substring of a String S is a part of S (of any length from 1 to n), which contains all consecutive characters from S.'''
string = input()
length = len(string)
for i in range(1,length+1):
for k in range(0, len(string)-i+1):
print(string[k:k+i]) | true |
44d43426cdb5496edecd6735c8a8f34ac8ea000c | code-drops/coding-ninjas | /Basics of data science and machine learning/3. More on loops/4. Decimal to binary.py | 354 | 4.375 | 4 | '''
Given a decimal number (integer N), convert it into binary and print.
The binary number should be in the form of an integer.
'''
n = int(input())
if n==0:
print(0)
elif n==1:
print(1)
else:
binary =''
while n!=1:
binary = binary + str(n%2)
n = n//2
binary = binary+str(1)
print(binary[-1::-1]) | true |
f18f4366c090a4c71c619b6157e8c1f7a061d623 | pleimi/Cuenta_regresiva_otros_scripts | /strings.py | 1,646 | 4.40625 | 4 | myStr = "pleimi es mi 23 8 9nicknaesme"
print("My name is " + myStr)
print(f"My name is {myStr}")# la f significa que hay una variable en el texto
print("My name is {0}".format(myStr))
print (dir(myStr)) # con dir vemos los métodos
print(myStr.upper()) # upper me cambia la palabra a mayuscula print(myStr.title()) # sirve para volver mi string en titulo
print(myStr.lower()) # todo en minuscula print(myStr.capitalize())# coloca la primera letra en minúscula
print(myStr.swapcase()) # cambia las mayusculas a minusculas
# print(myStr.strip()) # me muestra el string original
# print(myStr.startswith('a')) # me devuelve un boolean False
# print(myStr.endswith("e")) # termina mi string en la letra e? True print(myStr.split(' ')) # separe a partir de un espacio y da una list[]
# print(myStr.split("i")) #separa a partir de la letra i
# print(myStr.split("2")) # separa a partir del 2
# print(myStr.count("es"))# cuenta las veces en las que está "es"
# print(myStr.replace("23","22"))# reemplaza el 23 por el 22
# print(len(myStr))# me da la longitud de la todo el string 29 caracteres
# print(myStr.find("8")) # me da el indice o posición del caracter "8" ej.16
# print(myStr.index("8"))# como el anterior me da el indice ej. 16
# print(myStr[0])# que valor está en la posición 0? la p
# print(myStr[1])# que valor está en la posición 0? la l
# print(myStr[2])# que valor está en la posición 0? la e
# print(myStr[3])# que valor está en la posición 0? la i
# print(myStr[-2])# quien es el penúltimo caracter? la m
# print(myStr.isnumeric())# me devuelve un boolean
# print(myStr.isalpha())# me devuelve un boolean ej. False
| false |
860c1f4209d8877e492ff84d5f70c9446eb9c74f | daniellatali/Python-Practice | /3ex22.py | 1,512 | 4.59375 | 5 | # <-- Symbol used for making comments and doesn't show in terminal
# print() <-- print means to display what text or values in the terminal
# + add
# - subtract
# / divide
# * multiply
# % modulus (rounds to nearest integer w/o remainder)
# < less than
# > greater than
# = equal to (also can assign variables)
# <= less than or equal to
# >= greater than or equal to
# f before string "" <-- Tells python that string needs to be formatted and to put the variables in there
# print(variable.format(1, 2, 3, 4)) <-- the format command
# variable = input() <-- prompts user in terminal to input a specific variable.
# \t <-- makes indentation on text while displaying in the terminal
# \n <-- makes new line for text while displaying in the terminal
# from ... import... <-- uses or applies features in the command
# argv <-- argument variable: holds arguments to pass through your python script
# print(txt.read()) <-- Displays a text file when inputted
# open() <-- opens any file or document you want in the terminal
# open( ,'w') opens file in write mode
# open( ,'r') opens file in read mode
# open( , 'a') opens file in append mode
# variable.truncate <-- truncating the file means to shorten it
# variable.close <-- closes the file
# len() <-- gets length of string that you pass to it and returns that as a number
# def variable: <-- a way to define functions
# f.seek(any number) <-- seek means it opens a file to whatever point in bytes to read or write at that point.
| true |
b7c92bd54f4c37f5f36505f4bcce35fb90eaf5bd | Griffinw15/cs-module-project-recursive-sorting | /src/inclass/quicksort.py | 1,110 | 4.375 | 4 | #the partition function handles the work of
# selecting a pivot element and partitioning
# the data in the array around that pivot
# returns the left partition, the pivot, and the right partition
def partition(arr):
# pick the first element as the pivot element
pivot = arr[0]
left = []
right = []
# iterate through the rest of the array, putting each
# element in the appropriate bucket
for x in arr[1:]:
if x <= pivot:
left.append(x)
else:
right.append(x)
#returns wrapped in tuple
return left, pivot, right
##alternate partition syntax
#for num in arr:
# if num < pivot:
# left.append(num)
# if num > pivot:
# right.append(num)
def quicksort(arr):
# base case
# if the length of the array is less than or equal to 1
if len(arr) <= 1:
return arr
# how do we get closer to our base case?
left, pivot, right = partition(arr)
return quicksort(left) + [pivot] + quicksort(right)
arr = [13, 27, 5, 18, 3, 19, 22, 16]
arr = quicksort(arr)
print(arr) | true |
8ac710dcce81dbef775cb0a12226249329979a44 | Muneer320/Basic-Fun-Games-Python | /Coin toss game.py | 271 | 4.28125 | 4 | import random
coin = ["heads", "tails"]
while True:
toss = random.choice(coin)
selection = input("Heads or Tails: ")
if selection == toss:
print('You win! coin landed on ' + toss)
else:
print('You lost! coin landed on ' + toss) | true |
f078d49f80109222b41bbafb14789fe9850b2e48 | berlinelucien/100daysofcode-python-BLproject | /Day 1-Band Name Generator.py | 641 | 4.46875 | 4 |
#1. Create a greeting for your program.
print("Welcome to the Band Name Gnerator")
#2. Ask the user for the city that they grew up in.
city = input("What city did you grow up in?\n") ##we create input with the variable name so it wont get lost in the program, we can recall it later if we need it
#3. Ask the user for the name of a pet.
pet = input("Favorite name of a pet?\n")
#4. Combine the name of their city and pet and show them their band name.
print("Your awesome band name is " + city + " " + pet)
#5. Make sure the input cursor shows on a new line, see the example at:
# https://band-name-generator-end.appbrewery.repl.run/
| true |
3cbcdbecfaccd947b8a45d5495094bea8c994b55 | elvis1234512/Python-1 | /ZELLERS.py | 1,108 | 4.3125 | 4 | # zeller_congruence.py
# 10/28/17
# Zeller's congruence is an algorithm
# developed by Christian Zeller to
# calculate the day of the week.
name= input("Enter your name: ")
year = int(input('Enter year(e.g. 2015) : '))
month = int(input('Enter month(1-12) : '))
day = int(input('Enter day of the month(1-31) : '))
# If January or February is entered you must add
# 12 to the month and minus 1 from the year. This
# puts you in month 13 or 14 of previous year.
if month == 1:
month = month + 12
year = year - 1
elif month == 2:
month = month + 12
year = year - 1
print("{}was born on {} which is".format(name,day))
century = (year // 100)
century_year = (year % 100)
# Day of the week formula
dotw = (day + ((26 * (month + 1)) // (10)) + century_year + ((century_year) // \
(4)) + ((century) // (4)) + (5 * century)) % 7
if dotw == 0:
print('Saturday')
elif dotw == 1:
print('Sunday')
elif dotw == 2:
print('Monday')
elif dotw == 3:
print('Tuesday')
elif dotw == 4:
print('Wednesday')
elif dotw == 5:
print('Thursday')
elif dotw == 6:
print('Friday')
| false |
8a430137b4ee334bf73d9afa398759d0b2348dca | Idianale/Programming-Assignment-1-User-Input | /exercise1.py | 1,703 | 4.375 | 4 | # Your name here
# A python program in which you create more experiences with input
print("I make horoscope")
# TASK 1
# variables that hold horoscopes
# create a a series of variables with the names of the different astrology signs
# and set the value to be a string with anyhoroscope
# [Tip] all the signs are listed further down in the program
# Examples of variables that hold string
#
libra = " Extremely good luck but only if you switch shoes"
scorpio = " Don't roll any gacha"
sagittarius = " golden golden golden golden time "
capricorn = "https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley"
aquarius = " Your lucky animals are hippogriffs and jellyfish today"
pisces = " Avoid wizards "
# TASK 2
# prompt the user for there sign
# Uncomment the next line of code and add intro() function to make
# Make sure that input() is given a paremeter asking the user for information
# userSign =
# process userSign to make all variables lowercase
userSign = userSign.lower()
print(userSign)
# switch to match user with horoscope and output it to the screen
if userSign == "aries":
print(aries)
elif userSign == "taurus":
print(taurus)
elif userSign == "gemini":
print(gemini)
elif userSign == "cancer":
print(cancer)
elif userSign == "leo":
print(leo)
elif userSign == "virgo":
print(virgo)
elif userSign == "libra":
print(libra)
elif userSign == "scorpio":
print(scorpio)
elif userSign == "sagittarius":
print(sagittarius)
elif userSign == "capricorn":
print(capricorn)
elif userSign == "aquarius":
print(aquarius)
elif userSign == "pisces":
print(pisces)
else:
print("Thats not a sign you probably have bad luck")
| true |
0af92372639817311950221cd43f479e9e936692 | casprice/leetcode | /binary-search/search-in-rotated-sorted-array.py | 1,363 | 4.125 | 4 | """
Given an integer array nums sorted in ascending order, and an integer target.
Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You should search for target in nums and if you found return its index, otherwise return -1.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
"""
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
return mid
# left through mid is sorted
if nums[mid] >= nums[left]:
if target > nums[mid] or target < nums[left]:
left = mid + 1
else:
right = mid - 1
# mid through right is sorted
else:
if target < nums[mid] or target > nums[right]:
right = mid - 1
else:
left = mid + 1
return -1 | true |
d1f15e36b4f30dcb3d326d69de758f21147af51e | jnguyen0597/EARTH119 | /Earth119/Projects/Week1/Earth119/in class problem 1.2.py | 489 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
while loop, find max height
"""
import numpy as np
import matplotlib.pyplot as plt
v0 = 5 # m/s
g = 9.81 # m / s^2
n = 2000 # time steps
# time
a_t = np.linspace( 0, 1, n)
# computation
y = v0*a_t - 0.5*g*a_t**2
# find the max height in while loop
i = 1
# y[-1] last entry in array
while y[i] > y[i-1]:
largest_height = y[i]
i += 1
print ("max. height: %10.2f"%( largest_height))
plt.plot(a_t, y)
plt.show() | false |
16f2d9987a27651eca2159c52b55c218aaf2e12d | forksbot/byceps | /byceps/util/checkdigit.py | 1,833 | 4.1875 | 4 | """
byceps.util.checkdigit
~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import math
from string import ascii_uppercase, digits
from typing import Iterator
VALID_CHARS = frozenset(ascii_uppercase + digits)
def calculate_check_digit(chars: str) -> int:
"""Calculate the check digit for the given value, using a modified
Luhn algorithm to support not only digits in the value but also
letters.
Based on https://wiki.openmrs.org/display/docs/Check+Digit+Algorithm
"""
chars = chars.strip().upper()
total_weight = calculate_total_weight(chars)
# The check digit is the amount needed to reach the next number
# that is divisible by ten.
return (10 - (total_weight % 10)) % 10
def calculate_total_weight(chars: str) -> int:
total_weight = sum(calculate_weights(chars))
# Avoid a total weight less than 10 (this could happen if
# characters below `0` are allowed).
return int(math.fabs(total_weight)) + 10
def calculate_weights(chars: str) -> Iterator[int]:
# Loop through characters from right to left.
for position, char in enumerate(reversed(chars)):
yield calculate_weight(position, char)
def calculate_weight(position: int, char: str) -> int:
"""Calculate the current digit's contribution to the total weight."""
if char not in VALID_CHARS:
raise ValueError(f"Invalid character '{char}'.")
digit = ord(char) - 48
if is_even(position):
# This is the same as multiplying by 2 and summing up digits
# for values 0 to 9. This allows to gracefully calculate the
# weight for a non-numeric "digit" as well.
return (2 * digit) - int(digit / 5) * 9
else:
return digit
def is_even(n: int) -> bool:
return n % 2 == 0
| true |
025bfce62f5dcfbb3aa80f402b2ce4f392afe0c3 | SRSJA18/assignment-1-Quirkyturtle007 | /Problem4/operators.py | 1,143 | 4.25 | 4 | """Assignment 1: Problem 4: Operators"""
import math
'''
PART 1
Understanding opearators
'''
# TODO 1. Print the result of 5 plus 2
print(5+2)
# TODO 2. Print the result of 5 minus 2
print(5-2)
# TODO 3. Print the result of 5 times 2
print(5*2)
# TODO 4. Print the result of 5 divided by 2
print(5/2)
# TODO 5. Print the result of floor division or truncation division 5 // 2
print(5//2)
# TODO 6. Print the remainder of 5 / 2 using the modulo operator (%)
print(5%2)
# TODO 7. Print the result of 5 raised to the power of 2
print(5**2)
# TODO 8. Print the square root of 25
print(math.sqrt(25))
'''
PART 2
Transcribe the equations from part2.pdf preserving the order of operations with parenthesis as needed. Save
each as a variable and print the variable.
'''
# TODO 9. Equation 1
print(3*5/(2+3))
# TODO 10. Equation 2
print(math.sqrt(7+9)*2)
# TODO 11. Equation 3
print((4-7)**3)
# TODO 12. Equation 4
print((-19+100)**1/4)
# TODO 13. Equation 5
print(6%4)
'''
PART 3
Write two equations with the same operands and operators but that evaluate to different values. Store each in a
separate variable, then print the variables.
'''
| true |
accb2508bbd2183e5db4c4ae86cd92e81c85d9b6 | jeanmizero/SWDV-610 | /WEEK-5/selection_sort.py | 698 | 4.40625 | 4 | def selection_sort(list_value):
for i in range(0, len(list_value) - 1):
# Find the minimum value from list by using linear search
minimum_value = i
# Find the new smallest value
for j in range(i + 1, len(list_value)):
if list_value[j] < minimum_value: # use ascending order
minimum_value = j
# Swap the minimum value with the left-most value and do not swap the value with itself
if minimum_value != i:
list_value[i], list_value[minimum_value] = list_value[minimum_value], list_value[i]
list_value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
selection_sort(list_value)
print("Selection sorted list:", list_value)
| true |
e4eddbdbc8550f812fa55f49667ef795ad7812e5 | savannahjune/wbpractice | /trees/binarytree.py | 1,200 | 4.1875 | 4 | # class BinaryTree(object):
# def __init__(self,root):
class BinaryTreeNode(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
def set_parent(parent):
self.parent = parent
def get_left(self):
return self.left
def set_left(self, node):
if self.get_left(self) == None:
# if there is nothing to the left place the node there
self.left = node
node.parent = self
return
else:
# if there is something to the left, move your pointer to that node on the left
# and recursively check if there is anything to the left of that
return (self.left).set_left(node)
def get_right(self):
return self.right
def set_right(self, node):
#self is parent!
if self.get_right(self) == None:
self.right = node
node.parent = self
return
else:
return (self.right).set_right(node)
def get_value(self):
return self.value
def set_value(self, number):
if self.get_value(self) == None:
self.value = number
def breadth_first_traversal(root):
def test_tree():
root = BinaryTreeNode(1)
left = BinaryTreeNode(2)
right = BinaryTreeNode(3)
root.set_left(left)
root.set_right(right)
| true |
24fed157a04db7aaf4882783ec67b6e2c5e1a01c | salahuddinjony/Python- | /practice of python/use of elif.py | 314 | 4.25 | 4 | marks=int(input("enter your marks:"))
if marks>=80:
print("your grade is A+")
elif marks>=70:
print("your grade is A")
elif marks>=60:
print("your grade is A-")
elif marks>=50:
print("your marks is B")
elif marks>=40:
print("your marks is c")
else:
print("your marks is F")
| false |
172337e12ff12532349346056f4c7488b3e536c2 | jagadeeshwithu/Data-Structures-and-Algos-Python | /Arrays/Sudoku2.py | 1,923 | 4.125 | 4 | """
Determine given input of Sudoku Puzzle is valid or not!
For e.g.,
grid = [['.', '.', '.', '.', '2', '.', '.', '9', '.'],
['.', '.', '.', '.', '6', '.', '.', '.', '.'],
['7', '1', '.', '.', '7', '5', '.', '.', '.'],
['.', '7', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '8', '3', '.', '.', '.'],
['.', '.', '8', '.', '.', '7', '.', '6', '.'],
['.', '.', '.', '.', '.', '2', '.', '.', '.'],
['.', '1', '.', '2', '.', '.', '.', '.', '.'],
['.', '2', '.', '.', '3', '.', '.', '.', '.']]
the output should be sudoku2(grid) = False, because there are two '1's in the second column
"""
def sudoku2(grid):
return (is_row_valid(grid) and
is_col_valid(grid) and
is_square_valid(grid))
def is_row_valid(grid):
for row in grid:
if not is_unit_valid(row):
return False
return True
def is_col_valid(grid):
for col in zip(*grid):
if not is_unit_valid(col):
return False
return True
def is_square_valid(grid):
for i in (0, 3, 6):
for j in (0, 3, 6):
square = [grid[x][y] for x in range(i, i+3) for y in range(j, j+3)]
if not is_unit_valid(square):
return False
return True
def is_unit_valid(unit):
unit = [i for i in unit if i != '.']
return len(set(unit)) == len(unit)
if __name__ == "__main__":
grid = [["7",".",".",".","4",".",".",".","."],
[".",".",".","8","6","5",".",".","."],
[".","1",".","2",".",".",".",".","."],
[".",".",".",".",".","9",".",".","."],
[".",".",".",".","5",".","5",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".","2",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."]]
print(sudoku2(grid))
| false |
ee63384b58f3bb4395d2e23a7291909d4710af6d | jagadeeshwithu/Data-Structures-and-Algos-Python | /LinkedListsnBinaryTrees/Merge-two-lists.py | 2,039 | 4.125 | 4 | """
Implement merge function for two sorted lists
Assumptions: Sorted lists are passed as inputs
"""
from LinkedList import LinkedList, Node
class LinkedList1(LinkedList):
def merge_two_lists(self, A, B):
"""
This implementation would take two lists as arguments and does 'Merge' function
"""
mergedlist = dummy = Node(0)
one, two = A.head, B.head
while one and two:
if one.data < two.data:
mergedlist.next_node = one
one = one.next_node
else:
mergedlist.next_node = two
two = two.next_node
mergedlist = mergedlist.next_node
mergedlist.next_node = one or two
return dummy.next_node
def merge_two_lists1(self, A):
"""
Takes the other (sorted) list to be merged with!
:param A: list2 passed as argument to be merged with list1 as calling
:return: returns the merged list
"""
mergedlist = dummy = Node(0)
first, second = self.head, A.head
while first and second:
if first.data < second.data:
mergedlist.next_node = first
first = first.next_node
else:
mergedlist.next_node = second
second = second.next_node
mergedlist = mergedlist.next_node
mergedlist.next_node = first or second
return dummy.next_node
if __name__ == "__main__":
list1 = LinkedList1()
list1.add_beginning(9)
list1.add_beginning(7)
list1.add_beginning(5)
list1.add_beginning(3)
list1.add_beginning(1)
print(list1)
list2 = LinkedList1()
#list2.add_ending(0) : This case need to be handled
list2.add_beginning(6)
list2.add_beginning(4)
list2.add_beginning(2)
list2.add_ending(8)
print(list2)
#print(list2.merge_two_lists(list1, list2))
print(list2.merge_two_lists1(list1))
| true |
1cf677974fb7a0f1d316e01f1759018a9dee01e3 | jagadeeshwithu/Data-Structures-and-Algos-Python | /LinkedListsnBinaryTrees/Tree-namedtuples.py | 1,875 | 4.1875 | 4 | """
Implementation of Binary Tree - using namedtuples
Traversals:
1. Pre Order
2. Post Order
3. In Order
4. Level Order
"""
from collections import namedtuple
from sys import stdout
class Node(namedtuple('Node', 'data, left, right')):
__slots__ = ()
def preorder(self, visitor):
if self is not None:
visitor(self.data)
Node.preorder(self.left, visitor)
Node.preorder(self.right, visitor)
def inorder(self, visitor):
if self is not None:
Node.inorder(self.left, visitor)
visitor(self.data)
Node.inorder(self.right, visitor)
def postorder(self, visitor):
if self is not None:
Node.postorder(self.left, visitor)
Node.postorder(self.right, visitor)
visitor(self.data)
def levelorder(self, visitor, more=None):
if self is not None:
if more is None:
more = []
more += [self.left, self.right]
visitor(self.data)
if more:
Node.levelorder(more[0], visitor, more[1:])
def printwithspace(i):
stdout.write("%i " %i)
tree = Node(1,
Node(2,
Node(4,
Node(7, None, None),
None),
Node(5, None, None)),
Node(3,
Node(6,
Node(8, None, None),
Node(9, None, None)),
None))
if __name__ == "__main__":
stdout.write(' preorder: ')
tree.preorder(printwithspace)
stdout.write("\n inorder: ")
tree.inorder(printwithspace)
stdout.write('\n postorder: ')
tree.postorder(printwithspace)
stdout.write("\n levelorder: ")
tree.levelorder(printwithspace)
| true |
db02ee9dc1aacbc993cdcd1e5cd0f04be0701238 | bibinjose/hackerrank | /week challenge/acid_test.py | 523 | 4.21875 | 4 | #https://www.hackerrank.com/contests/w36/challenges/acid-naming
#!/bin/python3
import sys
def acidNaming(acid_name):
acid_type='not an acid'
if(acid_name.endswith('ic') ):
if (acid_name.startswith('hydro')):
acid_type = 'non-metal acid'
else:
acid_type='polyatomic acid'
return acid_type
if __name__ == "__main__":
n = int(input().strip())
for a0 in range(n):
acid_name = input().strip()
result = acidNaming(acid_name)
print(result)
| false |
0dd56cc7cfac8dc90c18c22633a46a9ce23831d1 | juuhi/Python---DataStructure | /MergeSort.py | 746 | 4.125 | 4 | # Merge Sort : the complexity of the program is O(nlogn), it is more efficient than quick sort and used for
#large data
def mergeSort(A):
merge_sort2(A,0,len(A)-1)
def merge_sort2(A,first,last):
if first<last:
middle = (first+last)/2
merge_sort2(A,first,middle)
merge_sort2(A,middle+1,last)
merge(A,first,middle,last)
def merge(A,first,middle,last):
L=A[first:middle+1]
R=A[middle+1:last+1]
L.append(999999)
R.append(999999)
i=j=0
for k in range(first,last+1):
if L[i]<=R[j]:
A[k] = L[i]
i =i+1
else:
A[k] = R[j]
j=j+1
A = [5, 9, 1, 2, 4, 8, 6, 3, 7]
print(A)
mergeSort(A)
print(A)
B = [3,4,2]
mergeSort(B)
print(B) | true |
d82d0c12469b209afaafd15ad675648d22d45406 | sanshitsharma/pySamples | /hashing/build_itinerary.py | 1,282 | 4.1875 | 4 | #!/usr/bin/python
'''
Given a list of tickets, find itinerary in order using the given list.
Example:
Input:
"Chennai" -> "Banglore"
"Bombay" -> "Delhi"
"Goa" -> "Chennai"
"Delhi" -> "Goa"
Output:
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
It may be assumed that the input list of tickets is not cyclic and there is one ticket from every city except final destination.
'''
def build_itinerary(tickets):
countMap = {}
src_dst = {}
# Build the maps
for ticket in tickets:
# Add the ticket
src_dst[ticket[0]] = ticket[1]
# Add the city count to countMap
try:
countMap[ticket[0]] += 1
except:
countMap[ticket[0]] = 1
try:
countMap[ticket[1]] += 1
except:
countMap[ticket[1]] = 1
# Find the originating city
for k, v in countMap.items():
if v == 1 and k in src_dst.keys():
oCity = k
# Build the itinerary
itinerary = []
while oCity in src_dst.keys():
itinerary.append((oCity, src_dst[oCity]))
oCity = src_dst[oCity]
return itinerary
if __name__ == "__main__":
print build_itinerary([('Chennai', 'Bangalore'), ('Bombay', 'Delhi'), ('Goa', 'Chennai'), ('Delhi', 'Goa')]) | true |
3ee88845a5efce8b62abe9ceb64be59f27e73941 | sanshitsharma/pySamples | /leetcode/bin_tree_right_view.py | 1,928 | 4.15625 | 4 | #!/usr/bin/python
'''
Problem #199
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
Ref: https://leetcode.com/problems/binary-tree-right-side-view/description/
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
evenQ = [root]
oddQ = []
res = []
while evenQ or oddQ:
if evenQ:
res.append(evenQ[-1].val)
while evenQ:
elem = evenQ.pop(0)
if elem.left:
oddQ.append(elem.left)
if elem.right:
oddQ.append(elem.right)
if oddQ:
res.append(oddQ[-1].val)
while oddQ:
elem = oddQ.pop(0)
if elem.left:
evenQ.append(elem.left)
if elem.right:
evenQ.append(elem.right)
return res
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(7)
root.right.right = TreeNode(8)
root.left.right.left = TreeNode(6)
root.right.right.left = TreeNode(9)
root.right.right.right = TreeNode(10)
root.right.right.right.left = TreeNode(11)
res = Solution().rightSideView(root)
print res | true |
df7787ba91135b9dd8dbc2cbe7228b6b75eac3d7 | sanshitsharma/pySamples | /dynamic_prog/longest_increasing_subsequence.py | 1,205 | 4.40625 | 4 | #!/usr/bin/env python
'''
Let us discuss Longest Increasing Subsequence (LIS) problem as an example problem that can be solved using Dynamic Programming.
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that
all elements of the subsequence are sorted in increasing order.
For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}.
longest-increasing-subsequence
More Examples:
Input : arr[] = {3, 10, 2, 1, 20}
Output : Length of LIS = 3
The longest increasing subsequence is 3, 10, 20
Input : arr[] = {3, 2}
Output : Length of LIS = 1
The longest increasing subsequences are {3} and {2}
Input : arr[] = {50, 3, 10, 7, 40, 80}
Output : Length of LIS = 4
The longest increasing subsequence is {3, 7, 40, 80}
Ref: https://www.geeksforgeeks.org/longest-increasing-subsequence/
'''
def lis(a):
lis = [1 for x in a]
for i in range(1, len(a)):
for j in range(i):
if a[j] < a[i] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
return max(lis)
if __name__ == "__main__":
a = [10, 22, 9, 33, 21, 50, 41, 60]
print lis(a) | true |
f228d0b122aa0326347fe6eaa37f1a0a5191f322 | sanshitsharma/pySamples | /strings/pos_same_as_alphabet.py | 787 | 4.21875 | 4 | #!/usr/bin/python
'''
Given a string of lower and uppercase characters, the task is to find that how many characters are at same position as in English alphabets.
Example:
Input: ABcED
Output : 3
First three characters are at same position
as in English alphabets.
Input: geeksforgeeks
Output : 1
Only 'f' is at same position as in English
alphabet
Input : alphabetical
Output : 3
'''
def find_count(string):
count = 0
string = string.lower()
for i in xrange(0, len(string)):
if ord(string[i]) - ord('a') == i:
count = count + 1
return count
if __name__ == "__main__":
print 'ABcED -->', find_count('ABcED')
print 'geeksforgeeks -->', find_count('geeksforgeeks')
print 'alphabetical -->', find_count('alphabetical')
| true |
60d5d9a2fe89d32ee6f9998594cf3657753884ee | sanshitsharma/pySamples | /nitin_interviews/encrypt_strings.py | 1,862 | 4.46875 | 4 | #!/usr/bin/python3
'''
You've devised a simple encryption method for alphabetic strings that shuffles the characters in such a way that the resulting string is hard to quickly read, but is easy to convert back into the original string.
When you encrypt a string S, you start with an initially-empty resulting string R and append characters to it as follows:
Append the middle character of S (if S has even length, then we define the middle character as the left-most of the two central characters)
Append the encrypted version of the substring of S that's to the left of the middle character (if non-empty)
Append the encrypted version of the substring of S that's to the right of the middle character (if non-empty)
For example, to encrypt the string "abc", we first take "b", and then append the encrypted version of "a" (which is just "a") and the encrypted version of "c" (which is just "c") to get "bac".
If we encrypt "abcxcba" we'll get "xbacbca". That is, we take "x" and then append the encrypted version "abc" and then append the encrypted version of "cba".
Input
S contains only lower-case alphabetic characters
1 <= |S| <= 10,000
Output
Return string R, the encrypted version of S.
Example 1
S = "abc"
R = "bac"
Example 2
S = "abcd"
R = "bacd"
Example 3
S = "abcxcba"
R = "xbacbca"
'''
def findEncryptedWord(s):
# Lets use recursion
out = []
_enc(s, 0, len(s)-1, out)
return ''.join(out)
def _enc(s, l, r, out):
if r < l:
return
if l == r:
out.append(s[l])
return
m = int((l+r)/2)
out.append(s[m])
_enc(s, l, m-1, out)
_enc(s, m+1, r, out)
if __name__ == "__main__":
s1 = "abc"
expected_1 = "bac"
output_1 = findEncryptedWord(s1)
print("Test #1:", expected_1 == output_1)
s2 = "abcd"
expected_2 = "bacd"
output_2 = findEncryptedWord(s2)
print("Test #2:", expected_2 == output_2)
| true |
06270feeb220ffa859bdeb7270782b2c5cd17b4f | sanshitsharma/pySamples | /uglyNumbers.py | 665 | 4.3125 | 4 | #!/usr/bin/python
# A number is called ugly if it's only prime factors are 2,3 or 5. Generally 1 is considered an ugly number
import sys
def isUglyNumber(num):
while num%2 == 0:
num = num/2
while num%3 == 0:
num = num/3
while num%5 == 0:
num = num/5
return num == 1
def main():
if len(sys.argv) != 2:
print "invalid input"
sys.exit()
try:
num = int(sys.argv[1])
except ValueError:
print "'" + sys.argv[1] + "' is not a numeric string"
sys.exit()
print "Is '" + sys.argv[1] + "' an ugly number? " + str(isUglyNumber(num))
if __name__ == "__main__":
main()
| false |
19e43b799fe929114ecaccbcd92b2dd3b42934fb | gabistein/warden_introcs | /Lesson_2/2.1_Lecture.py | 279 | 4.1875 | 4 | #Two main casting functions: int(), str()
n=input()
#Type 9 when asked for input.
print(type(n)) # string
cast_n = int(n)
print(type(cast_n)) # integer
# Now i want to use cast_n in a concatenated variable
# Print the line The user inputted <cast_n>, make sure to use the str()
| true |
ce68f281fdfe36d338638b3d0d0bda1575fe24a4 | eugeniocarvalho/CursoEmVideoPython | /Python Exercicios/Mundo 3: Estruturas Compostas/1. Tuplas em Python /ex072.py | 787 | 4.25 | 4 | '''
Crie um prgrama que tenha uma trupla totalmente preenchida com uma contagem por extensão, de zero ate vinte.
Seu programa devera ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenção
'''
numeros = (
'zero', 'um', 'dois', 'trẽs', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',
'cartoze', 'quinze', 'dezessseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
while True:
n = int(input('Digite um numero [0:20]: '))
while n < 0 or n > 20:
n = int(input('Digite um numero [0:20]: '))
print(f'Você digitou o numero {numeros[n]}')
i = input('Quer continuar? S/N').strip().upper()[0]
while i not in 'SN':
i = input('Quer continuar? S/N ').strip().upper()[0]
if i == 'N':
break
| false |
32122fee6e3156fc9b582f415b78ef00fb365559 | matt-r-lee/ticket_checkout_app | /ticket_checkout.py | 1,558 | 4.1875 | 4 | TICKET_PRICE = 10
SERVICE_CHARGE = 2
tickets_remaining = 100
# Function created to calculate customer's ticket price
def calculate_price(number_of_tickets):
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
# Runs as long as there are still tickets available
while tickets_remaining > 0:
print("There are {} tickets remaining".format(tickets_remaining))
name = input("Please provide your name. ")
num_tickets = input("Hi {}! How many tickets would you like to purchase? ".format(name))
try:
num_tickets = int(num_tickets)
if num_tickets > tickets_remaining:
raise ValueError("There are only {} tickets remaining.".format(tickets_remaining))
except ValueError as err:
print("We are having a problem processing your request. {} Please try again.".format(err))
else:
amount_due = calculate_price(num_tickets)
print("Okay, got it. The total amount for your ticket(s) is ${} (There is a service charge of ${}.).".format(amount_due,SERVICE_CHARGE))
confirm = input("Would you like to continue? Y/N? ")
if confirm.lower() == "y":
print("Thank you for your purchase!")
tickets_remaining -= num_tickets
elif confirm.lower() == "n":
print("Okay, if you woud change your mind {} feel free to come back!".format(name))
else:
print("I'm sorry, that is not a valid response. Please try again later. ")
# Once tickets are sold out, alerts system/user
print("Sorry the tickets are all sold out.")
| true |
1d86a2aaacb1a84f17bb096af6aac84699ebfced | samyak1903/Classes-And-Modules-1 | /S2.py | 849 | 4.25 | 4 | '''Q.2- Create a Student class and initialize it with name and roll number. Make methods to :
1. Display - It should display all informations of the student.
2. setAge - It should assign age to student 3. setMarks - It should assign marks to the student.'''
class Student:
def __init__(self,name,rno):
self.name=name
self.rno=rno
def display(self):
''' display the student details'''
print("Name={}, RollNumber={}, Age={}, Marks={}".\
format(self.name,self.rno,self.age,self.marks))
def setAge(self,age):
''' sets the age of student'''
self.age=age
def setMarks(self,marks):
''' sets the marks of student'''
self.marks=marks
s1=Student("Amit",1)
s1.setMarks(90)
s1.setAge(20)
s2=Student("Samyak",2)
s2.setMarks(80)
s2.setAge(21)
s1.display()
s2.display()
| true |
a857d66a09cb242c6140daeb9ddcd751690c7a31 | Aditya-Pundir/VSCode_python_projects | /VS_Code_Folder_2/python_learning_in_1_video_cwh/tuples.py | 343 | 4.34375 | 4 | # Creating a tuple using ()
t = (1, 2, 3, 4, 5)
# Empty tuple
# t1 = ()
# Creating a tuple with only 1 element
# t1 = (1) # This is the wrong way to create a tuple
t1 = (1, ) # This is the correct way to make a tuple
# Printing an element of a tuple
# print(t[0])
# You cannot update the value of a tuple
# t[0] = 7
# print(t[0])
print(t1) | true |
7f75b5c387f2bbcc5eea73f859dd6121d8b9f52d | zahidalidev/Ai-Lab | /assignment_1/Part1/Question2.py | 935 | 4.21875 | 4 | String1 = '''I'm a "Alaric"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
String1 = 'I\'m a "Alaric"'
print("\nEscaping Single Quote: ")
print(String1)
String1 = "I'm a \"Alaric\""
print("\nEscaping Double Quotes: ")
print(String1)
String1 = "C:\\Python\\Alaric\\"
print("\nEscaping Backslashes: ")
print(String1)
String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)
# Out Put
Initial String with use of Triple Quotes:
I'm a "Alaric"
Escaping Single Quote:
I'm a "Alaric"
Escaping Double Quotes:
I'm a "Alaric"
Escaping Backslashes:
C: \Python\Alaric\
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
| true |
b4f3041d05aaa8abb3dfd13c58fadfbfb408b72d | ethanjoyce14/python-standard-library-ethanjoyce14 | /pythonstandardlibrary.py | 1,975 | 4.15625 | 4 | import random
def instructions():
print(r"""
How to play Dice:
- Roll the die.
- Your opponent then rolls their die.
- Whoever has the highest number wins.
- Rinse and repeat.
""")
def intro():
response = input("\nPress ENTER to continue...\n")
if response == "":
play()
else:
print("You typed some text before enter, why on earth would you do" +
" this???\n")
intro()
def play():
response = input("To roll your die, input 'roll'. To quit, input 'quit'." +
" If you need help, input 'help'.\n")
if response == 'roll':
dieroll1 = random.randint(1, 6)
dieroll2 = random.randint(1, 6)
print(f"You rolled a {dieroll1}. Your opponent rolled a {dieroll2}.\n")
if dieroll1 > dieroll2:
print("You win. Congrats.\n")
intro()
elif dieroll1 < dieroll2:
print("Great job buddy. You managed to lose the worlds simplest " +
"game.\n")
intro()
elif dieroll1 == dieroll2:
print("Whoa! You both rolled the same thing.\n")
play()
elif response == 'quit':
response = input("Are you really sure you want to leave? (yes / no)\n")
if response == 'yes':
print("Okay fine.\n")
quit()
elif response == 'no':
print("Great. Glad to see you've got nothing better to do.\n")
else:
print("I didn't understand that, so I'll assume you want to play" +
" some more dice.\n")
play()
elif response == 'help':
instructions()
response = input("Input anything to go back.\n")
if response == '':
play()
else:
play()
else:
print("I didn't understand that.\n")
play()
instructions()
intro()
| true |
7343af25329c0d7897b5afa6688d413e8130c33d | javierpb275/python-basics | /functions-and-methods/built-in_functions_and_methods.py | 769 | 4.375 | 4 | # BUILT-IN FUNCTIONS:
#grabs the value typed in the terminal and store it in the variable asigned:
name = input("what's your name? ")
#print message in the terminal:
print("Hello " + name)
# len(): length
print(len('012345')) # 6
name = 'javier'
print(name[0:len(name)]) # javier
# METHODS:
quote = 'to be or not to be'
# upper(): uppercase
print(quote.upper())
# lower(): lowercase
print(quote.lower())
# capitalize(): capitalize the beginnig of the sentence
print(quote.capitalize())
# find(): it tells the index of the first 'be
print(quote.find('be')) # 3
print(quote.find('m')) # -1
# replace():
print(quote.replace('be', 'me'))
print(quote) # to be or not to be. Strings are immutable. We can overwrite them. We either create them or destroy them
| true |
3eae793b794e72118de1ced7b1799981de6248f2 | biergeliebter/Intro_to_Python | /boolean_variables.py | 576 | 4.125 | 4 | # A student makes honor roll if their average is >=85 and their lowest grade is not below 70
gpa = float(input('What was your Grade Point Average? '))
lowest_grade = input('What was your lowest grade? ')
lowest_grade = float(lowest_grade)
# True and False without quotes are boolean variables within Python
if gpa >= .85 and lowest_grade >= .70:
honor_roll = True
else:
honor_roll = False
# Somewhere later in the code if you need to check if the student is on honor roll, just check the boolean variable set here
if honor_roll:
print('You made honor roll!') | true |
2d2c07d3707be1fa9a02cb3216928d8cb53df6c1 | gravitonGB/python_for_everybody | /Course_2_Python_Data_Structures/ex_07_02/ex_07_02.py | 1,006 | 4.21875 | 4 | # 7.2 Write a program that prompts for a file name, then
# opens that file and reads through the file, looking for
# lines of the form:
# X-DSPAM-Confidence: 0.8475
# Count these lines and extract the floating point values
# from each of the lines and compute the average of those
# values and produce an output as shown below. Do not use
# the sum() function or a variable named sum in your solution.
# You can download the sample data at
# http://www.py4e.com/code3/mbox-short.txt when you are
# testing below enter mbox-short.txt as the file name.
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
total_confidance = 0.0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
confidance = line[19:]
confidance = float(confidance)
total_confidance = confidance + total_confidance
average_confidance = total_confidance / count
print('Average spam confidence:',average_confidance)
| true |
02964f924fe0e4a1602d8fe6a52023530a667e52 | gravitonGB/python_for_everybody | /Course_2_Python_Data_Structures/ex_07_01/ex_07_01.py | 474 | 4.6875 | 5 | # 7.1 Write a program that prompts for a file name, then
# opens that file and reads through the file, and print the
# contents of the file in upper case. Use the file words.txt
# to produce the output below.
# You can download the sample data at
# http://www.py4e.com/code3/words.txt
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
#fh_cha = fh.read()
#fh_upp = fh_cha.upper()
#print(fh_upp)
for w in fh:
print(w.upper().rstrip())
| true |
64df67d45473ca6cac12c2d093f1bcf2bd4a5d20 | omartinez694/CIS-2348 | /2.19.py | 1,579 | 4.28125 | 4 | '''
#Omar_Martinez_1484888
##HW_2.19
'''
#prompt user to enter amount of lemon juice
lemonJuice = float(input('Enter amount of lemon juice (in cups):\n'))
# enetr amount of water
water = float(input('Enter amount of water (in cups):\n'))
#enter amount of nectar and how many servings
agaveNectar = float(input('Enter amount of agave nectar (in cups):\n'))
servings = float(input('How many servings does this make?\n'))
#prints the servings it yields calling on servings as well
print('\nLemonade ingredients - yields', '{:.2f}'.format(servings), 'servings')
print('{:.2f}'.format(lemonJuice), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agaveNectar), 'cup(s) agave nectar\n')
NumberofServings = float(input('How many servings would you like to make?\n'))
print('\nLemonade ingredients - yields', '{:.2f}'.format(NumberofServings), 'servings')
serving = NumberofServings / servings
lemonJuice = lemonJuice * serving
water = water * serving
agaveNectar = agaveNectar * serving
print('{:.2f}'.format(lemonJuice),'cup(s) lemon juice')
print('{:.2f}'.format(water),'cup(s) water')
print('{:.2f}'.format(agaveNectar),'cup(s) agave nectar\n')
print('Lemonade ingredients - yields','{:.2f}'.format(NumberofServings),'servings')
lemonGallon = lemonJuice / 16.0
waterGallon = water / 16.0
agaveGallon = agaveNectar / 16.0
print('{:.2f}'.format(lemonGallon), 'gallon(s) lemon juice')
print('{:.2f}'.format(waterGallon),'gallon(s) water')
print('{:.2f}'.format(agaveGallon), 'gallon(s) agave nectar')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.