blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ad929f0d120653cf303cf7d59018eccdedae04c6 | KULDEEPMALIKM41/Practices | /Python/Python Basics/114.multiple.py | 2,399 | 4.3125 | 4 | # 4. multiple inheritance =>
# (base for C)CLASS A CLASS B(base for C)
# | |
# | |
# ______________________________________
# |
# |
# CLASS C(derived for A and B)
# Drawback of other technology =>
# 1.if base class will contain functionality with same name it may
# generate ambiguity problem.
# 2. their is no possibility to extends(inherit) multiple class
# simultaneously.
#Example:-
class A:
def aData(self):
print('class A member invoked')
class B:
def bData(self):
print('class B member invoked')
class C(A,B):
def cData(self):
print('class C member invoked')
obj=C()
obj.aData()
obj.bData()
obj.cData()
print('\n\n\n')
#Example:-
class A:
def Data(self):
print('class A member invoked')
class B:
def Data(self):
print('class B member invoked')
class C(A,B): # first class member function is call which same name.
def cData(self):
print('class C member invoked')
obj=C()
obj.Data()
obj.cData()
print('\n\n\n')
#Example:-
class A:
def Data(self):
print('class A member invoked')
class B:
def Data(self):
print('class B member invoked')
class C(B,A): # first class member function is call which same name.
def cData(self):
print('class C member invoked')
obj=C()
obj.Data()
obj.cData()
print('\n\n\n')
#Example:-
class A:
def Data(self):
print('class A member invoked')
class B:
def Data(self):
print('class B member invoked')
class C(B,A): # first class member function is call which same name.
def Data(self):
super(C,self).Data()
print('class C member invoked')
obj=C()
obj.Data()
print('\n\n\n')
#Example:-
class A:
def Data(self):
print('class A member invoked')
class B:
def bData(self):
print('class B member invoked')
class C(A,B): # first class member function is call which same name.
def Data(self):
super(C,self).Data()
print('class C member invoked')
obj=C()
obj.bData()
obj.Data()
print('\n\n\n')
#Example:-
class A:
def aData(self):
print('class A member invoked')
class B:
def Data(self):
print('class B member invoked')
class C(A,B): # first class member function is call which same name.
def Data(self):
super(C,self).Data()
print('class C member invoked')
obj=C()
obj.aData()
obj.Data()
print('\n\n\n') | true |
534146d46f8c71c9edec393105942add3bc01f5a | KULDEEPMALIKM41/Practices | /Python/Single Py Programms/statistics_module.py | 1,459 | 4.15625 | 4 | from statistics import *
a = [1,10,3.5,4,6,7.3,4]
b = [2,2,3,8,9]
print("mean(a) - ",mean(a)) # The mean() method calculates the arithmetic mean of the numbers in a list.
print("mean(b) - ",mean(b))
print("median(a) - ",median(a)) # The median() method returns the middle value of numeric data in a list.
print("median(b) - ",median(b))
print("mode(a) - ",mode(a)) # The mode() method returns the most common data point in the list.
print("mode(b) - ",mode(b))
print("median_grouped(a) - ",median_grouped(a,interval=2)) # The median_grouped() method return the 50th percentile (median) of grouped continuous data
print("median_grouped(b) - ",median_grouped(b,interval=2)) # interval by default is 1.
print("median_high(a) - ",median_high(a)) # The median_low() method returns the high middle value of numeric data in a list.
print("median_high(b) - ",median_high(b))
print("median_low(a) - ",median_low(a)) # The median_low() method returns the low middle value of numeric data in a list.
print("median_low(b) - ",median_low(b))
print("harmonic_mean(a) - ",harmonic_mean(a)) # The harmonic_mean() method returns the harmonic mean of data.
print("harmonic_mean(b) - ",harmonic_mean(b))
print("variance(a) - ",variance(a)) # The variance() method returns the sample variance of data.
print("variance(b) - ",variance(b))
print("stdev(a) - ",stdev(a)) # The stdev() method returns the square root of the sample variance.
print("stdev(b) - ",stdev(b))
| true |
0702ece64a2e2eaffc7fa970ddf974ec2f244dbf | minhnhoang/hoangngocminh-fundamental-c4e23 | /session3/password_validation.py | 424 | 4.28125 | 4 | pw = input("Enter password: ")
while True:
if len(pw) <= 8:
print("Password length must be greater than 8")
elif pw.isalpha():
print("Password must contain number")
elif pw.isupper() or pw.islower():
print("Password must contain both lower and upper case")
elif pw.isdigit():
print("Password must contain character")
else:
break
pw = input("Enter password: ") | true |
c298d41657f00d72a8718da8741c9d0cf24acc3a | oreolu17/python-proFiles | /list game.py | 1,284 | 4.1875 | 4 | flag = True
list = [ 10,20,30,40,50]
def menu():
print("Enter 1: to insert \n Enter 2: to remove \n Enter 3: to sort \n Enter 4: to extend \n Enter 5 to reverse \n Enter 6: to transverse")
def insertlist(item):
list.append(item)
def remove(item):
list.remove(item)
def sort(item):
list.sort()
def extend(item):
list.extend()
def reverse(item):
list.reverse()
def playgame():
flag = True
while (flag):
menu()
choice = input()
choice = int(choice)
if choice == 1:
item = input ('Enter the item you want to add to the list')
insertlist(item)
elif choice == 2:
item = input ('Enter the item you want to remove')
remove(item)
elif choice == 3:
item = input('Enter an item you want to sort')
sort(item)
elif choice == 4:
item = input('Enter an item you want to extend')
extend(item)
elif choice == 5:
item = input('Enter an item you want to reverse')
reverse(item)
elif choice == 6:
for d in list:
print(d)
playagain = input ('Do you want to play again? ')
if playagain == 'no':
flag = False
playgame()
| true |
cf0ffad1f8470707cf05177287c5a085b8db0098 | shubham3207/pythonlab | /main.py | 284 | 4.34375 | 4 | #write a program that takes three numbers and print their sum. every number is given on a separate line
num1=int(input("enter the first num"))
num2=int(input("enter the second num"))
num3=int(input("enter the third num"))
sum=num1+num2+num3
print("the sum of given number is",sum)
| true |
d3a882a461e6f5b853ea7202592418618539c5e1 | llmaze3/RollDice.py | /RollDice.py | 679 | 4.375 | 4 | import random
import time
#Bool variable
roll_again = "yes"
#roll dice until user doesn't want to play
while roll_again == "yes" or roll_again == "y" or roll_again == "Yes" or roll_again == "Y" or roll_again == "YES":
print("\nRolling the dice...")
#pause the code so that it feels like dice is being rolled
#sleep 1 second
time.sleep(1)
#pick variable between 1 and 6
dice1=random.randint(1, 6)
dice2=random.randint(1, 6)
print("The values are:")
print("Dice 1 =", dice1, "Dice 2 =", dice2)
if dice1 == dice2:
print("You rolled a double")
else:
print("Keep trying!")
#option to change yes to no
roll_again = input("\nRoll the dice again? (Y/N) ")
| true |
246d6138de3857dd8bf9a4488ebcce3d9f1c7144 | StevenLOL/kaggleScape | /data/script87.py | 1,355 | 4.34375 | 4 |
# coding: utf-8
# Read in our data, pick a variable and plot a histogram of it.
# In[4]:
# Import our libraries
import matplotlib.pyplot as plt
import pandas as pd
# read in our data
nutrition = pd.read_csv("../input/starbucks_drinkMenu_expanded.csv")
# look at only the numeric columns
nutrition.describe()
# This version will show all the columns, including non-numeric
# nutrition.describe(include="all")
# Plot a histogram using matplotlib.
# In[15]:
# list all the coulmn names
print(nutrition.columns)
# get the sodium column
sodium = nutrition[" Sodium (mg)"]
# Plot a histogram of sodium content
plt.hist(sodium)
plt.title("Sodium in Starbucks Menu Items")
# Plot a histogram using matplotlib with some extra fancy stuff (thanks to the Twitch chat for helping out!)
# In[25]:
# Plot a histogram of sodium content with nine bins, a black edge
# around the columns & at a larger size
plt.hist(sodium, bins=9, edgecolor = "black")
plt.title("Sodium in Starbucks Menu Items") # add a title
plt.xlabel("Sodium in milligrams") # label the x axes
plt.ylabel("Count") # label the y axes
# Plot a histogram using the pandas wrapper of matplotlib.
# In[26]:
### another way of plotting a histogram (from the pandas plotting API)
# figsize is an argument to make it bigger
nutrition.hist(column= " Sodium (mg)", figsize = (12,12))
| true |
2c8305b951b42695790cc95fef57b5f3751db447 | GowthamSiddarth/PythonPractice | /CapitalizeSentence.py | 305 | 4.1875 | 4 | '''
Write a program that accepts line as input and prints the lines after making all words in the sentence capitalized.
'''
def capitalizeSentence(sentence):
return ' '.join([word.capitalize() for word in sentence.split()])
sentence = input().strip()
res = capitalizeSentence(sentence)
print(res)
| true |
b78fea29f88fee4293581bbbfae5da0fa60065b9 | GowthamSiddarth/PythonPractice | /RobotDist.py | 1,030 | 4.4375 | 4 | '''
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT
with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
'''
from math import sqrt
def getRobotDistance():
dx, dy = 0, 0
while True:
ip = input().strip()
if not ip:
break
else:
lst = ip.split()
direction, dist = lst[0], int(lst[1])
if direction == "UP":
dy += dist
elif direction == "DOWN":
dy -= dist
elif direction == "LEFT":
dx -= dist
elif direction == "RIGHT":
dx += dist
return round(sqrt(dx * dx + dy * dy))
res = getRobotDistance()
print(res)
| true |
c1a94cfefd636be989ea3c0df1a2f40ecefd6390 | GowthamSiddarth/PythonPractice | /PasswordValidity.py | 1,368 | 4.3125 | 4 | '''
A website requires the users to input username and password to register.
Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria.
Passwords that match the criteria are to be printed, each separated by a comma.
'''
import re
def isValidPassword(password):
l = len(password)
if not re.search(pattern="[a-z]", string=password):
return False
elif not re.search(pattern="[A-Z]", string=password):
return False
elif not re.search(pattern="[0-9]", string=password):
return False
elif not re.search(pattern="[$#@]", string=password):
return False
elif re.search(pattern="[^a-zA-Z0-9$#@]", string=password):
return False
elif 6 > l > 12:
return False
else:
return True
def getValidPasswords(passwords):
return [password for password in passwords if isValidPassword(password)]
passwords = input().strip().split(',')
res = getValidPasswords(passwords)
print(res)
| true |
2b78532e935cc48136266b96a4a8d5070d14852b | GowthamSiddarth/PythonPractice | /EvenValuesFromTuple.py | 268 | 4.1875 | 4 | '''
Write a program to generate and print another tuple whose values are even numbers
'''
def getEvenNumsFromTuple(nums):
return tuple(x for x in nums if x % 2 == 0)
nums = list(map(int, input().strip().split(',')))
res = getEvenNumsFromTuple(nums)
print(res)
| true |
615e85b944a61c73a1e1e0a2c99738750ebd112a | CHANDUVALI/Python_Assingment | /python27.py | 274 | 4.21875 | 4 | #Implement a progam to convert the input string to lower case ( without using standard library)
Str1=input("Enter the string to be converted uppercase: ")
for i in range (0,len(Str1)):
x=ord(Str1[i])
if x>=65 and x<=90:
x=x+32
y=chr(x)
print(y,end="")
| true |
6c299c77b83d1f18798aacebb941d947de7236d4 | monajalal/Python_Playground | /binary_addition.py | 510 | 4.1875 | 4 | '''
Implement a function that successfully adds two numbers together and returns
their solution in binary. The conversion can be done before, or after the
addition of the two. The binary number returned should be a string!
Test.assert_equals(add_binary(51,12),"111111")
'''
#the art of thinking simpler is POWER
def add_binary(a,b):
#your code here
#binary_sum = bin(a + b)
#b_index = binary_sum.index('b')
#return binary_sum[b_index+1:]
return bin(a + b)[2:]
print(add_binary(51, 12))
| true |
cce21967d8f50cdc3ac1312886f909db26cae7cf | bjgrant/python-crash-course | /voting.py | 1,033 | 4.3125 | 4 | # if statement example
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# else stament example
else:
print("Sorry, you are too young to vote!")
print("Please register to vote as soon as you turn 18!")
# if-elif-else example
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
# more concise way of writing it
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# adding multiple elif blocks
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
# not using an else block
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
| true |
0efc11ea4177989652d50c18eaeca9cf25988c18 | bjgrant/python-crash-course | /cars.py | 594 | 4.53125 | 5 | # list of car makers
cars = ["bmw", "audi", "toyota", "subaru"]
# sorts the list alphabetically
cars.sort()
print(cars)
# sorts the list in reverse alphabetic order
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort(reverse=True)
print(cars)
cars = ["bmw", "audi", "toyota", "subaru"]
# Print the list contents sorted, but do change the list itself
print("Here is the original list:")
print(cars)
print("Here is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)
# reverse the order of the list
print(cars)
cars.reverse()
print(cars)
print(len(cars)) | true |
5bfeeb9948c267f0d0a4029800ef0cd8157a3689 | Japoncio3k/Hacktoberfest2021-5 | /Python/sumOfDigits.py | 225 | 4.1875 | 4 | num = int(input("Enter a number: "));
if(num<0):
print('The number must be positive')
else:
total = 0;
while num!=0:
total += num%10;
num = num//10;
print("The sum of the digits is: ", total); | true |
1d52ec1e83e2f428223741dde50588025375dd26 | derekhua/Advent-of-Code | /Day10/Solution.py | 1,859 | 4.125 | 4 | '''
--- Day 10: Elves Look, Elves Say ---
Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s).
Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).
For example:
1 becomes 11 (1 copy of digit 1).
11 becomes 21 (2 copies of digit 1).
21 becomes 1211 (one 2 followed by one 1).
1211 becomes 111221 (one 1, one 2, and two 1s).
111221 becomes 312211 (three 1s, two 2s, and one 1).
Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
Your puzzle answer was 360154.
--- Part Two ---
Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of Life fame).
Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?
Your puzzle answer was 5103798.
Both parts of this puzzle are complete! They provide two gold stars: **
'''
# num_str is a string
# count is a in
# returns a string
def look_and_say(num_str, counts):
if counts == 0:
return num_str
builder = ''
candidate = num_str[0]
count = 1
for c in num_str[1:]:
if c != candidate:
builder += str(count) + candidate
candidate = c
count = 1
else:
count +=1
builder+= str(count) + candidate
return look_and_say(builder, counts-1)
print '40 times: ' + str(len(look_and_say('1113122113', 40)))
print '50 times: ' + str(len(look_and_say('1113122113', 50)))
| true |
2ad7197fd85f713b16fece5d7253bb4a4bd8b606 | JuanSaldana/100-days-of-code-challenges | /day-19/turtle_race.py | 1,638 | 4.125 | 4 | from turtle import Turtle, Screen, colormode
from random import randint
colormode(255)
def set_random_color(turtle: Turtle):
r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
turtle.color((r, g, b))
def setup_race(n):
turtles = []
screen_size = screen.screensize()
step = screen_size[1]/n
initial_pos = step/2.
y_pos = [initial_pos + i*step + y_offset for i in range(n)]
x_pos = [20 + x_offset]*n
for i in range(n):
turtle = Turtle("turtle")
turtles.append(turtle)
turtle.penup()
set_random_color(turtle)
turtle.setpos((x_pos[i], y_pos[i]))
return turtles
def race(turtles):
winner = None
while not winner:
for turtle in turtles:
turtle.forward(randint(5, 30))
winner = next(
(turtle for turtle in turtles if turtle.position()[0] >= race_limit), None)
return winner
screen = Screen()
x_offset = -500
y_offset = -200
race_limit = 800 + x_offset
size = (400, 1000)
screen.setup(height=size[0], width=size[1])
# screen.setworldcoordinates(-500, -100, 500, 100)
screen.screensize(canvheight=size[0], canvwidth=size[1])
n_turtles = 10
# Setup race
turtles = setup_race(n_turtles)
# ask turtle's name
turtle_id = screen.numinput(
"Bet for a turtle", f"Pick a number between 0 and {n_turtles-1}")
# Start race
winner = race(turtles)
winner_id = turtles.index(winner)
screen.title(f"WINNER IS TURTLE {winner_id}")
if winner_id == turtle_id:
message = "YOU WIN"
else:
message = "YOU LOOSE"
# Print race's output
screen.textinput(message, "Please just enter to leave")
screen.listen()
| true |
8412be3158ced9cda22b82984ba0b2296c3da8a2 | jsculsp/python_data_structure | /11/buildhist.py | 1,361 | 4.25 | 4 | # Prints a histogram for a distribution of the letter grades computed
# from a collection of numeric grades extracted from a text file.
from maphist import Histogram
def main():
# Create a Histogram instance for computing the frequencies.
gradeHist = Histogram('ABCDF')
# Open the text file containing the grades.
with open('cs101grades.txt') as gradeFile:
content = gradeFile.readlines()
# Extract the grades and increment the appropriate counter.
lst = []
for line in content:
lst += line.split(' ')
for i in lst:
grade = int(i)
gradeHist.incCount(letterGrade(grade))
# Print the histogram chart.
printChart(gradeHist)
# Determine the letter grade for the given numeric value.
def letterGrade(grade):
if grade >= 90:
return 'A'
elif grade >= 80:
return 'B'
elif grade >= 70:
return 'C'
elif grade >= 60:
return 'D'
else:
return 'F'
# Print the histogram as a horizontal bar chart.
def printChart(gradeHist):
print(' Grade Distribution.')
# Print the body of the chart.
letterGrades = ('A', 'B', 'C', 'D', 'F')
for letter in letterGrades:
print(' |')
print(letter + ' +'),
freq = gradeHist.getCount(letter)
print('*' * freq)
# Print the x-axis.
print(' |')
print(' ' + '+----' * 8)
print(' 0 5 10 15 20 25 30 35')
# Call the main routine.
if __name__ == '__main__':
main() | true |
4d79e76fceb858235da96274f62274bd8bc9fa7a | jsculsp/python_data_structure | /2/gameoflife.py | 1,548 | 4.25 | 4 | # Program for playing the game of Life.
from life import LifeGrid
from random import randrange
# Define the initial configuration of live cells.
INIT_CONFIG = [(randrange(10), randrange(10)) for i in range(50)]
# Set the size of the grid.
GRID_WIDTH = 10
GRID_HEIGHT = 10
# Indicate the number of generations.
NUM_GENS = 20
def main():
# Construct the game grid and configure it.
grid = LifeGrid(GRID_WIDTH, GRID_HEIGHT)
grid.configure(INIT_CONFIG)
# Play the game.
print('This is the initial generation: ')
draw(grid)
for i in range(NUM_GENS):
print('This is generation %s: ' % (i + 1))
evolve(grid)
draw(grid)
# Generates the next generation of organisms.
def evolve(grid):
# List for storing the live cells of the next generations.
liveCells = list()
# Iterate over the elements of the grid.
for i in range(grid.numRows()):
for j in range(grid.numCols()):
# Determine the number of live neighbors for this cell.
neighbors = grid.numLiveNeighbors(i, j)
# Add the (i, j) tuple to liveCells if this cell contains
# a live organism in the next generation.
if (neighbors == 2 and grid.isLiveCell(i, j)) or \
(neighbors == 3):
liveCells.append((i, j))
# Reconfigure the grid using the liveCells coord list.
grid.configure(liveCells)
# Prints a text-based representation of the game grid.
def draw(grid):
for i in range(grid.numRows()):
for j in range(grid.numCols()):
print grid[i, j],
print ''
print '\n\n'
# Executes the main routine
if __name__ == '__main__':
main() | true |
7b37bb7acc6c035aaeb649d750983ec9af284bdc | jsculsp/python_data_structure | /8/priorityq.py | 1,346 | 4.1875 | 4 | # Implementation of the unbounded Priority Queue ADT using a Python list
# with new items append to the end.
class PriorityQueue(object):
# Create an empty unbounded priority queue.
def __init__(self):
self._qList = list()
# Return True if the queue is empty.
def isEmpty(self):
return len(self) == 0
# Return the number of items in the queue.
def __len__(self):
return len(self._qList)
# Add the given item to the queue.
def enqueue(self, item, priority):
# Create a new instance of the storage class and append it to the list.
entry = _PriorityQEntry(item, priority)
self._qList.append(entry)
# Remove and return the first item in the queue.
def dequeue(self):
assert not self.isEmpty(), 'Cannot dequeue from an empty queue.'
# Find the entry with the highest priority.
highest = self._qList[0].priority
for i in range(self.len()):
# See if the ith entry contains a higher priority (smaller integer).
if self._qList[i].priority < highest:
highest = self._qList[i].priority
# Remove the entry with the highest priority and return the item.
entry = self._qList.pop(highest)
return entry.item
# Private storage class for associating queue items with their priority.
class _PriorityQEntry(object):
def __init__(self, item, priorty):
self.item = item
self.priority = priority | true |
ac0ca45de03da9e85d16cbd00e07595e92ceb8cc | Ethan2957/p02.1 | /fizzbuzz.py | 867 | 4.5 | 4 | """
Problem:
FizzBuzz is a counting game. Players take turns counting the next number
in the sequence 1, 2, 3, 4 ... However, if the number is:
* A multiple of 3 -> Say 'Fizz' instead
* A multiple of 5 -> Say 'Buzz' instead
* A multiple of 3 and 5 -> Say 'FizzBuzz' instead
The function fizzbuzz should take a number and print out what the player
should say.
Tests:
>>> fizzbuzz(7)
7
>>> fizzbuzz(10)
Buzz
>>> fizzbuzz(12)
Fizz
>>> fizzbuzz(30)
FizzBuzz
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this function
def fizzbuzz(n):
if n %3 == 0 and n %5 == 0:
print("FizzBuzz")
elif n %3 == 0:
print("Fizz")
elif n %5 == 0:
print("Buzz")
else:
print(n)
| true |
7307669144fb61678697580311b3e82de4dc9784 | sujoy98/scripts | /macChanger.py | 2,495 | 4.34375 | 4 | import subprocess
import optparse
# 'optparse' module allows us to get arguments from the user and parse them and use them in the code.
# raw_input() -> python 2.7 & input() -> python3
# interface = raw_input("Enter a interface example -> eth0,wlan0 :-")
'''
OptionParser is a class which holds all the user input arguments by
creating a object 'parser' i.e we cant use the class without making an instance or
object of the class here it is 'parser'.
'''
# from optparse import OptionParser
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="interface modules like eth0, wlan0, etc.")
parser.add_option("-m", "--mac", dest="new_mac", help="example -> 00:xx:xx:xx:xx:xx")
'''
when we call .parse_args(), it will go through everything the user inputs and
separate it into two sets of information the first is arguments which is --interface and --mac and the
second one is the values i.e eth0 or wlan and the mac address
'''
'''
.parse_args() method will return two sets of information arguments and options, and to capture that we
are using two variables, we are calling them (options and arguments) which is equal to whatever it will return
through parser.parse_args()
'''
(options, arguments) = parser.parse_args()
# variables 1. interface 2. new_mac
# interface = input("Enter a interface example -> eth0,wlan0 :-")
# new_mac = input("Enter new Mac example -> 00:xx:xx:xx:xx:xx :-")
# to use the user input options we need to use options.interface and options.new_mac
interface = options.interface
new_mac = options.new_mac
print("[+] Changing MAC address for " + interface + " to " + new_mac)
'''
with this this script can be manipulated
by wlan0;ls;(in linux we can run multiple commands using ;) -> we are injecting two another extra command which
is not secure for out script
'''
# subprocess.call("ifconfig " + interface + " down", shell=True)
# subprocess.call("ifconfig " + interface + " hw ether " + new_mac, shell=True)
# subprocess.call("ifconfig " + interface + " up", shell=True)
'''
This is an another process to run subprocess in a secure way
using a list here we close quotations in place of space in the command and
as interface is a variable we doesn't need to put that in quotations
'''
subprocess.call(["ifconfig", interface, "down"])
subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])
subprocess.call(["ifconfig", interface, "up"])
| true |
4da9e5bb9096d891064eb88bfa4ccfd5bcf95447 | catechnix/greentree | /sorting_two_lists.py | 502 | 4.15625 | 4 | """
compared two sorted arrays and return one that combining the two arrays
into one which is also sorted, can't use sort function
"""
array1=[0,3,2,1,6]
array2=[1,2,4,5]
print(array2)
for i in array1:
if i not in array2:
array2.append(i)
print(array2)
array3=[]
while array2:
minimum = array2[0] # arbitrary number in list
for x in array2:
if x < minimum:
minimum = x
array3.append(minimum)
array2.remove(minimum)
print(array3)
| true |
32061facf23b68d0d1b6f7794366186dba758ead | catechnix/greentree | /print_object_attribute.py | 442 | 4.375 | 4 | """
Write a function called print_time that takes a Time object and prints it in the form hour:minute:second.
"""
class Time():
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
present_time=Time(12,5,34)
def print_time(time):
time_text="The present time is {:2d}:{:2d}:{:2d}"
print(time_text.format(time.hour,time.minute,time.second))
print_time(present_time)
| true |
8f6253e19d64eb0b4b7630e859f4e3a143fb0833 | IBA07/Test_dome_challanges | /find_roots_second_ord_eq.py | 751 | 4.1875 | 4 | '''
Implement the function find_roots to find the roots of the quadriatic equation:
aX^2+bx+c.
The function should return a tuple containing roots in any order. If the equation has only one solution, the function should return that solution as both elements of the tuple. The equation will always have at least one solution.
The roots of the quadriatic equation can be ound with the following formula:
x1,2=(-b+-sqrt(b^2-4ac))/2a
For example, find_roots(2,10,8) should return (-1, -4) or (-4,-1) as the roots of the equation 2x^2+10x+8=0 are -1 and -4.
'''
def find_roots(a, b, c):
import math
delta = b**2-4*a*c
x1 = (-1*b+math.sqrt(delta))/(2*a)
x2 = (-1*b-math.sqrt(delta))/(2*a)
return x1,x2
print(find_roots(2, 10, 8)); | true |
91bd2e803e12dae1fb6dad102e24e11db4dfdb03 | ZainabFatima507/my | /check_if_+_-_0.py | 210 | 4.1875 | 4 | num = input ( "type a number:")
if num >= "0":
if num > "0":
print ("the number is positive.")
else:
print("the number is zero.")
else:
print ("the number is negative.")
| true |
524b1d0fa45d90e7a326a37cc1f90cdabc1942e0 | CTEC-121-Spring-2020/mod-5-programming-assignment-Rmballenger | /Prob-1/Prob-1.py | 2,756 | 4.1875 | 4 | # Module 4
# Programming Assignment 5
# Prob-1.py
# Robert Ballenger
# IPO
# function definition
def convertNumber(numberGiven):
# Here a if/elif loop occurs where it checks if the numberGiven is equal to any of the numbers below, and if it does it prints the message.
if numberGiven == 1:
print("Your number of", numberGiven,
"converted to Roman Numerals is I")
elif numberGiven == 2:
print("Your number of", numberGiven,
"converted to Roman Numerals is II")
elif numberGiven == 3:
print("Your number of", numberGiven,
"converted to Roman Numerals is III")
elif numberGiven == 4:
print("Your number of", numberGiven,
"converted to Roman Numerals is IV")
elif numberGiven == 5:
print("Your number of", numberGiven,
"converted to Roman Numerals is V")
elif numberGiven == 6:
print("Your number of", numberGiven,
"converted to Roman Numerals is VI")
elif numberGiven == 7:
print("Your number of", numberGiven,
"converted to Roman Numerals is VII")
elif numberGiven == 8:
print("Your number of", numberGiven,
"converted to Roman Numerals is VIII")
elif numberGiven == 9:
print("Your number of", numberGiven,
"converted to Roman Numerals is IX")
elif numberGiven == 10:
print("Your number of", numberGiven,
"converted to Roman Numerals is X")
# Here it checks if the number is out of the 1-10 range.
elif numberGiven > 10 or numberGiven < 1:
print("I said a number BETWEEN 1 and 10.\nPlease try again...")
return
'''
main()
'''
# unit test function
def unitTest():
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Unit Tests")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# Here in my unit testing, I run a loop that checks the function with all all the potentail options the function is set to expect. I decided to use a range of 12 so both 0 and 11 are tested as well.
for numberGiven in range(12):
convertNumber(numberGiven)
print("\n")
def main():
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Main")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# For my main function here, it's just a simple input request. I do have an int selected so it makes sure to send the number as an int and not a string. I also added a break for readability. The program then calls the function convertNumber() with the paramater of whatever number was given by the user.
numberGiven = int(input("Pick a number 1 through 10\n"))
convertNumber(numberGiven)
unitTest()
main()
| true |
03f6b186c0858c30b3ec64a7954bc98d6c2b169f | StephenTanksley/cs-algorithms | /moving_zeroes/moving_zeroes.py | 1,662 | 4.1875 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
"""
U - Input is a list of integers. The list of integers will have some 0s included in it.
The 0s need to be pushed to the tail end of the list. The rest of the list needs to remain in order.
P1 (in-place swap plan) -
1) We need a way of keeping track of where we are in the array.
2) We need to know the total length of the array.
3) We need to determine if an object at a certain index is equal to 0.
4) If the integer at the next looping index is NOT equal to 0, we can insert at that index.
5) We don't actually need to touch the 0s.
P2 (ugly-stepchild recombinant lists plan) -
1) - Count the number of zeroes in the array.
2) - Remove all zeroes from the array.
3) - Create a new array with the correct number of zeroes.
4) - Squash the old array (minus zeroes) together with the new array (with the right number of zeroes)
5) - Profit.
E - We'll need a counter, a list comprehension,
a new array for the correct number of zeroes,
and then to put things together.
R - Look for a way of cleaning these functions up.
Ideally, we'd want to use the in-place swap because it wouldn't require more space.
"""
def moving_zeroes(arr):
item_count = arr.count(0)
minus_zero = [item for item in arr if item != 0]
add_zero = [0] * item_count
final_array = minus_zero + add_zero
return final_array
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
| true |
4186c4b7ce7404bdb82854787a04983a3b1dd7c7 | priyankitshukla/pythontut | /Logical Operator.py | 594 | 4.25 | 4 | is_Hot=False
is_Cold=False
if is_Hot:
print('''
Its very hot day
Drink Plenty of water
''')
elif is_Cold:
print('Its a cold day')
else:
print('Its a lovely day')
print('Enjoy your day!')
# Excersise with logical operator
if is_Cold==False and is_Hot==False:
print("Both condidtion's are false")
if is_Cold==False and not is_Hot:
print("Both condidtion's are false")
#condition
temperature=30
if temperature>30:
print('Hot Day')
elif temperature<30 and temperature>20:
print('Lovely day')
else:
print('Cold day')
| true |
dcfeb5f5a83c47e5123cf8e0c07c39a8ed246898 | afahad0149/How-To-Think-Like-A-Computer-Scientist | /Chap 8 (STRINGS)/exercises/num5(percentage_of_a_letter).py | 1,515 | 4.3125 | 4 | import string
def remove_punctuations(text):
new_str = ""
for ch in text:
if ch not in string.punctuation:
new_str += ch
return new_str
def word_frequency (text, letter):
words = text.split()
total_words = len(words)
words_with_letter = 0
for word in words:
if letter in word:
words_with_letter += 1
frequency = (words_with_letter/total_words)*100
print ("Your text contains {0} words, of which {1} ({2:.2f}%) contain an '{3}'.".
format(total_words, words_with_letter, frequency, letter))
text = """“Voilà!
In view, a humble vaudevillian veteran cast vicariously as both victim
and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity,
is a vestige of the vox populi, now vacant, vanished.
However, this valorous visitation of a bygone vexation stands vivified
and has vowed to vanquish these venal and virulent vermin
vanguarding vice and vouchsafing the violently vicious
and voracious violation of volition! The only verdict is vengeance;
a vendetta held as a votive, not in vain,
for the value and veracity of such shall one day vindicate
the vigilant and the virtuous. [laughs] Verily, this vichyssoise of verbiage
veers most verbose, so let me simply add that
it’s my very good honor to meet you and you may call me “V”."""
no_punct_text = remove_punctuations(text)
#print(no_punct_text)
word_frequency(no_punct_text,'e')
word_frequency(no_punct_text,'v') | true |
c5262a687592caede04cadc4f18ef5a66c8b9e0d | Chandu0992/youtube_pthon_practice | /core/array_example_one.py | 1,044 | 4.15625 | 4 | '''from array import *
arr = array('i',[])
n = int(input("Please Enter size of the array : "))
for i in range(n):
x = int(input("Enter next Value : "))
arr.append(x)
#manual method
print(arr)
s = int(input("Enter a Value to search : "))
k = 0
for i in arr:
if i == s:
print(k)
break
k += 1
if s not in arr:
print("Element not Found !")
#Inbulit Method
print(arr.index(s))
'''
#Assignment Questions
#1) Create an array with 5 values and delete the value at index number 2 without using in-built function
#2) write a code to reverse an array without using in-built function
from array import *
arr = array('i',[])
n = int(input("Enter size of an array : "))
for i in range(n):
x = int(input("Please Enter a value : "))
arr.append(x)
print(arr)
s = int(input("Enter value to delete : "))
for i in arr:
if i == s:
#arr.remove(s) #delete the particular element
#del arr[i] #delete the element at ith iendex
arr.remove(s)
break
print("After deletion array : ",arr) | true |
5354b5ce25def354480fbd85463224f527e38e83 | Ajat98/LeetCode-2020-Python | /good_to_know/reverse_32b_int.py | 702 | 4.3125 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
val = int(str(x)[::-1])
else:
x = x*-1
val = int(str(x)[::-1]) *-1
if val > 2**31 -1 or val < -2**31:
return 0
else: return val
| true |
412485e1024007908fc7ae3f65bc31897545985b | vaishnavi-gupta-au16/GeeksForGeeks | /Q_Merge Sort.py | 1,565 | 4.125 | 4 | """
Merge Sort
Merge Sort is a Divide and Conquer algorithm. It repeatedly divides the array into two halves and combines them in sorted manner.
Given an array arr[], its starting position l and its ending position r. Merge Sort is achieved using the following algorithm.
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide
the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in
step 2 and 3:
Call merge(arr, l, m, r)
Example 1:
Input:
N = 5
arr[] = {4 1 3 9 7}
Output: 1 3 4 7 9
Link - https://practice.geeksforgeeks.org/problems/merge-sort/1#
"""
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print() | true |
9cadb464d665ebddf21ddc73b136c0cf4026ba11 | chaiwat2021/first_python | /list_add.py | 390 | 4.34375 | 4 | # append to the end of list
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# insert with index
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
# extend list with values from another list
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
| true |
f47e0a404ee9c531f82b657c0cc4ecc987e9279c | 2flcastro/python-exercises | /solutions/2flcastro/intermediate/smallest_common_multiple.py | 2,773 | 4.375 | 4 | # ----------------------------------
# Smallest Commom Multiple
# ----------------------------------
# Find the smallest common multiple of the provided parameters that can be
# evenly divided by both, as well as by all sequential numbers in the range
# between these parameters.
#
# The range will be a list of two numbers that will not necessarily be in
# numerical order.
#
# e.g. for 1 and 3, find the lowest common multiple of both 1 and 3 that is
# evenly divisible by all numbers BETWEEN 1 and 3.
#
# Helpful Links:
# - https://www.mathsisfun.com/least-common-multiple.html
# - https://www.artofproblemsolving.com/wiki/index.php/Least_common_multiple
# ----------------------------------
import unittest
# Using a while loop to test multiples of the largest number in list,
# incrementing the largest value on itself until it reaches a value all numbers
# in the range can evenly divide into.
def smallest_common(lst):
lst.sort()
largest_num = lst[len(lst) - 1]
scm = largest_num
while True:
for number in range(lst[0], largest_num + 1):
if scm % number != 0:
scm += largest_num
break
else:
# break out of the while-loop if scm found
break
return scm
# There is another formula for finding the SCM of a pair of numbers:
# LCM(a, b) = a * b / GCD(a, b)
# You first need to find the GCD (greatest common divisor), which is done Using
# the Euclidean Algorithm (euclidean_gcd() function).
def smallest_common_2(lst):
def euclidean_gcd(a, b):
if b == 0:
return a
else:
return euclidean_gcd(b, a%b)
lst.sort()
scm = lst[0]
for i in range(lst[0] + 1, lst[len(lst) - 1] + 1):
scm = scm * i / euclidean_gcd(scm, i)
return scm
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Smallest_Common(unittest.TestCase):
def test_1(self):
self.assertEqual(smallest_common([1, 5]), 60)
def test_2(self):
self.assertEqual(smallest_common([5, 1]), 60)
def test_3(self):
self.assertEqual(smallest_common([1, 13]), 360360)
def test_4(self):
self.assertEqual(smallest_common([23, 18]), 6056820)
class Test_Smallest_Common_2(unittest.TestCase):
def test_1(self):
self.assertEqual(smallest_common_2([1, 5]), 60)
def test_2(self):
self.assertEqual(smallest_common_2([5, 1]), 60)
def test_3(self):
self.assertEqual(smallest_common_2([1, 13]), 360360)
def test_4(self):
self.assertEqual(smallest_common_2([23, 18]), 6056820)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == "__main__":
unittest.main()
| true |
c253c625f1d74938fc087d2206d75b75c974cd23 | 2flcastro/python-exercises | /beginner/longest_word.py | 1,175 | 4.1875 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
def find_longest_word(strg):
return len(strg)
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Find_Longest_Word(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word('What if we try a super-long word such as otorhinolaryngology'), 19)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == '__main__':
unittest.main()
| true |
cb64405d60c43194cb2fd4455a68a4ec7f4441d0 | 2flcastro/python-exercises | /solutions/2flcastro/beginner/longest_word.py | 2,172 | 4.28125 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
# using list comprehension and max() built-in function
def find_longest_word(strg):
words = strg.split()
return max([len(word) for word in words])
# using split() and a for-loop
def find_longest_word_2(strg):
sentence = strg.split()
longest_word = len(strg[0])
for word in sentence:
if len(word) > longest_word:
longest_word = len(word)
return longest_word
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Find_Longest_Word(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word('What if we try a super-long word such as otorhinolaryngology'), 19)
class Test_Find_Longest_Word_2(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word_2('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word_2('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word_2('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word_2('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word_2('What if we try a super-long word such as otorhinolaryngology'), 19)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == '__main__':
unittest.main()
| true |
166f72638df619e350bc3763d1082890106a7303 | smysnk/my-grow | /src/lib/redux/compose.py | 820 | 4.1875 | 4 | """
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* lambda *args: f(g(h(*args)))
"""
def compose(*funcs):
if len(funcs) == 0:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
# reverse array so we can reduce from left to right
funcs = list(reversed(funcs))
last = funcs[0]
rest = funcs[1:]
def composition(*args):
composed = last(*args)
for f in rest:
composed = f(composed)
return composed
return composition
| true |
80c7a5e3c64f31e504c793b59951260636c65d17 | mike-something/samples | /movies/movies_0.py | 974 | 4.3125 | 4 | # https://namingconvention.org/python/
#
# define variables for the cost of tickets
#
# we try and use names for variables which are clear and memorable. Its
# good to prefer longer names which are clearer - in a large program this
# can really matter
#
adult_ticket_cost = 18
child_ticket_cost = 10
print('Welcome to the movie price calculator!\n\nHow many tickets do you require?\n\n')
# a simple use of input - there is no validation though so this isn't
# nearly sufficient in the real world
adult_count = int(input('How many adults? '))
child_count = int(input('How many children? '))
total_cost = adult_ticket_cost * adult_count + child_ticket_cost * child_count
# __repr__ is a special thing in python which returns a string representation
# of an object but you can't rely on what is returned being a simple string if
# the object is a complex object
print("\n\nTotal cost to take your family to the movies: " + total_cost.__repr__())
| true |
76db9c3360d671f7461297a63475063908e33df9 | carlos-paezf/Snippets_MassCode | /python/factorial.py | 472 | 4.5 | 4 | #Calculates the factorial of a number.
#Use recursion. If num is less than or equal to 1, return 1.
#Otherwise, return the product of num and the factorial of num - 1.
#Throws an exception if num is a negative or a floating point number.
def factorial(num):
if not ((num >= 0) & (num % 1 == 0)):
raise Exception(
f"Number( {num} ) can't be floating point or negative ")
return 1 if num == 0 else num * factorial(num - 1)
factorial(6) # 720
| true |
c8f0da7555edde737b7f5e8ad697305b1087079c | carlos-paezf/Snippets_MassCode | /python/keys_only.py | 714 | 4.3125 | 4 | #Function which accepts a dictionary of key value pairs and returns
#a new flat list of only the keys.
#Uses the .items() function with a for loop on the dictionary to
#track both the key and value and returns a new list by appending
#the keys to it. Best used on 1 level-deep key:value pair
#dictionaries (a flat dictionary) and not nested data-structures
#which are also commonly used with dictionaries. (a flat dictionary
#resembles a json and a flat list an array for javascript people).
def keys_only(flat_dict):
lst = []
for k, v in flat_dict.items():
lst.append(k)
return lst
ages = {
"Peter": 10,
"Isabel": 11,
"Anna": 9,
}
keys_only(ages) # ['Peter', 'Isabel', 'Anna']
| true |
56f8f9eb11022cce409c96cabf50ecb13273e7df | HaoyiZhao/Text-chat-bot | /word_count.py | 1,116 | 4.34375 | 4 | #!/usr/bin/python
import sys
import os.path
# check if correct number of arguments
if len(sys.argv)!=2:
print "Invalid number of arguments, please only enter only one text file name as the command line argument"
sys.exit()
# check if file exists
if os.path.isfile(sys.argv[1]):
file=open(sys.argv[1], "r+")
wordFrequency={}
# read all words in file into a list, then iterate through list words
for word in file.read().split():
# separate word by hyphens, if it has hyphens
for hyphenWord in word.split('-'):
hyphenWord = ''.join(l for l in hyphenWord if l.isalpha())
# don't add word if it is a empty string after removing non-alphabetic characters(e.g. numbers)
if hyphenWord == '':
continue;
hyphenWord = hyphenWord.lower()
if hyphenWord in wordFrequency:
wordFrequency[hyphenWord] += 1
else:
wordFrequency[hyphenWord] = 1
# sort by second field of tuples (values) returned by items(), then print tuple pairs
file.close()
for k,v in sorted(wordFrequency.items(), key=lambda tup:tup[1], reverse=True):
print "%s:%s" %(k,v)
else:
print "Invalid file name specified"
| true |
c6c066383c6d2fc587e3c2bf5d26ee36c060e288 | sarank21/SummerSchool-Assignment | /SaiShashankGP_EE20B040/Assignment1Q2.py | 1,483 | 4.25 | 4 | '''
Author: Sai Shashank GP
Date last modified: 07-07-2021
Purpose: To find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.
Sample input: 10 20 10 40 50 60 70
Sample ouput: {1: [0, 3], 2: [2, 3], 3: [3, 0], 4: [3, 2]}
'''
# importing useful libraries
import numpy as np
import random
# creating a random numbers list and target number
mean = uniform(0, 10)
std_dev = uniform(0, 10)
numbers = list((np.random.rand(100)*std_dev)+mean)
targetnumber = uniform(0, 100)
def Checkcondition(N, T):
'''
This function checks the required condition for each and every possile pair and returns the list of pairs of required indices.
'''
finallist = []
len_N = len(N)
for i in range(len_N):
for j in range(len(N)):
if N[i]+N[j] == T:
answer = [i, j]
finallist.append(answer)
else:
continue
return finallist
class FindTargetIndices:
'''
This class contains to find indices of a pair of elements in a given list which add up to the given target number.
'''
target_indices = Checkcondition(numbers, targetnumber)
def show(self):
dict_target_indices = {}
for i in range(len(self.target_indices)):
dict_target_indices[i+1] = self.target_indices[i]
print(dict_target_indices)
answer_2 = FindTargetIndices()
answer_2.show()
| true |
d5131ecef9b8ab0918033d2a66a4e21ff329dd39 | NinjaOnRails/fillgaps | /fillGaps.py | 916 | 4.15625 | 4 | #! /usr/bin/env python3
# fillGaps - Finds all files with a given prefix in a folder,
# locates any gaps in the numbering and renames them to close the gap.
import shutil, os, re
folder = input("Enter path to the folder containing your files: ")
prefix = input("Enter prefix: ")
def fillGaps(folder, prefix):
regex = re.compile(r'(%s)(\d+)' % prefix)
foundFiles = []
for filename in os.listdir(folder):
if filename.startswith(prefix):
foundFiles.append(filename)
foundFiles.sort()
for i in range(1, len(foundFiles) + 1):
mo = regex.search(foundFiles[i-1])
if mo.group(2) != '0'*(3 - len(str(i))) + str(i):
newName = prefix + '0'*(3 - len(str(i))) + str(i)
print('Renaming %s to %s' % (foundFiles[i-1], newName))
shutil.move(os.path.join(folder, foundFiles[i-1]), os.path.join(folder, newName))
fillGaps(folder, prefix)
| true |
a7aff197a21019a5e75502ad3e7de79e08f80465 | jesusbibieca/rock-paper-scissors | /piedra_papel_tijeras.py | 2,820 | 4.4375 | 4 | ##Rock, paper o scissors##
#Written by Jesus Bibieca on 6/21/2017...
import random # I import the necessary library
import time #This will import the module time to be able to wait
#chose = "" #Initializing variables
def computer(): #This function will get a rand value between 1-99 and depending on the number I'll select either "rock, paper o scissors"
for i in range(1): #Determines the amount of numbers that will be returned
rand_value = random.randint(1, 99) #Set the limits of the random library
if rand_value <= 33:
chose = "rock"
elif rand_value <= 66:
chose = "paper"
else:
chose = "scissors"
return chose #Gives back an answer with the computer's selection
def game(): #This function is the game perce
print
print "This is the rock, paper, scissors' game written by Jesus Bibieca." #Display msgs
print
user = raw_input("Choose rock, paper or scissors and type it to play: ")#Takes user's entry
selection = computer()#Look for a rand selection
if user == selection:#Here below I've set a way to determine who wins
print "You chose: ", user, " and the computer chose: ", selection
print "It was a tie."
elif user == "rock" and selection == "paper":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "rock" and selection == "scissors":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
elif user == "paper" and selection == "rock":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
elif user == "paper" and selection == "scissors":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "scissors" and selection == "rock":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "scissors" and selection == "paper":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
else:
print
print "You chose: ", user, " and this is not a valid option."
time.sleep(3) #The game waits for 3 secs and then starts again.
play_again()
def play_again():
print
keep_play = raw_input("Do you want to play again? (Type yes or no) ")
if keep_play == "yes":
time.sleep(2)
game()
elif keep_play == "no":
print
print "Thank you for playing!"
time.sleep(2)
exit()
else:
print
print "This is not a valid option."
play_again()
game()#The game executes.
| true |
13c728affd7e5939a50aa5001c77f8bf25ee089c | FadilKarajic/fahrenheitToCelsius | /temp_converter.py | 653 | 4.4375 | 4 | #Program converts the temperature from Ferenheit to Celsius
def getInput():
#get input
tempInCAsString = input('Enter the temperature in Ferenheit: ')
tempInF = int( tempInCAsString )
return tempInF
def convertTemp(tempInF):
#temperature conversion formula
tempInC = (tempInF - 32) * 5/9
return tempInC
def main():
tempInF=getInput()
tempInC=convertTemp(tempInF)
print('The temperature in Celsius is: ', "%.1f" %tempInC, 'degrees')
#asks the user to perform 3 conversions
#for conversionCount in range( 3 ):
# doConversion()
if __name__ == "__main__":
main() | true |
273f798d759f25e69cfe21edcad3418d66ffd0aa | Victor094/edsaprojrecsort | /edsaprojrecsort/recursion.py | 1,020 | 4.46875 | 4 | def sum_array(array):
'''Return sum of all items in array'''
sum1 = 0
for item in array:
sum1 = sum1 + item # adding every item to sum1
return sum1 # returning total sum1
def fibonacci(number):
"""
Calculate nth term in fibonacci sequence
Args:
n (int): nth term in fibonacci sequence to calculate
Returns:
int: nth term of fibonacci sequence,
equal to sum of previous two terms
Examples:
>>> fibonacci(1)
1
>> fibonacci(2)
1
>> fibonacci(3)
2
"""
if number == 0:
return 0
if number == 1:
return 1
else :
return fibonacci(number - 1) + fibonacci(number - 2)
def factorial(n):
'''
Return n!
Example :
n! = 1*2*3*4....n
'''
if n == 0:
return 1
else:
return n * factorial(n-1)
def reverse(word):
'''
picking from last to first index
Return word in reverse
'''
return word[::-1]
| true |
c1ea1eede64d04257cd5ba8bde4aea1601044136 | Rekid46/Python-Games | /Calculator/app.py | 1,076 | 4.1875 | 4 | from art import logo
def add(a,b):
return(a+b)
def subtract(a,b):
return(a-b)
def multiply(a,b):
return(a*b)
def divide(a,b):
return(a/b)
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
n1=float(input("Enter first number: "))
n2=float(input("Enter second number: "))
while True:
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation: ")
calculation_function=operations[operation_symbol]
first_answer=calculation_function(n1,n2)
print(f"{n1}{operation_symbol}{n2}={first_answer}")
cont=input(f"type 'y' to continue with previous result{first_answer} or type 'n' to start fresh calculation and type 'q' to exit: ")
if cont=="y":
n1=first_answer
n2=float(input("Enter the next number: "))
elif cont=='n':
calculator()
elif cont=='q':
print("Thanks for using calculator.Have a good day! :-) ")
break
calculator()
| true |
838775b7700e92d22745528eb8a0d03135d44f55 | brandong1/python_textpro | /files.py | 1,485 | 4.28125 | 4 | myfile = open("fruits.txt")
content = myfile.read()
myfile.close() # Flush and close out the IO object
print(content)
##########
file = open("fruits.txt")
content = file.read()
file.close()
print(content[:90])
##########
def foo(character, filepath="fruits.txt"):
file = open(filepath)
content = file.read()
return content.count(character)
##########
with open("bear.txt") as file:
content = file.read()
with open("first.txt", "w") as file:
file.write(content[:90])
###########
# Append the text of bear1.txt to bear2.txt.
with open("bear1.txt") as file:
content = file.read()
with open("bear2.txt", "a") as file:
file.write(content)
############
# Modify the content of data.txt
with open("data.txt", "a+") as file:
file.seek(0)
content = file.read()
print(content)
file.seek(0)
file.write(content)
file.write(content)
#############
You can read an existing file with Python:
with open("file.txt") as file:
content = file.read()
You can create a new file with Python and write some text on it:
with open("file.txt", "w") as file:
content = file.write("Sample text")
You can append text to an existing file without overwriting it:
with open("file.txt", "a") as file:
content = file.write("More sample text")
You can both append and read a file with:
with open("file.txt", "a+") as file:
content = file.write("Even more sample text")
file.seek(0)
content = file.read() | true |
8e5033488a99f2c785a5d52e13745d4ab0910f61 | tanglan2009/Python-exercise | /classCar.py | 2,858 | 4.4375 | 4 | # Imagine we run a car dealership. We sell all types of vehicles,
# from motorcycles to trucks.We set ourselves apart from the competition
# by our prices. Specifically, how we determine the price of a vehicle on
# our lot: $5,000 x number of wheels a vehicle has. We love buying back our vehicles
# as well. We offer a flat rate - 10% of the miles driven on the vehicle. For trucks,
# that rate is $10,000. For cars, $8,000. For motorcycles, $4,000.
#If we wanted to create a sales system for our dealership using Object-oriented
# techniques, how would we do so? What would the objects be? We might have a Sale class,
# a Customer class, an Inventory class, and so forth, but we'd almost certainly have
# a Car, Truck, and Motorcycle class.
from abc import ABCMeta, abstractmethod
class Vehicle(object):
"""A vehicle for sale by Jeffco Car Dealership.
Attributes:
wheels: An integer representing the number of wheels the vehicle has.
miles: The integral number of miles driven on the vehicle.
make: The make of the vehicle as a string.
model: The model of the vehicle as a string.
year: The integral year the vehicle was built.
sold_on: The date the vehicle was sold.
"""
__metaclass__ = ABCMeta
base_sale_price = 0
wheels = 0
def __init__(self, miles, make, model, year, sold_on):
self.miles = miles
self.make = make
self.model = model
self.year = year
self.sold_on = sold_on
def sale_price(self):
"""Return the sale price for this vehicle as a float amount."""
if self.sold_on is not None:
return 0.0 # Already sold
return 5000.0 * self.wheels
def purchase_price(self):
"""Return the price for which we would pay to purchase the vehicle."""
if self.sold_on is None:
return 0.0 # Not yet sold
return self.base_sale_price - (.10 * self.miles)
@abstractmethod
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
pass
class Car(Vehicle):
"""A car for sale by Jeffco Car Dealership."""
base_sale_price = 8000
wheels = 4
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'car'
class Truck(Vehicle):
"""A truck for sale by Jeffco Car Dealership."""
base_sale_price = 10000
wheels = 4
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'truck'
class Motorcycle(Vehicle):
"""A motorcycle for sale by Jeffco Car Dealership."""
base_sale_price = 4000
wheels = 2
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'motorcycle'
| true |
c259a0fb4637d7d3c208a8e08657b7584501e424 | Karlhsiao/py4kids | /homework/hw_30_pay_calc.py | 1,262 | 4.21875 | 4 | '''
Calculate weekly payment by working hours and hourly rate
'''
STANDARD_HOURS = 40
OVERTIME_FACTOR = 1.5
def process_user_input(working_hours, hourly_rate):
hrs = float(working_hours)
r = float(hourly_rate)
return hrs, r
def input_from_user():
#working hours in the week, ex. 40
working_hours = None
#the hourly rate per hour, ex. 10.5
hourly_rate = None
working_hours = input("What's your working hours?:")
hourly_rate = input("What's the hourly rate?:")
return working_hours, hourly_rate
def transform_payment(hrs, rate):
overtime = hrs - STANDARD_HOURS
overtime_hr = rate * OVERTIME_FACTOR
payment = None
if hrs > STANDARD_HOURS:
payment = (STANDARD_HOURS*rate)+(overtime*overtime_hr)
else:
payment = hrs*rate
return payment
def output_to_user(payment):
payment = str(payment)
print("Your payment will be: " + payment)
def test():
hrs = 40
rate = 10.5
payment = transform_payment(hrs, rate)
assert payment == 498.75, "Please check your code..."
if __name__ == "__main__":
hrs, rate = input_from_user()
hrs, rate = process_user_input(hrs, rate)
payment = transform_payment(hrs, rate)
output_to_user(payment)
| true |
a094eace179eb7883904a900bb4ec3587c580d2c | KonstantinKlepikov/all-python-ml-learning | /python_learning/class_attention.py | 1,427 | 4.15625 | 4 | # example of traps of class construction
"""Chenging of class attributes can have side effect
"""
class X:
a = 1
"""Chenging of modified attributes can have side effect to
"""
class C:
shared = []
def __init__(self):
self.perobj = []
"""Area of visibility in methods and classes
"""
def generate1():
class Spam: # Spam - name for local area of generate()
count = 1
def method(self):
print(Spam.count)
return Spam()
def generate2():
return Spam1()
class Spam1: # is in top level of module
count = 2
def method(self):
print(Spam1.count)
def generate3(label): # return class instead of exemplar
class Spam:
count = 3
def method(self):
print('{0}={1}'.format(label, Spam.count))
return Spam
if __name__ == "__main__":
I = X()
print(I.a)
print(X.a)
print('side effect')
X.a = 2
print(I.a)
J = X()
print(J.a) # and in that exemplar to
x = C()
y = C()
print(y.shared, y.perobj) # ([], [])
x.shared.append('spam') # is translated to class attr in C()
x.perobj.append('spam') # is actual only in class exemplar
print(x.shared, x.perobj) # (['spam'], ['spam'])
print(y.shared, y.perobj) # (['spam'], [])
print(C.shared) # ['spam]
generate1().method() # 1
generate2().method() # 2
a = generate3('WhoIAm')
a().method() # WhoIAm' = 3
| true |
8dfac5602f8b55eb4b850bf8f3b7c15ea7c3363b | merryta/alx-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 550 | 4.34375 | 4 | #!/usr/bin/python3
"""
This is the "0-add_integer" module.
add a and b and it can be int or floats
"""
def add_integer(a, b):
'''
add two number
Args:
a : int or float
b : int or float
Rueturn an int
'''
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError("a must be integer")
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError("b must be integer")
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
return a + b
| true |
a5a62e8a5f03096ad0ad03eb27d9da6e1864a6b5 | JesusSePe/Python | /recursivity/Exercises3.py | 1,503 | 4.28125 | 4 | """Exercise 1. Rus multiplication method."""
from math import trunc
from random import randint
def rus(num1, num2):
if num1 == 1:
print(num1, "\t\t", num2, "\t\t", num2)
return num2
elif num1 % 2 == 0:
print(num1, "\t\t", num2)
return rus(trunc(num1 / 2), num2 * 2)
else:
print(num1, "\t\t", num2, "\t\t", num2)
return num2 + rus(trunc(num1 / 2), num2 * 2)
# print("A\t\t", "B\t\t", "SUMS")
# print(rus(3000, 82))
"""Exercise 2. Mathematical curiosity."""
def curiosity(num):
if num == 11111111:
print(num**2)
return
else:
print(num**2)
return curiosity(num * 10 + 1)
# curiosity(1)
"""Exercise 3. Guess the number."""
def guess(num, min=0, max=1000, attempt=1):
user_guess = int(input("Which number do you think it is? "))
if num == user_guess:
print("CORRECT! You guessed the number at the ", attempt, "attempt")
return
else:
if min < user_guess < num:
print("The number is between", user_guess, "and", max)
return guess(num, user_guess, max, attempt+1)
elif num < user_guess < max:
print("The number is between", min, "and", user_guess)
return guess(num, min, user_guess, attempt+1)
else:
print("The number is between", min, "and", max)
return guess(num, min, max, attempt+1)
print("A random number between 0 and 1000 will be chosen.")
guess(randint(0, 1001))
| true |
d02faf79c21f33ace38aabe121dcffc7a213e457 | vivekmuralee/my_netops_repo | /learninglists.py | 1,069 | 4.34375 | 4 | my_list = [1,2,3]
print (my_list)
print (my_list[0])
print (my_list[1])
print (my_list[2])
#########################################################
print ('Appending to the lists')
my_list.append("four")
print(my_list)
######################################################
print ('Deleting List Elements')
del my_list[2]
print (my_list)
#######################################################
print ('Learning nested List')
nest_list= []
nest_list.append (123)
nest_list.append (22)
nest_list.append ('ntp')
nest_list.append ('ssh')
my_list.append(nest_list)
print (my_list)
#######################################################
print ('Manipulating Lists')
print(my_list[3])
print (my_list[3][2])
#print (my_list[0][1])
print (my_list[2][1])
###########################################################
print ('Slicing')
sliced = my_list[1:3]
print (sliced)
#############################################################
slice_me = "ip address"
sliced = slice_me[:2]
print (sliced)
#############################################################
| true |
92379a4874c8af8cc39ba72f79aeae7e0edb741c | RyanIsCoding2021/RyanIsCoding2021 | /getting_started2.py | 270 | 4.15625 | 4 |
if 3 + 3 == 6:
print ("3 + 3 = 6")
print("Hello!")
name = input('what is your name?')
print('Hello,', name)
x = 10
y = x * 73
print(y)
age = input("how old are you?")
if age > 6:
print("you can ride the rolercoaster!")
else:
print("you are too small!")
| true |
f9e1251d704a08dc1132f4d54fb5f46fb171766e | BjornChrisnach/Edx_IBM_Python_Basics_Data_Science | /objects_class_02.py | 2,998 | 4.59375 | 5 | #!/usr/bin/env python
# Import the library
import matplotlib.pyplot as plt
# %matplotlib inline
# Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# Create an object RedCircle
RedCircle = Circle(10, 'red')
# Find out the methods can be used on the object RedCircle
dir(RedCircle)
# Print the object attribute radius
RedCircle.radius
# Print the object attribute color
RedCircle.color
# Set the object attribute radius
RedCircle.radius = 1
RedCircle.radius
# Call the method drawCircle
RedCircle.drawCircle()
# We can increase the radius of the circle by applying the method add_radius(). Let increases the
# radius by 2 and then by 5:
# Use method to change the object attribute radius
print('Radius of object:', RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):', RedCircle.radius)
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):', RedCircle.radius)
# Create a blue circle with a given radius
BlueCircle = Circle(radius=100)
# Print the object attribute radius
print(BlueCircle.radius)
# Print the object attribute color
print(BlueCircle.color)
# Call the method drawCircle
BlueCircle.drawCircle()
# Create a new Rectangle class for creating a rectangle object
class Rectangle(object):
# Constructor
def __init__(self, width=2, height=3, color='r'):
self.height = height
self.width = width
self.color = color
# Method
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height, fc=self.color))
plt.axis('scaled')
plt.show()
# Let’s create the object SkinnyBlueRectangle of type Rectangle. Its width will be 2 and height
# will be 3, and the color will be blue:
# Create a new object rectangle
SkinnyBlueRectangle = Rectangle(2, 10, 'blue')
# Print the object attribute height
print(SkinnyBlueRectangle.height)
# Print the object attribute width
print(SkinnyBlueRectangle.width)
# Print the object attribute color
print(SkinnyBlueRectangle.color)
# Use the drawRectangle method to draw the shape
SkinnyBlueRectangle.drawRectangle()
# Let’s create the object FatYellowRectangle of type Rectangle :
# Create a new object rectangle
FatYellowRectangle = Rectangle(20, 5, 'yellow')
# Print the object attribute height
print(FatYellowRectangle.height)
# Print the object attribute width
print(FatYellowRectangle.width)
# Print the object attribute color
print(FatYellowRectangle.color)
# Use the drawRectangle method to draw the shape
FatYellowRectangle.drawRectangle()
| true |
987a02de30705a5c911e4182c0e83a3e46baecb3 | littleninja/udacity-playground | /machine_learning_preassessment/count_words.py | 1,201 | 4.25 | 4 | """Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
word_dict = {}
word_list = s.split(" ")
max_count = 1
max_word_list = []
top_n = []
for word in word_list:
if word in word_dict:
word_dict[word] += 1
max_count = max(max_count, word_dict[word])
else:
word_dict[word] = 1
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
for word in word_dict:
max_word_list.append((word, word_dict[word]))
max_word_list.sort(key=lambda item: item[0]) # Sort alphabetically first
max_word_list.sort(key=lambda item: item[1],reverse=True) # Sort numerically last
# TODO: Return the top n words as a list of tuples (<word>, <count>)
n = min(n, len(max_word_list))
top_n = max_word_list[0:n]
return top_n
def test_run():
"""Test count_words() with some inputs."""
print count_words("cat bat mat cat bat cat", 3)
print count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run() | true |
857692c3bf179c775cb1416fc7d742dfbb254a39 | NCCA/Renderman | /common/Vec4.py | 1,551 | 4.125 | 4 | import math
################################################################################
# Simple Vector class
# x,y,z,w attributes for vector data
################################################################################
class Vec4:
# ctor to assign values
def __init__(self, x, y, z, w=1.0):
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
# debug print function to print vector values
def __str__(self):
return "[", self.x, ",", self.y, ",", self.z, ",", self.w, "]"
# overloaded sub operator subtract (self - rhs) returns another vector
def __sub__(self, rhs):
return Vec4(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z, self.w)
# overloaded sub operator subtract (self - rhs) returns another vector
def __add__(self, rhs):
return Vec4(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z, self.w)
# Cross product of self with rhs returns another Vector
def cross(self, rhs):
return Vec4(
self.y * rhs.z - self.z * rhs.y, self.z * rhs.x - self.x * rhs.z, self.x * rhs.y - self.y * rhs.x, 0.0
)
# Normalize vector to unit length (acts on itself)
def normalize(self):
len = math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
if len != 0:
self.x /= len
self.y /= len
self.z /= len
# simple dot product of self and rhs value n
def dot(self, n):
return (self.x * n.x) + (self.y * n.y) + (self.z * n.z)
| true |
f6d6fce48a00f5af17044c4fafbcfef686ddd1f3 | nikdom769/test_py111 | /Tasks/a2_priority_queue.py | 1,534 | 4.21875 | 4 | """
Priority Queue
Queue priorities are from 0 to 5
"""
from typing import Any
memory_prior_queue = {}
def enqueue(elem: Any, priority: int = 0) -> None:
"""
Operation that add element to the end of the queue
:param elem: element to be added
:return: Nothing
"""
global memory_prior_queue
if priority in memory_prior_queue:
memory_prior_queue[priority].append(elem)
else:
memory_prior_queue[priority] = [elem]
return None
def dequeue() -> Any:
"""
Return element from the beginning of the queue. Should return None if not elements.
:return: dequeued element
"""
global memory_prior_queue
if memory_prior_queue:
priority_min = min(memory_prior_queue)
data = memory_prior_queue[priority_min].pop(0)
if not memory_prior_queue[priority_min]:
del memory_prior_queue[priority_min]
return data
else:
return None
def peek(ind: int = 0, priority: int = 0) -> Any:
"""
Allow you to see at the element in the queue without dequeuing it
:param ind: index of element (count from the beginning)
:return: peeked element
"""
global memory_prior_queue
return memory_prior_queue[priority][ind] if memory_prior_queue\
and memory_prior_queue[priority]\
and ind < len(memory_prior_queue[priority]) - 1 else None
def clear() -> None:
"""
Clear my queue
:return: None
"""
global memory_prior_queue
memory_prior_queue = {}
return None
| true |
2be9e85741dc8553d4f6accc9f6bfd4f9ad545d1 | jwex1000/Learning-Python | /learn_python_the_hard_way_ex/ex15_extra.py | 865 | 4.4375 | 4 | #!/usr/bin/env python
# this imports the argv module from the sys libaray
print "What is the name of the file you are looking for?"
filename = raw_input("> ")
#creates a variable txt and opens the variable passed into it from the argv module
txt = open (filename)
#Shows the user what the file name is
print "Here's your file %r:" % filename
#shows the actualy contents of the file by performing the read method on the txt variable
print txt.read()
txt.close()
print txt.closed
#asks the user to retype the file name and will see it again
print "I'll also ask you to type it again:"
#put whatever the user writes into the file_again variable
file_again = raw_input("> ")
#puts the open file from the file_again variable into the txt_again variable
txt_again = open (file_again)
#shows the user the contents of the file
print txt_again.read()
txt_again.close()
| true |
66efbf4f5f6c20fe0a4a715e8f10bbf6d5690913 | JMCCMJ/CSCI-220-Introduction-to-Programming | /HW 1/usury.py | 1,750 | 4.34375 | 4 | ##
## Name: <Jan-Michael Carrington>
## <usury>.py
##
## Purpose: <This program calculates the priniple payments on a car or home
## purchase. It will tell exactly how much interest will be paid
## over the period of the loans. It also will tell the total payment.>
##
##
## Certification of Authenticity:
##
## I certify that this lab is entirely my own work.
##
##
## Input: <The principal amount, the length of the loan in months,
## and the interest rate.>
## Output: <The principal payment each month, amound paid over the life of the
## loan, and the total interest paid.>
"""
Program 1 Usury
Author: <Jan-Michael Carrington>
Purpose: Calculate the monthly payment, total amount paid, and total interest paid for a loan.
Inputs:
1.principal
2.months
3.interest rate
Outputs:
1.monthly payments
2.total payment
3.total interest paid
Authenticity:
I certify that this program is entirely my work.
"""
def main():
print('This program calculates the monthly payment, total amound paid, and total interest paid over the course of a loan.')
# Get inputs
principal = eval(input("Enter the loan amount: $"))
months = eval(input("Enter the length of the loan in months: "))
interest = eval(input('Enter the interest rate (ex. "4.3" for 4.3%) '))
# Calculate outputs
rate = interest / 1200
monthly_payment = (principal * (rate * (1 + rate)**months)) / ((1 + rate)**months - 1)
total_payment = monthly_payment * months
total_interest = total_payment - principal
# Print the outputs with text to explain what they are
print("The monthly payment is $", monthly_payment,sep="")
print("The total amount paid is $",total_payment,sep="")
print("The total interest paid is $",total_interest,sep="")
main()
| true |
0d359a3c30b12076205a4b030b7723ecf65b7ba0 | asiguqaCPT/Hangman_1 | /hangman.py | 1,137 | 4.1875 | 4 | #TIP: use random.randint to get a random word from the list
import random
def read_file(file_name):
"""
TODO: Step 1 - open file and read lines as words
"""
words = open(file_name,'r')
lines = words.readlines()
return lines
def select_random_word(words):
"""
TODO: Step 2 - select random word from list of file
"""
r_word_pos = random.randint(0,len(words)-1)
r_word = words[r_word_pos]
letter_pos = random.randint(0,len(r_word)-1)
letter = r_word[letter_pos]
word_prompt = r_word[:letter_pos] + '_' + r_word[letter_pos+1:]
print("Guess the word:",word_prompt)
return r_word
def get_user_input():
"""
TODO: Step 3 - get user input for answer
"""
guess = input("Guess the missing letter: ")
return guess
def run_game(file_name):
"""
This is the main game code. You can leave it as is and only implement steps 1 to 3 as indicated above.
"""
words = read_file(file_name)
word = select_random_word(words)
answer = get_user_input()
print('The word was: '+word)
if __name__ == "__main__":
run_game('short_words.txt')
| true |
9b3f76d0f3659b1b5d9c4c1221213ea6fbbc2a5b | arloft/thinkpython-exercises | /python-thehardway-exercises/ex4.py | 892 | 4.34375 | 4 | my_name = "Aaron Arlof"
my_age = 40 # sigh...
my_height = 70 # inches
my_weight = 152 # about
my_eyes = 'blue'
my_teeth = 'mostly white'
my_hair = 'brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall" % my_height
print "He's %d pounds heavy" % my_weight
print "Actually, that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
# more examples to show the difference between %s (format as a string) and %r (format as the literal object)
print "This -> %r is what shows up when modulo+r is used in a string." % my_name
months = "\nJan\nFeb\nMar\nApr\nMay"
print "Here are the months (as a string): %s" % months
print "Here are the months (the literal object): %r" % months
| true |
c4d6ef81f598c2f0277bb734bfd90316be19043b | andrijana-kurtz/Udacity_Data_Structures_and_Algorithms | /project3/problem_5.py | 2,914 | 4.21875 | 4 | """
Building a Trie in Python
Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search.
Before we move into the autocomplete function we need to create a working trie for storing strings. We will create two classes:
A Trie class that contains the root node (empty string)
A TrieNode class that exposes the general functionality of the Trie, like inserting a word or finding the node which represents a prefix.
Give it a try by implementing the TrieNode and Trie classes below!
"""
class TrieNode(object):
def __init__(self):
self.is_word = False
self.children = {}
def suffixes(self):
suff_store = []
self._suffixes_helper('', suff_store, self)
return suff_store
def _suffixes_helper(self, suffix, store, pnode):
## Recursive function that collects the suffix for
## all complete words below this point
if self.is_word:
store.append(suffix)
for ck, node in self.children.items():
if self == pnode:
suffix = ''
newsuffix = suffix + ck
node._suffixes_helper(newsuffix, store, pnode)
return store
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
insert `word` to trie
"""
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
def find(self, prefix):
node = self.root
for c in prefix:
if c not in node.children:
return None
node = node.children[c]
return node
MyTrie = Trie()
wordList = [
"ant", "anthology", "antagonist", "antonym",
"fun", "function", "factory",
"trie", "trigger", "trigonometry", "tripod"
]
for word in wordList:
MyTrie.insert(word)
node = MyTrie.find('tr')
print(node.suffixes())
assert(node.suffixes() == ['ie', 'igger', 'igonometry', 'ipod'])
node = MyTrie.find('ant')
print(node.suffixes())
assert(node.suffixes() == ['', 'hology', 'agonist', 'onym'])
node = MyTrie.find('f')
print(node.suffixes())
assert(node.suffixes() == ['un', 'unction', 'actory'])
node = MyTrie.find('') #edge case empty input prefix, I would personally expect all available words
print(node.suffixes())
assert(node.suffixes() == ['ant', 'anthology', 'antagonist', 'antonym', 'fun', 'function', 'factory', 'trie', 'trigger', 'trigonometry', 'tripod'])
node = MyTrie.find('Slavko') #edge case non existing input prefix
assert(node == None)
| true |
8ec108d9e7689393dce6d610019da91cd693dfd7 | ottoman91/ds_algorithm | /merge_sort.py | 1,124 | 4.375 | 4 | def merge_sort(list_to_sort):
#base case: lists with fewer than 2 elements are sorted
if len(list_to_sort) < 2:
return list_to_sort
# step 1: divide the list in half
# we use integer division so we'll never get a "half index"
mid_index = len(list_to_sort) / 2
left = list_to_sort[:mid_index]
right = list_to_sort[mid_index:]
# step 2: sort each half
sorted_left = merge_sort(left)
sorted_right = merge_sort(right)
#step 3: merge the sorted halves
sorted_list = []
current_index_left = 0
current_index_right = 0
#sortedLeft's first element comes next
# if its less than sortedRight's first
# element or if sortedRight is exhausted
while len(sorted_list) < len(left) + len(right):
if((current_index_left < len(left))) and
(current_index_right == len(right) or
sorted_left[current_index_left] < sorted_right[current_index_right]):
sorted_list.append(sorted_left[current_index_left])
current_index_left += 1
else:
sorted_list.append(sorted_right[current_index_right])
current_index_right += 1
return sorted_list
| true |
03dc6d2c4223efe10b69acd3cc6b8bbda5732fc8 | noltron000-coursework/data-structures | /source/recursion.py | 1,182 | 4.40625 | 4 | #!python
def factorial(n):
'''
factorial(n) returns the product of the integers 1 through n for n >= 0,
otherwise raises ValueError for n < 0 or non-integer n
'''
# check if n is negative or not an integer (invalid input)
if not isinstance(n, int) or n < 0:
raise ValueError(f'factorial is undefined for n = {n}')
# implement factorial_iterative and factorial_recursive below, then
# change this to call your implementation to verify it passes all tests
return factorial_iterative(n)
# return factorial_recursive(n)
def factorial_iterative(n):
# initialize total
total = 1
while n > 1:
# loop-multiply total by n
total *= n
# subtract multiplier (n) by one before looping again
n -= 1
else:
return total
def factorial_recursive(n):
# check if n is an integer larger than the base cases
if n > 1:
# call function recursively
return n * factorial_recursive(n - 1)
else:
return 1
def main():
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 1:
num = int(args[0])
result = factorial(num)
print(f'factorial({num}) => {result}')
else:
print(f'Usage: {sys.argv[0]} number')
if __name__ == '__main__':
main()
| true |
1f6878f1a62be6110158401c6e04d0c8d46a5d8b | noltron000-coursework/data-structures | /source/palindromes.py | 2,633 | 4.3125 | 4 | #!python
def is_palindrome(text):
'''
A string of characters is a palindrome if it reads the same forwards and
backwards, ignoring punctuation, whitespace, and letter casing.
'''
# implement is_palindrome_iterative and is_palindrome_recursive below, then
# change this to call your implementation to verify it passes all tests
assert isinstance(text, str), f'input is not a string: {text}'
# return is_palindrome_iterative(text)
return is_palindrome_recursive(text)
def is_palindrome_iterative(text):
'''
for each letter's index, check if [len-index-1] is equal
if its not, then its not a palindrome
'''
# lft & rgt represent index locations in the text
# lft character index mirrors rgt character index
lft = 0
rgt = len(text) - 1
# we go through the string at both ends,
# checking if its mirrored along the way
while lft < rgt:
# these while loops will skip non-alphabetical chars
# also, if lft==rgt, text[lft]==text[rgt], hence lft<rgt
while not text[lft].isalpha() and lft < rgt:
lft += 1
while not text[rgt].isalpha() and lft < rgt:
rgt -= 1
# nesting these while loops still avoids O(n^2)
# each time one of these while loops are hit...
# ...the parent while loop is hit one less time
# check if the letters are (not) symmetrical
if text[lft].lower() != text[rgt].lower():
return False
else:
# continue loop
lft += 1
rgt -= 1
else:
# if loop ends, this is a palindrome
return True
def is_palindrome_recursive(text, lft=None, rgt=None):
'''
for each letter's index, check if [len-index-1] is equal
if its not, then its not a palindrome
'''
# these can only be true on first run
if lft == None:
lft = 0
if rgt == None:
rgt = len(text) - 1
if text == '':
return True
# we go through the string at both ends,
# checking if its mirrored along the way
while lft < rgt and not text[lft].isalpha():
lft += 1
while lft < rgt and not text[rgt].isalpha():
rgt -= 1
# check if the letters are symmetrical
if text[lft].lower() != text[rgt].lower():
return False
elif lft >= rgt:
return True
else:
# continue loop
lft += 1
rgt -= 1
return is_palindrome_recursive(text,lft,rgt)
def main():
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) > 0:
for arg in args:
is_pal = is_palindrome(arg)
result = 'PASS' if is_pal else 'FAIL'
is_str = 'is' if is_pal else 'is not'
print(f'{result}: {repr(arg)} {is_str} a palindrome')
else:
print(f'Usage: {sys.argv[0]} string1 string2 ... stringN')
print(' checks if each argument given is a palindrome')
if __name__ == '__main__':
main()
| true |
ac8e6616fe97a418e310efd5feced4ffde77a8cd | themeliskalomoiros/bilota | /stacks.py | 1,696 | 4.46875 | 4 | class Stack:
"""An abstract data type that stores items in the order in which they were
added.
Items are added to and removed from the 'top' of the stack. (LIFO)"""
def __init__(self):
self.items = []
def push(self, item):
"""Accepts an item as a parameter and appends it to the end of the list.
Returns nothing.
The runtime for this method is O(1), or constant time, because appending
to the end of a list happens in constant time.
"""
self.items.append(item)
def pop(self):
"""Removes and returns the last item from the list, which is also the
top item of the Stack.
The runtime is constant time, because all it does is index to the last
item of the list (and returns it).
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""This method returns the last item in the list, which is also the item
at the top of the Stack.
The runtime is constant time, because indexing into a list is done in
constant time.
"""
if self.items:
return self.items[-1]
return None
def size(self):
"""Returns the length of the list that is representing the Stack.
This method runs in constant time because finding the length of a list
also happens in constant time.
"""
return len(self.items)
def is_empty(self):
"""This method returns a boolean value describing whethere or not the
Stack is empty.
Testing for equality happens in constant time.
"""
return self.items == []
| true |
4022fb87a259c9fd1300fd4981eb3bd23dce7c1f | 0ushany/learning | /python/python-crash-course/code/5_if/practice/7_fruit_like.py | 406 | 4.15625 | 4 | # 喜欢的水果
favorite_fruits = ['apple', 'banana', 'pear']
if 'apple' in favorite_fruits:
print("You really like bananas!")
if 'pineapple' in favorite_fruits:
print("You really like pineapple")
if 'banana' in favorite_fruits:
print("You really like banana")
if 'lemon' in favorite_fruits:
print("You really like lemon")
if 'pear' in favorite_fruits:
print("You really like pear")
| true |
500d2e4daea05e14d3cedad52e0fae2d1ca4fe92 | harjothkhara/computer-science | /Intro-Python-I/src/08_comprehensions.py | 1,847 | 4.75 | 5 | """
List comprehensions are one cool and unique feature of Python.
They essentially act as a terse and concise way of initializing
and populating a list given some expression that specifies how
the list should be populated.
Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
for more info regarding list comprehensions.
Comprehensions in Python. Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined.
List comprehensions are used for creating new lists from other iterables. As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. ... Here, square brackets signifies that the output is a list
"""
# Write a list comprehension to produce the array [1, 2, 3, 4, 5]
y = [i for i in range(1, 6)]
print(y)
# Write a list comprehension to produce the cubes of the numbers 0-9:
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
# creates a new list containing the cubes of all values from range(10)
y = [i**3 for i in range(10)]
print(y)
# Write a list comprehension to produce the uppercase version of all the
# elements in array a. Hint: "foo".upper() is "FOO".
a = ["foo", "bar", "baz"]
y = [words.upper() for words in a]
print(y)
# Use a list comprehension to create a list containing only the _even_ elements
# the user entered into list x.
x = input("Enter comma-separated numbers: ").split(',')
# What do you need between the square brackets to make it work? used int() build in python method
# elements in x are strings, need to convert each to int before using any math operation
y = [elements for elements in x if int(elements) % 2 == 0]
print(y)
| true |
23d8562ec8a10caa237d4544bb07cfefbb6fcd7f | harjothkhara/computer-science | /Sprint-Challenge--Data-Structures-Python/names/binary_search_tree.py | 2,610 | 4.1875 | 4 |
class BinarySearchTree: # a single node is a tree
def __init__(self, value): # similar to LL/DLL
self.value = value # root at each given node
self.left = None # left side at each given node
self.right = None # right side at each given node
# Insert the given value into the tree
def insert(self, value):
# compare the root value to the new value being added
# if the value is less than the root, move left
if value < self.value:
# if no child on that side insert
if self.left is None:
# creating a new class instance
self.left = BinarySearchTree(value) # a single node is a tree
# else keep moving left and call insert method again (on left) and do the check again until no child, and you can insert value to the tree
else:
self.left.insert(value)
# if the value is greater than the root, move right
elif value >= self.value:
# if no child on that side insert
if self.right is None:
# creating a new class instance
self.right = BinarySearchTree(value) # a single node is a tree
# else keep moving right and call insert method again (on right) and do the check again until no child, and you can insert value to the tree
else:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# look at root and compare it to the target
# if the target is less than the current node value,
if target < self.value:
# move left, if value exists repeat
if self.left is not None:
# recurse left side until target is found
return self.left.contains(target)
else:
return False
# if target is greater than the current node value, move right and repeat
elif target > self.value:
# move right, if value exists repeat
if self.right is not None:
# recurse right side until target is found
return self.right.contains(target)
else:
return False
# if the target equals the value return True - basecase
elif target == self.value:
return True
bst = BinarySearchTree(1)
bst.insert(8)
bst.insert(5)
bst.insert(7)
bst.insert(6)
bst.insert(3)
bst.insert(4)
bst.insert(2)
# bst.in_order_print(print)
# bst.dft_print(print)
# bst.bft_print(print)
| true |
49e4c6e85a28647c59bd025e34ac9bae09b05fc8 | rtorzilli/Methods-for-Neutral-Particle-Transport | /PreFlight Quizzes/PF3/ProductFunction.py | 445 | 4.34375 | 4 | '''
Created on Oct 9, 2017
@author: Robert
'''
#===============================================================================
# (5 points) Define a function that returns the product (i.e. ) of an unknown set of
# numbers.
#===============================================================================
def mathProduct(xi):
total = 1
for i in xi:
total = total*i
return total
answer=mathProduct([3,2,5])
print(answer)
| true |
a8e5c4bc11d9a28b1ef139cbd0f3f6b7377e6780 | itsmedachan/yuri-python-workspace | /YuriPythonProject2/YuriPy2-6.py | 337 | 4.21875 | 4 | str_temperature = input("What is the temperature today? (celsius) : ")
temperature = int(str_temperature)
if temperature >= 27:
message = "It's hot today."
elif temperature >= 20:
message = "It's warm and pleasant today."
elif temperature >= 14:
message = "It's coolish today."
else:
message = "It's cold today."
print(message) | true |
5079c30dbdb327661f2959b057a192e45fa20319 | itsmedachan/yuri-python-workspace | /YuriPythonProject2/YuriPy2-1.py | 242 | 4.15625 | 4 | str_score = input("Input your score: ")
score = int(str_score)
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is: ", grade) | true |
ad5f7bd7652559a42904eee699f9f3b0238689c8 | soniccc/regexp | /regexp2.py | 386 | 4.53125 | 5 | # Example: To verify a string contans a particular word
import re
paragraph = '''
The regular expression isolates the document's namespace value, which is then used to compose findable values for tag names
'''
word = 'namespace'
if re.search(word, paragraph):
print(f"The paragraph contains the word : '{word}'")
else:
print(f"The word '{word}' is not in this paragraph")
| true |
c50996345949e25f2bc5e6ab451e8a22f6a0c5fb | DanielFleming11/Name | /AverageScores.py | 551 | 4.28125 | 4 | #Initialize all variables to 0
numberOfScores = 0
score = 0
total = 0
scoreCount = 0
average = 0.0
#Accept the number of scores to average
numberOfScores = int(input("Please enter the number of scores you want to input: "))
#Add a loop to make this code repeat until scoreCount = numberOfScores
while(scoreCount != numberOfScores):
score = int(input("Please enter a score: "))
total = total + score
scoreCount = scoreCount + 1
average = str(total / numberOfScores)
print("The average for all the scores is: " + average)
| true |
221a661ba52f4393d984a377511f87f7ca1e285d | iwasnevergivenaname/recursion_rocks | /factorial.py | 328 | 4.40625 | 4 | # You will have to figure out what parameters to include
# 🚨 All functions must use recursion 🚨
# This function returns the factorial of a given number.
def factorial(n, result = 1):
# Write code here
result *= n
n -= 1
if n == 1:
return result
return factorial(n, result)
print(factorial(5)) | true |
b2e6d5d485409a42c565292fa84db602445778a4 | eugenesamozdran/lits-homework | /homework8_in_progress.py | 1,178 | 4.3125 | 4 | from collections.abc import Iterable
def bubble_sort(iter_obj, key=None, reverse=False):
# first, we check if argument is iterable
# if yes and if it is not 'list', we convert the argument to a list
if isinstance(iter_obj, Iterable):
# here we check if some function was passed as a key
# and modify our iterable applying the function to all its elements
if key == None:
iter_obj = list(iter_obj)
pass
else:
iter_obj = list(map(key, iter_obj))
# this is the sorting loop itself
for i in range(len(iter_obj)):
for y in range(len(iter_obj)-i-1):
if iter_obj[y] > iter_obj[y+1]:
iter_obj[y], iter_obj[y+1] = iter_obj[y+1], iter_obj[y]
# here we check if the result should be reversed or not
if reverse:
return iter_obj[::-1]
return iter_obj
else:
raise TypeError
a = [{"value": 42}, {"value": 32}, {"value": 40}, {"value": 56}, {"value": 11}]
a = bubble_sort(a, lambda x: x["value"])
print(a)
| true |
12ca3949ce6f3d218ed13f58ee0ab0a0e06f4ab4 | geyunxiang/mmdps | /mmdps/util/clock.py | 1,760 | 4.34375 | 4 | """
Clock and time related utils.
"""
import datetime
from datetime import date
def add_years(d, years):
"""
Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year + years)
except ValueError:
return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
def now():
"""
Time string represents now().
No ':' in the string, can be used in filename.
The iso time string cannot be used in filename.
"""
return datetime.datetime.now().strftime('%Y-%m-%dT%H-%M-%S.%f')
def now_str():
"""A more reader-friendly format"""
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def isofmt():
"""ISO time fmt."""
return '%Y-%m-%dT%H:%M:%S'
def simplefmt():
"""Simple time fmt."""
return '%Y%m%d'
def iso_to_time(isostr):
"""ISO time string to time object."""
return datetime.datetime.strptime(isostr, isofmt())
def time_to_iso(t):
"""Time object to iso time string."""
return datetime.datetime.strftime(t, isofmt())
def iso_to_simple(isostr):
"""ISO time string to simple time string."""
t = iso_to_time(isostr)
return datetime.datetime.strftime(t, simplefmt())
def simple_to_time(simplestr):
"""Simple time string to time object."""
return datetime.datetime.strptime(simplestr, simplefmt())
def eeg_time(t):
year, month, day, hour, minute, second = t.replace('T','-').replace(':','-').split('-')
return datetime.datetime(int(year),int(month),int(day),int(hour),int(minute),int(second))
| true |
522bc730e6d05cc957a853f5d667e553229474ff | Bigbys-Hand/crash_course_git | /functions.py | 2,909 | 4.4375 | 4 | def greet_nerds():
"""Display a simple greeting"""
print("Live long and prosper")
def better_greeting(username):
"""Display a simple greeting, pass name to function"""
print(f"Live long and prosper, {username.title()}!")
#This function is similar to the first one, but we created the PARAMETER 'username' so we could pass a name value to it as an ARGUMENT.
#The PARAMETER is 'username', the ARGUMENT could be any name - samuel, rebeka, etc.
def display_message():
"""Prints a formatted block of text summarizing what I've learned from chapter 8."""
print("This function is similar to the first one, but we created the PARAMETER 'username' so we could pass a name value to it as an ARGUMENT. \nThe PARAMETER is 'username', the ARGUMENT could be any name - samuel, rebeka, etc.")
def favorite_book(book_title):
"""Accepts one parameter, 'book_title'. Prints a message declaring the argument to be your favorite book."""
print(f"{book_title.title()} is my favorite book!")
#You can pass arguments to parameters in a number of way.
#A function definition may have multiple parameters, so a function call may need multiple arguments.
#POSITIONAL ARGUMENTS: Match each argument to parameter by the order in which the arguments are provided.
def describe_kitty(kitty_name, kitty_size, kitty_color):
"""Displays information about a pet cat. Name, size, color."""
print(f"\nI have a cat named {kitty_name.title()}.")
print(f"This is a {kitty_size} cat. Fur color is {kitty_color}.")
describe_kitty('snow','small','ashy brown and white')
#You can work with as many positional arguments as you like! Just don't forget their order.
#KEYWORD ARGUMENTS: Name-value pair you pass to a function. Name and value are associated within the argument.
#Thus you can't put arguments in the wrong order.
#The function is written the same! You just name each parameter explicitly when passing your arguments:
describe_kitty(kitty_name='snow',kitty_color='ashy gray with white coat',kitty_size='small')
#DEFAULT VALUES: An argumment for a parameter provided in the function call.
#Note that order still matters, and you can overwrite a default argument by entering that argument with a new value when you call the function.
#Order is important, default parameters should always be last so you can enter new values for them only when needed.
def describe_doggo(doggo_name, doggo_breed, doggo_good='GOOD BOY'):
"""Display factual and unbiased information about a dog."""
print(f"My dog's name is {doggo_name.title()}")
print(f"This dog is a {doggo_breed.title()} and a very {doggo_good}!")
describe_doggo('Obby','bird dog mutt')
describe_doggo('Obby','bird dog mutt','okay boy')
#If you specify name-value parts when calling a function, you can enter them in any order.
describe_doggo(doggo_breed='corgi',doggo_good='VERY GOOD BOY',doggo_name='Zeke')
| true |
5d40801b679cd7469773a11535c56ec1efb8c63e | weixuanteo/cs_foundation | /string_splosion.py | 474 | 4.28125 | 4 | # Given a non-empty string like "Code" return a string like "CCoCodCode".
# Sample input
s = "Code"
def string_splosion(str):
result = ""
# On each iteration, add the substring of the chars
for i in range(len(str)):
print("str[:i+1]: ", str[:i+1])
# [Python slicing] Returns from begining of the string to pos i+1 and concatenate to result.
result = result + str[:i+1]
return result
# Main
result = string_splosion(s)
print(result) | true |
c72327d594362697ad1b65db7530a19d564b74da | saintsavon/PortfolioProjects | /Interview_Code/Palindrome.py | 1,434 | 4.21875 | 4 | import re
import sys
# Used to get the word list file from command line
# Example command: 'python Palindrome.py test_words.txt'
input_file = sys.argv[1]
def palindrome(word):
"""
Checks if word is a palindrome
:param word:
:return Boolean:
"""
return word == word[::-1]
palindrome_dict = {}
def update(word, palindrome_dict):
"""
Used to update the dictionary when Palindrome is found
:param word:
:param palindrome_dict:
:return updated dict count:
"""
if word not in palindrome_dict:
palindrome_dict[word] = 1
return palindrome_dict
else:
palindrome_dict[word] += 1 # Counts number of times palindrome occurs
return palindrome_dict
# Reads desired .txt file to be searched for Palindromes
with open(input_file, "r") as in_f:
for line in in_f:
for word in line.split():
word = re.sub(r'[^\w]', '', word.lower()) # removes non-word char and capitalization
if palindrome(word) and len(word) > 1:
palindrome_dict = update(word, palindrome_dict)
else:
continue
in_f.close()
# Prints found palindromes to .txt file
with open("found_palindromes.txt", "w") as fp: # fp = found palindrome
for item, val in palindrome_dict.items():
fp.write(" ".join((item, str(val), "\n")))
fp.close()
print("Done! File saved as found_palindromes.txt")
| true |
11a39da4784ff32c31419d5bb891893ec22f810e | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /14. Dictionaries/125. iterating_dict.py | 1,365 | 4.25 | 4 | instructor = {
"name":"Cosmic",
"num_courses":'4',
"favorite_language" :"Python",
"is_hillarious": False,
44 : "is my favorite number"
}
# Accessing all values in a dictionary
# We'll loop through keys, loop through values, loop through both keys and values
# Values Print .values() method call on a dictionary
for value in instructor.values():
print(value)
# Keys print
for key in instructor.keys(): # .keys() method call on a dictionary
print(key)
# .items() is the method we call on the dictionary to print both the key as well as values pair
# Method 1
"""b = instructor.items()
print(b)
"""
# Method 2
"""for item in instructor.items():
print(item)"""
# Method 3
for key,value in instructor.items():
print(f"key is {key} and value is {value}")
# Exercise 126
# Loop over donations, add all the VALUES together and store in a variable called total_donations
donations = dict(sam=25.0, lena=88.99, chuck=13.0, linus=99.5, stan=150.0, lisa=50.25, harrison=10.0)
# Method 1
total_donations = []
# for donation in donations.values():
# total_donations.append(donation)
# print(total_donations)
# print(sum(total_donations))
# Method -2
a = sum(donation for donation in donations.values())
print(a)
# Method-3
b = sum(donations.values())
print(b) | true |
a9b3cedf7ae1dae5eb5ce3246552c15df6bf59eb | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /12. Lists/104. list_methods.py | 1,127 | 4.1875 | 4 | first_list = [1,2,3,4]
first_list.insert(2,'Hi..!')
print(first_list)
items = ["socks", 'mug', "tea pot", "cat food"]
# items.clear()
#Lets the items list to be a list but clears everything within it.
items = ["socks", 'mug', "tea pot", "cat food"]
first_list.pop() # Remove the last element
first_list.pop(1) #Removes the element with the index 1
# While removing it also returns the item that is removed so that we may append or assign it somewhere else as well in case you want to capture and do some operation.
last_item = items.pop()
print(last_item)
# remove - Remove the first item from the list whose value is x.
names = ["Colt","Blue","Arya","Lena","Colt","Selena","Pablo"]
names.remove("Blue")
print(names)
print(names.count("Colt")) #Counts the number of times a particular value or string is present inside a list.
# Using join is commonly done to convert lists to strings
words = ['Coding', 'is', 'fun']
b = ' '.join(words)
print(b)
name = ["Mr", "Steele"]
c= '. '.join(name)
print(c)
friends = ["Colt","Blue","Arya","Lena","Colt","Selena","Pablo"]
d = ", ".join(friends)
print(d) | true |
f4724113c5118d7bd8a03d862cf6010ba588539f | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/game_of_thrones.py | 1,970 | 4.15625 | 4 | print("Heyy there! Welcome to GOT quotes machine.")
print("What is your name human ?")
user_name = input()
print("\n Select from numbers 1 through 5 and we will give a quote (or two) based on your name. e.g. 1 or Tyrion or TL (case sensitive)\n \n")
# or First Name or Initials
print("What's your character's name?\n 1. Tyrion Lannister \n 2. Cersei Lannister \n 3. Daenerys Targaryen \n 4. Ned Stark \n 5. Ygritte \n ")
name = input("Enter your input here: ")
if name == "1": # or "Tyrion" or "TL":
print("Here are some of the Tyrion Lannister quotes:\n 1. The powerful have always preyed on the powerless. That's how they became powerful in the first place.")
print("2. Let me give you some advice, bastard. Never forget what you are. The rest of the world will not. Wear it like armor, and it can never be used to hurt you.")
print("3. A lion doesn't concern himself with the opinions of a sheep.")
print("4. It's easy to confuse 'what is' with 'what ought to be', especially when 'what is' has worked out in your favor.")
elif name == "2": # or "Cersei" or "CL":
print("1. If you ever call me 'sister' again, I'll have you strangled in your sleep.")
print("2. When you play the game of thrones, you win or you die.")
elif name == "3": # or "Daenerys" or "DT":
print("1. The next time you raise a hand to me will be the last time you have hands.")
elif name == "4": # or "Ned" or "NS":
print("Winter is coming.")
elif name == "5": # or "Ygritte" or "Y":
print("You know Nothing! Jon Snow!")
else:
print("Please read the first line where at the end we give examples about how to enter name to get character quotes.\nProgram will exit now. Re-run if you actually need GOT quotes and are not here for QA testing of my code.")
print(f"You just need to read and feed in right input {user_name}. C'mon {user_name} you can do it! :) ")
# Suggestion for future based on key words in quotes make an alexa function that recognizes who said it . | true |
aaaf8d5decbabeede4a42c2630fc1f31ec387a58 | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/bouncer.py | 1,367 | 4.375 | 4 | #Psuedo Code: Ask for age
# 18-21 Wristband and No Drinks
# Method1
# age = input("How old are you: ")
# age = int(age)
# if age != "":
# if age >= 18 and age < 21:
# print("You can enter, but need a wristband ! Also no drinks for you ese!")
# # 21+ Normal Entry and Drinks
# elif age >= 21:
# print("Your age is good to enter, and can drink!")
# # else too young, sorry.
# else:
# print("You can't come in little one! :( ")
# else:
# print("You drunk or what mate ? Enter a proper number as your age.")
#Now the problem is if the user hits empty string without an int and hits enter then Python throws an error.
#To solve that problem we sub-class all the statements about age inside a if != "" if not equal to empty string. Else enter valid age.
#For now just focusing on user hitting enter and not giving asljal0923 or something stupid as an input. We'll see about that in other videos.
age = input("How old are you: ")
if age:
age = int(age)
if age >= 21:
print("You age good to enter, and can drink!")
elif age >= 18:
print("You can enter, but need a wristband ! Also no drinks for you ese!")
else:
print("You can't come in little one! :( ")
else:
print("You drunk or what mate ? Enter a proper number as your age.") | true |
f96111974debd6f8a56e9eb3d964bcf2d40517d7 | iroshan/python_practice | /recursive_sum.py | 588 | 4.28125 | 4 | def recursive_sum(n=0):
''' recursively add the input to n and print the total when the input is blank'''
try:
i = input('enter a number: ')
# base case
if not i:
print(f'total = {n}')
# check if a number
elif not i.isnumeric():
print("not a number")
recursive_sum(n)
# add the number and do recursion
else:
recursive_sum(int(i)+n)
except Exception as e:
print(e)
def main():
print("SUM OF NUMBERS")
recursive_sum()
if __name__ == '__main__':
main() | true |
65fb533a490dfcaf5ed1462f217047f7a8ae5f74 | iroshan/python_practice | /guess_the_number.py | 783 | 4.125 | 4 | from random import randint
def guess_num():
''' guess a random number between 0 and 100. while users guess is equal to the number provide clues'''
num = randint(0,100)
while True:
try:
# get the number and check
guess = int(input('enter your guess: '))
if num > guess:
print('too low')
elif num < guess:
print('too high')
else:
print('That is correct. You won')
break
except Exception as e:
print('Did you enter a valid number? The number must be between 0 and 100')
def main():
print("Guessing Game\nCan you guess my number?\nIt's between 0 and 100")
guess_num()
if __name__ == '__main__':
main()
| true |
ebfcfd2080c938b2f842bebf1e0e21a2a75b8cd6 | jayfro/Lab_Python_04 | /Minimum Cost.py | 866 | 4.3125 | 4 | # Question 4 c
groceries = [ 'bananas', 'strawberries', 'apples', 'champagne' ] # sample grocery list
items_to_price_dict = { 'apples': [ 1.1, 1.3, 3.1 ], 'bananas': [ 2.1, 1.4, 1.6, 4.2 ],
'oranges': [ 2.2, 4.3, 1.7, 2.1, 4.2 ],
'pineapples': [ 2.2, 1.95, 2.5 ], 'champagne': [ 6.5, 5.9 ],
'strawberries': [ 0.98, 1.1, 0.67, 0.99 ] } # price of products
def min_cost( grocery_list, item_to_price_list_dict ):
total_min_cost = 0
for item in grocery_list:
if item in item_to_price_list_dict:
total_min_cost = total_min_cost + min(item_to_price_list_dict[item])
print " The minimum cost is: ", total_min_cost # minimum cost
min_cost( groceries, items_to_price_dict ) | true |
a3b6a12ec18d72801bf0ee0bb8a348313ddb62fa | AZSilver/Python | /PycharmProjects/test/Homework 05.py | 2,286 | 4.4375 | 4 | # -------------------------------------------------------------------------------
# Name: Homework 05
# Purpose: Complete Homework 5
# Author: AZSilverman
# Created: 10/21/2014
# Desc: Asks the user for the name of a household item and its estimated value.
# then stores both pieces of data in a text file called HomeInventory.txt
# -------------------------------------------------------------------------------
import json
# 1: Create new manages a "ToDo list." The ToDo file will contain two columns of data, separated by a comma, called:
# Task, Priority. Use a Python Dictionary to work with the data while the program is running.
# Also use Try - Catch blocks to manage user input errors.
toDoFile = "An object that represents a file"
toDoFile = open('ToDo.txt', 'r')
#
# When the program starts, load the any data you have in a text file called ToDo.txt into a python Dictionary.
data = {}
with open("ToDo.txt") as f:
for line in f:
(key, val) = line.split()
data[key] = val
# Display the contents of the file to the user
def displayData():
for key, value in data.items():
print(key, ",", value)
displayData()
#
# .
# Allow the user to Add tasks, Remove, and save the task to a file using numbered choices like this:
# print "1. Add task"
def addTask():
taskName = str(input('What is the name of the task? '))
priorityName = str(input('What is the priority of this task? '))
data.update({taskName, priorityName})
displayData()
#
# print "2. Remove task"
def removeTask():
taskName = str(input('What is the name of the task you would like to delete? '))
try:
del data['taskName']
except KeyError:
pass
# print "3. Save tasks to file"
def saveTask():
with open("ToDo.txt") as f:
f.write(json.dumps(data))
while inputString != 3:
inputString = str(input('Please select from one of the following options'))
print('1. Add task')
print('2. Remove task')
print('3. Save tasks to file (and quit)')
if (inputString == '1'):
addTask()
elif (inputString == '1'):
removeTask()
elif (inputString == '3'):
saveTask()
else:
print('I don\'t understand an option besides 1,2 or 3. Please try again' )
toDoFile.close()
exit()
| true |
6c64f1505db0b69276f2212bc96e8ec89ef81734 | u4ece10128/Problem_Solving | /DataStructures_Algorithms/10_FactorialofAnyNumber.py | 719 | 4.5 | 4 | # Find the factorial of a given number n
def factorial_iterative(n):
"""
Calculates the factorial of a given number
Complexity: O(N)
:param n: <int>
:return: <int>
"""
result = 1
for num in range(2, n+1):
result *= num
return result
def factorial_recursive(n):
"""
Calculates the factorial of a given number using recursive approach
Complexity: O(N)
:param n: <int>
:return: <int>
"""
# base case
# we keep going until we hit th base case
if n == 2:
return 2
if n < 2:
return 1
return n * factorial_recursive(n-1)
if __name__ == "__main__":
print(factorial_iterative(5))
print(factorial_recursive(5))
| true |
de2e1abde37e6fd696a8f50d6143d491d8fb5d05 | if412030/Programming | /Python/HackerRank/Introduction/Division.py | 1,658 | 4.40625 | 4 | """ In Python, there are two kinds of division: integer division and float division.
During the time of Python 2, when you divided one integer by another integer, no matter what, the result would always be an integer.
For example:
>>> 4/3
1
In order to make this a float division, you would need to convert one of the arguments into a float.
For example:
>>> 4/3.0
1.3333333333333333
Since Python doesn't declare data types in advance, you never know when you want to use integers and when you want to use a float. Since floats lose precision, it's not advised to use them in integral calculations.
To solve this problem, future Python modules included a new type of division called integer division given by the operator //.
Now, / performs float division, and // performs integer division.
In Python 2, we will import a feature from the module __future__ called division.
>>> from __future__ import division
>>> print 4/3
1.3333333333333333
>>> print 4//3
1
Note: The __ in __future__ is a double underscore.
Task
Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
You don't need to perform any rounding or formatting operations.
Input Format
The first line contains the first integer, aa. The second line contains the second integer, bb.
Output Format
Print the two lines as described above.
Sample Input
4
3
sample Output
1
1.3333333333333333
"""
#submissions
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a // b
print a / b
| true |
0fdb20e59477fd96d05f5c3d2ed9abcbb0201e39 | if412030/Programming | /Python/HackerRank/Introduction/ModDivmod.py | 1,002 | 4.5 | 4 | """ One of the built-in functions of Python is divmod, which takes two arguments aa and bb and returns a tuple containing the quotient of a/ba/b first and then the remainder aa.
For example:
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.
Task
Read in two integers, aa and bb, and print three lines.
The first line is the integer division a//ba//b (Remember to import division from __future__).
The second line is the result of the modulo operator: a%ba%b.
The third line prints the divmod of aa and bb.
Input Format
The first line contains the first integer, aa, and the second line contains the second integer, bb.
Output Format
Print the result as described above.
Sample Input
177
10
Sample Output
17
7
(17, 7)
"""
#submissions
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a // b
print a % b
print divmod(a,b)
| true |
762121b1d623ce8b5fc62b6234b333c67187131e | Ro7nak/python | /basics/Encryption_Decryption/module.py | 621 | 4.625 | 5 | # encrypt
user_input = input("Enter string: ")
cipher_text = '' # add all values to string
for char in user_input: # for every character in input
cipher_num = (ord(char)) + 3 % 26 # using ordinal to find the number
# cipher = ''
cipher = chr(cipher_num) # using chr to convert back to a letter
cipher_text = (cipher_text + cipher)
print(cipher_text)
# decrypt
decrypt_text = ''
for char in cipher_text: # for every character in the encrpted text
decrypt_num = (ord(char)) - 3 % 26
# decrypt = ''
decrypt = chr(decrypt_num)
decrypt_text = (decrypt_text + decrypt)
print(decrypt_text)
| true |
d85a139d910c67059507c6c73d49be723f3faa56 | bugmark-trial/funder1 | /Python/sum_of_digits_25001039.py | 349 | 4.25 | 4 | # Question:
# Write a Python program that computes the value of a+aa+aaa+aaaa with a given
# digit as the value of a.
#
# Suppose the following input is supplied to the program:
# 9
# Then, the output should be:
# 11106
#
# Hints:
# In case of input data being supplied to the question, it should be
#
# assumed to be a console input.
#
# Solution:
| true |
e10eae47d7a19efb93d76caeb2f6a2752cdd6666 | dichen001/CodeOn | /HWs/Week 5/S5_valid_anagram.py | 1,626 | 4.125 | 4 | """
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
"""
def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
### Please start your code here###
letterCtr = {}
for sVals in s:
if sVals in letterCtr:
letterCtr[sVals] += 1
if not sVals in letterCtr:
letterCtr[sVals] = 1
for key, val in letterCtr.iteritems():
if not t.count(key) == val:
return False
return True
### End ###
"""
Below are the test cases I created for testing the correctness of your code.
Please don't modify them when you push the file back to GitHub
"""
if __name__ == '__main__':
test0 = ("anagram", "nagaram", True)
test1 = ("rat","tar", True)
test2 = ("sdfd","d987", False)
test3 = ("23ss","ii", False)
test4 = ("rat","rt", False)
tests = [test0, test1, test2, test3, test4]
for i, test in enumerate(tests):
print("------------- Test " +str(i) + " -------------")
print("-Test Input:")
print(test[0], test[1])
print("-Expected Output:")
print(test[2])
print("-Your Output:")
your_ans = isAnagram(test[0], test[1])
print(your_ans)
print(test[2])
assert your_ans == test[2], "Wrong return. Please try again."
print('\n**** Congratulations! You have passed all the tests! ****')
| true |
3e73ef211d9d20808bad316e3d1f8493a386abd7 | joeyyu10/leetcode | /Array/56. Merge Intervals.py | 731 | 4.21875 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
res = []
intervals.sort(key=lambda x: x[0])
for x in intervals:
if res and x[0] <= res[-1][1]:
res[-1][1] = max(res[-1][1], x[1])
else:
res.append(x)
return res
| true |
886bcb3990f524a5495b4254f71d6f6d03986a9f | reemanaqvi/HW06 | /HW06_ex09_06.py | 939 | 4.34375 | 4 | #!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write function(s) to assist you
# - number of abecedarian words:
##############################################################################
# Imports
# Body
def is_abecedarian(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
else:
return is_abecedarian(word[1:])
##############################################################################
def main():
# pass # Call your function(s) here.
counter = 0
fin = open("words.txt", "r")
for word in fin:
if is_abecedarian(word):
counter +=1
fin.close()
print ("The number of abecedarian words is: %d") %(counter)
if __name__ == '__main__':
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.