blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9fc0f09b271cd06a682492a17990ae66e85859bd | Vecnik88/python-projects | /ConsoleGameKubiki/ConsoleGameKybiki.py | 2,968 | 4.15625 | 4 | """Простая игра в кубики на Python""" #
# create by vecnik88 04.01.2016 #
#######################################
print("\t\t***GAME KUBIKI***\n")
#подключаем два заголовочных файла
#time - для паузы
#randint - для рандомного числа
import time
from random import randint
#класс, который генерирует случайное число
class Die():
def __init__(self, sides=6):
self.sides=sides
###########################################################################################################
def rool_die(self):
"""Генерируетслучайное число в диапазоне [1-sides]"""
x=randint(1,self.sides)
return(x)
#консольный интерфейс программы
print ("Здраствуйте, какие кубики вы выбираете?\n\n"
" - Нажмите 1, если кубик с 6-тью гранями\n"
" - Нажмите 2, если кубик с 10-тью гранями\n"
" - Нажмите 3, если кубик с 20-тью гранями\n")
sel=False
select=""
while sel==False:
select = input()
if select == '1':
kubik6=Die()
sel=True
print("Поздравляю, вы выбрали кубики с 6 гранями, хороший выбор.\n")
elif select=='2':
kubik6=Die(10)
sel=True
print("Поздравляю, вы выбрали кубики с 10 гранями, достойный выбор.\n")
elif select=='3':
kubik6=Die(20)
sel=True
print("Поздравляю, вы выбрали кубики с 20 гранями, рискованный выбор.\n")
else:
print("Вы ввели некорректную цифру, повторите ваш ввод\n\n"
" - Нажмите 1, если кубик с 6-тью гранями\n"
" - Нажмите 2, если кубик с 10-тью гранями\n"
" - Нажмите 3, если кубик с 20-тью гранями\n")
#заключительная часть, игровой цикл
print("\t***Начнем! Удачи!!!***\n")
summa = 0
but="y"
while but =='y':
print("Хорошо встряхнем кубик и...")
time.sleep(3)
a=kubik6.rool_die()
print("На кубике, "+ str(a))
summa+= a
but=input("Хотите продолжить(y-да,n-нет)?")
if but!='y':
print("Спасибо за игру, вы достойно играли!\n"
"Сумма набранных вами баллов = "+str(summa)+'!')
#как нибудь
#сделать графический интерфейс
#------------------------------------the-end------------------------------------------------------------------
| false |
7aaafff8000a8dd92ef7fb320a857eaf7f44ff90 | krishnakrish7/string-programs | /remove nth position in a string.py | 228 | 4.125 | 4 | def remove(string,n):
first=string[:n]
last=string[n+1:]
return first+last
string=input("Enter a string")
n=int(input("Enter the index of character to remove"))
print("Modified string")
print(remove(string,n)) | true |
80d83964232354a5bac0d611e199d6c5f15cbbe3 | campbellaaron/python-coursework | /PythonDiscussions/Week3Discussion.txt | 1,089 | 4.28125 | 4 | #Print opening statement
print("To determine the oldest and youngest of 3 siblings, please enter \n" +
"their ages below: ")
firstAge = int(input("First age: "))
secondAge = int(input("Second age: "))
thirdAge = int(input("Third age: "))
#Determine the largest number by checking if each value is greater than the other 2
if (firstAge > secondAge) and (firstAge > thirdAge) :
oldest = firstAge
elif (secondAge > firstAge) and (secondAge > thirdAge) :
oldest = secondAge
elif (thirdAge > firstAge) and (thirdAge > secondAge) :
oldest = thirdAge
else :
print("Default")
#Determine the smallest number by checking if each value is less than the other 2
if (firstAge < secondAge) and (firstAge < thirdAge) :
youngest = firstAge
elif (secondAge < firstAge) and (secondAge < thirdAge) :
youngest = secondAge
elif (thirdAge < firstAge) and (thirdAge < secondAge) :
youngest = thirdAge
else :
print ("Default")
#Print the result to the screen
print ("The oldest sibling is",oldest,"years old, and the youngest sibling is",
youngest,"years old.")
| true |
0d70e1d2cbd6ae5555e39f37112aa9aa0272c8a9 | campbellaaron/python-coursework | /Assignment4/Assignment4.py | 1,034 | 4.46875 | 4 | #Initialize list of five students
studentsList = ["Sandra Dee",
"Johnny Appleseed",
"James Kirk",
"Quentin Florentino",
"Ronald Weasley"]
#Initialize variables for student grades to compute
gradeList = []
studentGradeTotal = 0
studentGradeAvg = 0
#Print opening statement
print("Please input the grades for the following students")
#Iterate through list of students
for student in studentsList:
print("Enter the grade for",student)
#Prompt user to input grade for each student as it loops
studentGrade = float(input())
#Add each grade to a new list
gradeList.append(studentGrade)
studentGradeTotal += studentGrade
#Take the student grade total and divide by the number of students for the average
studentGradeAvg = round((studentGradeTotal / 5),1)
#Convert average to string and print the result to the screen
print("The average grade for all five students is " +
str(studentGradeAvg) + "%, and the \n" +
"highest grade was " + str(max(gradeList)) + "%.")
| true |
a602ef81eca9abafcdb0c58f2327c56f8fccc247 | marciosobral/curso-python-intermediario | /Parte 3 - Função 2/Exercicio 2.py | 333 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# EXERCÍCIO 2
from time import sleep
print("\nPrograma que soma os elementos de um tupla que contenha N números.\n")
sleep(1)
def soma(*valores):
soma = 0
for numero in valores:
soma += numero
return print(f"A soma dos valores {valores} é igual a {soma}.")
soma(1, 5, 3)
| false |
cf3210da74cd4d82fa6be7533ab50a61931974c7 | sun-yifeng/python-primer | /ch11-object-class/SingleInheritDemo.py | 949 | 4.1875 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2018/11/9 10:19 AM
# @Author: sunyf
# @File : SingleInheritDemo.py
import random as r
""" 定义一个父类 """
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
self.x = -1
print("我的位置是:", self.x, self.y)
""" 定义如下子类 """
class GoldFish(Fish):
pass
class GarpFish(Fish):
pass
class SalmFish(Fish):
pass
""" 覆盖子类 """
class SharkFish(Fish):
def __init__(self):
# 注意这里要调用父类的super函数
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print("吃饭")
self.hungry = False
else:
print("太饱了")
""" 创建对象 """
fish = Fish()
fish.move()
goldFish = GoldFish()
goldFish.move()
sharkFish = SharkFish()
sharkFish.move()
| false |
4e5ae6a6d343928cbbf85d1d1f542be0b3b92ec3 | stanislavkozlovski/data_structures_feb_2016 | /SoftUni/Collection Data Structures and Libraries/exercises/events_in_given_range.py | 2,291 | 4.15625 | 4 | """
Write a program that reads a set of events in format "Event name | Date and time"
and a series of date ranges a < b and prints for each range (a < b)
all events within the range [a … b] inclusively (ordered by date;
for duplicated dates preserve the order of appearance).
Examples
Input
5
C# Course – Group II | 15-Aug-2015 14:00
Data Structures Course | 13-Aug-2015 18:00
C# Course – Group I | 15-Aug-2015 10:00
Seminar for Java Developers | 18-Aug-2015 19:00
Game Development Seminar | 15-Aug-2015 10:00
2
15-Aug-2015 10:00 | 1-Sep-2015 0:00
13-Aug-2015 10:00 | 13-Aug-2015 20:00
Output
4
C# Course - Group I | 15-Aug-2015
Game Development Seminar | 15-Aug-2015
C# Course - Group II | 15-Aug-2015
Seminar for Java Developers | 18-Aug-2015
1
Data Structures Course | 13-Aug-2015 18:00
"""
from datetime import datetime
from sortedcontainers import SortedDict
import dateparser
def main():
events = read_events(int(input())) # type: SortedDict
process_events_in_given_date(events, int(input()))
def process_events_in_given_date(events: SortedDict, events_count: int):
"""
Reads each line of user input to get the events between the two dates
"""
for _ in range(events_count):
start_date, end_date = [dateparser.parse(part) for part in input().split('|')]
print_events_between_dates(events, start_date, end_date)
def print_events_between_dates(events:SortedDict, start_date:datetime, end_date:datetime):
date_keys_between_dates = events.irange(minimum=start_date, maximum=end_date, inclusive=(True, True))
events = [(event, date_key) for date_key in date_keys_between_dates for event in events[date_key]]
for event, date in events:
print("{event} | {date}".format(event=event, date=date))
def read_events(events_count) -> SortedDict:
"""
Save a SortedDictionary of type {
key: DateTime object
value: List of courses that will happen then
}
"""
events_dict = SortedDict()
for _ in range(events_count):
event, time_str = input().split('|')
time = dateparser.parse(time_str)
if time not in events_dict.keys():
events_dict[time] = []
events_dict[time].append(event)
return events_dict
if __name__ == '__main__':
main() | true |
934a3e228a0ad3b744ad889bbd22544c0c90aa93 | KONASANI-0143/Dev | /requirements/triangle.py | 658 | 4.34375 | 4 | # Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern triangle
from __future__ import print_function # for end = " " in print syntax.
def triangle(n):
i = 0
while i<=n:
print( " " * (2*n-i), "* " * (i+1))
i+=1
j = 0
while j<=n:
print(" " * (2*n-i), "* " * (i))
i -=1
j +=1
## k = 2*n - 2
## for i in range(0, n):
## for j in range(0, k):
## print(end=" ")
## k = k - 1
## for j in range(0, i+1):
## print("* ", end=" ")
## print()
n = 5
triangle(n)
| false |
793a96f7bace97d70152e2902561206f664d4fc5 | stochasticB/projects | /classes.py | 994 | 4.21875 | 4 | # Object Orientated Programming in Python
class Goober: #Goober
def __init__(self, name): # instantiate object right when it's created
self.name = name # these don't need to match in name
print(name)
def add_one(self, x):
print(x + 1)
def bark(self): # 'self' - we need to invisibily pass the dog object through itself so that we know which dog we're accessing
print("bark")
def get_name(self):
d = Goober('Stella') # instance of class Dog
print(d.name) # name is now an attribute of the Goober
# d.bark()
#d.add_one(5)
#print(type(d)) # <class '__main__.Dog'>; default module = __main__ is the module that this class is in.
class Chonk:
def __init__(self, name):
self.name = name
print(name)
def meow(self):
print('Meow, meow, feed me!')
def feed(self,x):
print('The monthly food budget for this chonk is $:', x)
s = Chonk("Smelly")
#Smelly.meow()
#Smelly.feed(15)
| true |
a23814ef8bc9fef19fc53f150e7a44196faa25a0 | charlesjhall/lectures | /csc131/polygons.py | 2,641 | 4.25 | 4 | from turtle import Turtle
from turtle import Screen
def square(t: Turtle, length: int):
"""
Draw a hexagon with a given length
:param t: an instance of a Turtle used to render a square
:param length: length of one side of the square
:return: None
"""
b=4
for count in range(b):
t.forward(length)
t.left((360/b))
def hexagon(t: Turtle, length: int):
"""
Draw a hexagon with a given length
:param t: an instance of a Turtle used used to render a hexagon
:param length: length of one side of the hexagon
:return: None
"""
b=6
for count in range(b):
t.forward(length)
t.left((360/b))
def octagon(t: Turtle, length: int):
"""
Draw a hexagon with a given length
:param t: an instance of a Turtle used used to render a octagon
:param length: length of one side of the octagon
:return: None
"""
b=8
for count in range(b):
t.forward(length)
t.left((360/b))
def triangle(t: Turtle, length: int):
"""
Draw a hexagon with a given length
:param t: an instance of a Turtle used used to render a triangle
:param length: length of one side of the triangle
:return: None
"""
b=3
for count in range(b):
t.forward(length)
t.left((360/b))
def regular_polygon(t: Turtle, length: int, num_sides=4):
"""
Draw any regular polygon with a given length
:param t: an instance of a Turtle used used to render a regular polygon
:param length: length of one side of the polygon
:param num_sides: number of sides of the regular polygon
:return: None
"""
for count in range(num_sides):
t.forward(length)
t.left((360 / num_sides))
def radial_pattern(t: Turtle, n: int, length: int, shape) -> None:
'''
:param t: an instance of a Turtle used used to render a radial pattern
:param n: number of polygons to be drawn in the radial pattern
:param length: length of one side of the polygon
:param shape: name of the regular polygon to be drawn in the pattern, for example 'square' or 'octagon'
:return: None
'''
for count in range(n):
shape(t, length)
t.left(360 / n)
def main() -> int:
yertle = Turtle()
screen = Screen()
yertle.speed(2000)
screen.colormode(255)
yertle.color("blue")
yertle.up()
square(yertle, 300)
hexagon(yertle, 100)
octagon(yertle, 80)
triangle(yertle, 300)
regular_polygon(yertle, 5, 100)
yertle.down()
radial_pattern(yertle, 299, 100, octagon)
screen.exitonclick()
if __name__ == '__main__':
main()
| true |
07e9a83e631a5f98a1d197a2740705be5fd68123 | pita-367/sample-codes | /unit_conversion.py | 1,576 | 4.59375 | 5 | #Pushpita Rahman
#Computer Programming I
#Oct 27, 2017
#code converted lengths
#creates dictionary using inches as a base
dict_units = {
'inches': 1,
'feet': 12,
'yards': 36,
'miles': 63360,
'leagues': 190080,
'centimeters': 1/2.54,
'decimeters':10/2.54,
'meters':10**2/2.54,
'decameters':10**3/2.54,
'hectometers': 10**4/2.54,
'kilometers':10**5/2.54
}
#lets user know what program can do and what units it can take
print('Welcome to the length conversion wizard.')
print('This program can convert between any of the following length.')
print('inches\nfeet\nyards\nmiles\nleagues\ncentimeters\ndecimeters\nmeters\ndecameters\nhectometers\nkilometers')
print('Note: you must use the units exactly as spelled above.\n')
#asks user for inputs
user_val=float(input('Enter value: ')) #asks user for a digit; supports decimals
user_unit=input('Enter from units: ') #asks user for initial units
converted_units=input('Enter to units: ') #asks user for units they wish to convert to
val_in_inches=user_val*dict_units[user_unit] #converts the value into inches
converted_unit_in_inches= dict_units[converted_units] #goes into dictonary to obtain the units in inches for the unit they wish to convert to
converted_val= val_in_inches/converted_unit_in_inches #converts value to converted unit
converted_val_round4sigfigs=round(converted_val,4) #rounds value to 4 significant digits
print() #blank line
#prints the answer
print(user_val, user_unit, 'is', converted_val_round4sigfigs, converted_units,'\n')
| true |
854e2533ead287e67df6a02674a7021a5f690044 | gssakib/python-projects | /ex6.py | 926 | 4.34375 | 4 | x = 'There are %d types of people' % 10 # Just a normal variable which has a integer in items
binary = "binary" # assigning a variable
do_not = "don't" # assigning a variable
y = "Those who know %s and those who %s." %(binary, do_not) # assigning a variable with some pre-assigned variable strings
print x # printing variables
print y # printing variables
print "I said: %s" % x #printing a variable that has both string and integer
print "I also said: %r. " %y # printing a variable that has two other string variables in it
hilarious = False # boolean
joke_evaluaiton = "Isnt that joke so funny ? ! %r" % hilarious # using boolean to assign value of variable
print joke_evaluaiton #printing the variable
w = "This is the left side of ....." # assigning string variable
e = "a string with a right side." # assigning string variable
print w + e #making new string variable by adding two previous string variable
| true |
7cfe591ab787dfab8c66709275305b5f65109714 | gssakib/python-projects | /calculator.py | 1,102 | 4.15625 | 4 | from sys import argv
script , int_file, rslt_file, usr_name, pas = argv
#defining a function to read input from external files
def read_integers(int_file):
with open(int_file) as f:
return map(int,f)
if pas == 'dfort360' :
print ("Welcome %r!. Here are the operations that you can perform: Add-1 Subtract-2, Multiply-3, Divide-4.")
opr = raw_input(" what would you like to do today ?: ")
out_file = open(rslt_file, 'w')
if int(opr) == 1 :
print"Performing Operation......"
in_file = open(int_file, 'r')
num_1 =
num_2 =
rslt = num_1 + num_2
elif int(opr) == 2 :
print"Performing Operation......"
in_file = open(int_file, 'r')
num_1 =
num_2 =
rslt = num_1 - num_2
elif int(opr) == 3:
print"Performing Operation......"
in_file = open(int_file, 'r')
num_1 =
num_2 =
rslt = num_1 * num_2
elif int(opr) == 4:
print"Performing Operation......"
in_file = open(int_file, 'r')
num_1 =
num_2 =
rslt = num_1 / num_2
out_file.write(rslt)
out_file.close()
in_file.close()
else :
print"Wrong pass! Please try again!"
| true |
9714fe960e1beaf6b9c5a238272856d967a1789b | alchermd/commentify | /commentify.py | 989 | 4.25 | 4 | #! /usr/bin/python3.5
"""" Transform your plaintext into a comment. """
import sys
import pyperclip
def commentify(lang):
""" Grabs the text from the clipboard and transforms it into comments.
lang -> A string that signifies the programming language to base
the comment format.
"""
plaintext = pyperclip.paste().split('\n')
if lang == 'python':
comment = ['###\n']
char = ' # '
end = '###\n'
else:
comment = ['/*\n']
char = ' * '
end = '*/\n'
for line in plaintext:
comment.append(char + line + '\n')
comment.append(end)
return ''.join(comment)
def main():
""" Main method of the program. Ensures proper usage
and calls the commentify function. """
if len(sys.argv) > 2:
print('Usage: commentify [language]')
sys.exit(1)
language = sys.argv[1] if len(sys.argv) > 1 else 0
pyperclip.copy(commentify(language))
if __name__ == '__main__':
main()
| true |
ab7eb22dddb5249274458b7ea8d353f6bfdb53c1 | ZhouningMan/LeetCodePython | /binarysearch/SquareRoot.py | 764 | 4.1875 | 4 | class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
if x < 0:
raise ValueError('....')
# special case
if x == 0 or x == 1:
return x
start, end = 0, x
while start <= end:
mid = start + (end - start) // 2
# whenever you do division, think of division by zero
quotient = x // mid
if quotient == mid:
return mid
elif quotient > mid:
start = mid + 1
else:
end = mid - 1
# most of the time we return low because that is the insertion point,
# but in this case if we return low, then low*low > x
return end
| true |
b1d1989ede1b5fb89faa22c51e21ee13039b85ee | evantkchong/AdventOfCode2019 | /day02/solution_part2.py | 1,510 | 4.125 | 4 | # !/usr/bin/python
from solution_part1 import puzzle_input_path
from intcode_computer import IntcodeComputer
def brute_force(program:str, output:int):
for noun in range(100):
for verb in range(100):
# Instantiate intcode computer
computer = IntcodeComputer(program)
# Replace values at addresses 1 and 2 as per
# puzzle instructions
computer.edit_input(1, noun)
computer.edit_input(2, verb)
# We then run the program for the current
# noun, verb pair
try:
computer.compute()
if computer.final_state[0] == output:
print('{}, {} produces the desired output {}'.format(noun, verb, desired_output))
return noun, verb
except IndexError:
continue
print('Unable to find a suitable noun, verb pair.')
return False
if __name__ == "__main__":
# Read and preprocess the raw textfile
with open(puzzle_input_path) as f:
intcode_program_list = f.readlines()
program = intcode_program_list[0]
# Iterate through possible values of nouns and verbs
# until we obtain the pair that produces the output we want
desired_output = 19690720
noun, verb = brute_force(program, desired_output)
# Run the winning pair through the checksum
answer = (100 * noun) + verb
print('The answer for part two of the puzzle is {}'.format(answer))
| true |
d648ca6cfcce1c0952a54ffa4a964b08b24e06ea | jiikrish/Delhivery---PJM-Project | /Olastring.py | 1,923 | 4.5 | 4 | print("Hello")
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = "Hello, World!"
print(a[1])
#Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
#Get the characters from position 5 to position 1, starting the count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
#The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
#The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
#The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
#The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
#The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
#The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
#Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
# Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
# To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
# Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
# The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price)) | true |
f37c6043351ad18d6e6ca2e769b663d42250f2fb | saryamane/Python_Tips_Tricks | /Patterns_For_Cleaner_Python/Product_Sum_Problem.py | 756 | 4.28125 | 4 | # Product Sum
# Input is an array which can contain another arrays inside it.
# Return the sum of the products within the passed array list.
# Example: [x, [y,z]], output should be x + 2*(y + z)
def product_sum(array, multiplier=1):
sum = 0
for element in array:
if type(element) is list:
sum += product_sum(element, multiplier+1)
else:
sum += element
return sum * multiplier
# def product_sum(array, multiplier = 1):
# sum = 0
# for element in array:
# if type(element) is list:
# sum += product_sum(element, multiplier + 1)
# else:
# sum += element
# return sum * multiplier
output = product_sum([5,2,[7,-1], 3,[6,[-13,8], 4]])
print(output)
| true |
c73f20fe7b1152e4ed86dfd486157e9783241cad | saryamane/Python_Tips_Tricks | /Medium_Complexity/Powersets.py | 956 | 4.125 | 4 | # Write a function that takes an array of unique integers and returns its powerset.
# For e.g. Powerset of [1,2] is [[],[1],[2],[1,2]] and so on.
# We start with an iterative approach.
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets
print(powerset([1,2,3]))
# Space and Time complexity is O(n*2^n)
# Let's now do a recursive approach to this.
def powersetRecursive(array, idx=None):
if idx is None:
idx = len(array) - 1
elif idx < 0:
return [[]]
ele = array[idx]
subsets = powersetRecursive(array, idx - 1)
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets
print(powersetRecursive([1,2,3,4]))
# Space and Time complexity for the recurrsive approach is also O(n*2^n)
| true |
b35b521e5398015c85a88fc3c2875dec265d540f | Adarsh144/Hackerrank | /Python/timedelta.py | 1,661 | 4.1875 | 4 | """
When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago.
Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:
Day dd Mon yyyy hh:mm:ss +xxxx
Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.
Input Format :
The first line contains T, the number of testcases.
Each testcase contains 2 lines, representing time t1 and time t2.
Constraints :
Input contains only valid timestamps
year <= 3000
Output Format :
Print the absolute difference(t1 - t2) in seconds.
Sample Input :
2
Sun 10 May 2015 13:54:36 -0700
Sun 10 May 2015 13:54:36 -0000
Sat 02 May 2015 19:54:36 +0530
Fri 01 May 2015 13:54:36 -0000
Sample Output :
25200
88200
"""
# CODE
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the time_delta function below.
from datetime import datetime
def time_delta(t1, t2):
t1 = datetime.strptime(t1, '%a %d %b %Y %H:%M:%S %z')
t2 = datetime.strptime(t2, '%a %d %b %Y %H:%M:%S %z')
return str(int(abs((t2-t1).total_seconds())))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
t1 = input()
t2 = input()
delta = time_delta(t1, t2)
fptr.write(delta + '\n')
fptr.close()
| true |
eb0b5557e63ce414d5a26b596f001ca5730732ac | altynai02/Chapter1-Part3-Task2 | /task2.py | 594 | 4.1875 | 4 | # 2. Напишите функцию который будет конвертировать
# Фаренгейт в Цельсии и наоборот.
def cel_to_fah():
result = (temp * 9 // 5) + 32
return result
def fah_to_cel():
result = (temp - 32) * 5//9
return result
print(" 1.Celsius to Fahrenheit")
print("2.Fahrenheit to Celsius")
option = int(input("Hello young novice. Choose the option: "))
temp = int(input("Enter a temperature in degree: "))
if option == 1:
print(cel_to_fah())
elif option == 2:
print(fah_to_cel())
else:
print("Error")
| false |
9cec5addc3d998ac0ea930e467f0fc8d92aac731 | kofiBandoh/KofiBandoh_DataStructuresAlgo | /KofiBandoh_LAB_000.py | 1,043 | 4.34375 | 4 | ##Simple Calculator to operate on three numbers
def add(a,b,c):
return a + b + c
def subtract(a, b, c):
return a - b - c
def multiplication(a, b, c):
return a*b*c
def divide (a, b, c):
return (a/ b/ c )
print("Welcome to calculator \n " )
print("Select: \n1 for addition \n2 for subtraction \n3 for multiplication \n4 for subtraction ")
while True:
operator = int(input("Enter operation number: "))
if operator in (1, 2, 3, 4):
a = int(input("Enter number: "))
b = int(input("Enter another number:" ))
c = int(input("Enter the last number: "))
if operator == 1:
print("Your answer is:" , add(a, b, c))
elif operator == 2:
print("Your answer is:", subtract(a, b, c))
elif operator == 3:
print("Your answer is:", mutiplication(a, b, c))
elif operator == 4:
print("Your answer is:", divide(a, b, c))
break
else:
print("Invalid operator input ") | false |
35b035f423cb79282f37d5b12770b4b8e7c53b50 | hannah2306-cmis/hannah2306-cmis-cs2 | /ourwakeup.py | 2,086 | 4.25 | 4 |
print "This program will ask for 5 integer or float values. It will calculate the average of all values from 0 inclusive to 10 exclusive. It will print out whether the resulting average is even or odd."
def main():
number0 = raw_input("n0: ")
if float(number0) < 0 or float(number0) >= 10:
floatednumber0 = float(number0)
print (floatednumber0, " is out of range.")
else sumofnumbers = float(0thnumber):
Anumberofnumbers = 1
firstnumber = raw_input("n1: ")
if float(firstnumber) = 0 or float(firstnumber) >= 10:
floatedfirstnumber = float(firstnumber)
print floatedfirstnumber " is out of range."
elif float(0thnumber) >= 0 or float(0thnumber) < 10:
sumofnumbers = float(0thnumber) + float(firstnumber)
Bnumberofnumbers = Anumberofnumbers + 1
secondnumber = raw_input("n2: ")
if float(secondnumber) < 0 or float(secondnumber) >= 10:
floatedsecondnumber = float(secondnumber)
print floatedsecondnumber " is out of range."
elif float(firstnumber) >= 0 or float(firstnumber) < 10:
sumofnumbers = float(firstnumber) + float(secondnumber)
Bnumberofnumbers = Anumberofnumbers + 1
thirdnumber = raw_input("n3: ")
if float(thirdnumber) < 0 or float(thirdnumber) >= 10:
floatedthirdnumber = float(thirdnumber)
print floatedthirdnumber " is out of range."
elif float(secondnumber) >= 0 or float(secondnumber) < 10:
sumofnumbers = float(secondnumber) + float(thirdnumber)
Bnumberofnumbers = Anumberofnumbers + 1
fourthnumber = raw_input("n4: ")
if float(fourthnumber) < 0 or float(fourthnumber) >= 10:
floatedfourthnumber = float(fourthnumber)
print floatedfourthnumber " is out of range."
elif float(thirdnumber) >= 0 or float(thirdnumber) < 10:
sumofnumbers = float(thirdnumber) + float(fourthnumber)
Bnumberofnumbers = Anumberofnumbers + 1
| true |
29e197ee8751bfeb0546670d8d949938b7c1699a | christophchamp/xtof-devops | /src/python/thinkpython/word_histogram.py | 2,387 | 4.15625 | 4 | import string
def process_file(filename):
h = dict()
fp = open(filename)
for line in fp:
process_line(line, h)
return h
def process_line(line, h):
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(string.punctuation + string.whitespace)
word = word.lower()
h[word] = h.get(word, 0) + 1
#To count the total number of words in the file, we can add up the frequencies in the histogram:
def total_words(h):
return sum(h.values())
#The number of different words is just the number of items in the dictionary:
def different_words(h):
return len(h)
#To find the most common words, we can apply the DSU pattern; most_common takes a histogram and returns a list of word-frequency tuples, sorted in reverse order by frequency:
def most_common(h):
t = []
for key, value in h.items():
t.append((value, key))
t.sort(reverse=True)
return t
def print_most_common(hist, num=10):
t = most_common(hist)
print 'The most common words are:'
for freq, word in t[0:num]:
print word, '\t', freq
def subtract(d1, d2):
"""Takes dictionaries d1 and d2 and returns a new dictionary that contains
all the keys from d1 that are not in d2. Since we do not really care about
the values, we set them all to None.
"""
res = dict()
for key in d1:
if key not in d2:
res[key] = None
return res
import random
def random_word(h):
"""To choose a random word from the histogram, the simplest algorithm is to
build a list with multiple copies of each word, according to the observed
frequency, and then choose from the list.
"""
t = []
for word, freq in h.items():
# The expression [word] * freq creates a list with freq copies of the
# string word.
# The extend method is similar to append except that the argument is a
# sequence.
t.extend([word] * freq)
return random.choice(t)
hist = process_file('emma.txt')
print 'Total number of words:', total_words(hist)
print 'Number of different words:', different_words(hist)
print_most_common(hist)
#words = process_file('words.txt')
#diff = subtract(hist, words)
#print "The words in the book that aren't in the word list are:"
#for word in diff.keys():
# print word,
print "RANDOM_WORD: ", random_word(hist)
| true |
0c4515b106bc0f5e5510769e4cc5a240a595db31 | erpragatisinghpython/Python-Basic | /Tut-all-py/1find_factors.py | 698 | 4.46875 | 4 | ##Python Program to Find Factors of Number
# Python Program to find the factors of a number
# define a function
def print_factors(x):
"""This function takes a
number and prints the factors"""
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
# take input from the user
num = int(input("Enter a number: "))
print_factors(num)
##In this program we take a number from the user and display its factors using the function print_factors(). In the function, we use a for loop to iterate from 1 to that number and only print it if, it perfectly divides our number. Here, print_factors() is a user-defined function.
| true |
0aec8ef1436315e6e697d976a44fe4775de9c20d | erpragatisinghpython/Python-Basic | /Tut-all-py/prime_in_interval.py | 329 | 4.21875 | 4 | ##Python Program to Print all Prime Numbers in an Interval
num = int(input("Enter a number: "))
for n in range (2, num+1):
for i in range (2, n):
if (n % i) == 0:
print (n ,"is a prime not a number")
break
else:
print (n, "is a pime number")
| false |
7965497aafd667145bfd448a11abdb9bbd523571 | erpragatisinghpython/Python-Basic | /Tut-all-py/string_demo.py | 2,212 | 4.125 | 4 | print(""" Siring Demo
""")
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
print("\n updateing string ")
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
print(""" Escape Characters
\a 0x07 Bell or alert
\b 0x08 Backspace
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical TabSpace
""")
print("""String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −""")
print("""String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello
[] Slice - Gives the character from the given index a[1] will give e
[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given string H in a will give 1
not in Membership - Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the
raw string operator,
the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.
print r'\n' prints \n and print R'\n'prints \n""")
print("\n String Formatting Operator\n")
print ("My name is %s and weight is %d kg!" % ('Pragati', 21) )
print("\n Triple Quotes \n")
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
print("\n Unicode String \n")
print(u'Hello, world!')
| true |
b30f2a4792970ddc21fc76d502916508e3f13f50 | zsl0001/python17 | /api/page2.py | 1,501 | 4.15625 | 4 | def paginate(page, size=20):
"""
数据库 分页 和 翻页 功能函数
@param page: int or str 页面页数
@param size: int or str 分页大小
@return: dict
{
'limit': 20, 所取数据行数
'offset': 0, 跳过的行数
'before': 0, 前一页页码
'current': 1, 当前页页码
'next': 2 后一页页码
}
"""
if not isinstance(page, int):
try:
page = int(page)
except TypeError:
page = 1
if not isinstance(size, int):
try:
size = int(size)
except TypeError:
size = 20
if page > 0:
page -= 1
data = {
"limit": size,
"offset": page * size,
"before": page,
"current": page + 1,
"next": page + 2
}
return data
if __name__ == '__main__':
result = paginate(None, None)
print(type(result))
result = paginate(0, 20)
print(result)
result = paginate(1, 50)
print(result)
result = paginate(3, 20)
print(result)
result = paginate("3", "30")
print(result)
"""
{'limit': 20, 'offset': 0, 'before': 0, 'current': 1, 'next': 2}
{'limit': 20, 'offset': 0, 'before': 0, 'current': 1, 'next': 2}
{'limit': 50, 'offset': 0, 'before': 0, 'current': 1, 'next': 2}
{'limit': 20, 'offset': 40, 'before': 2, 'current': 3, 'next': 4}
{'limit': 30, 'offset': 60, 'before': 2, 'current': 3, 'next': 4}
"""
| false |
5105c376949b8d7229b9c66367092f2558d7f45b | npryce/code-guide | /examples/button-blink.py | 1,659 | 4.34375 | 4 | #!/usr/bin/env python3
#|| Button Blink
#|| ============
#||
#|| This example extends the [blink program](blink) to read from a
#|| GPIO input pin connected to a push-button. The LED will only
#|| blink while you are holding the button down.
from itertools import cycle
from time import sleep
#| [5] You must import the GPIO pins and direction constants In and
#| Out from quick2wire.gpio before you can use them
from quick2wire.gpio import pins, In, Out
#|.
#| [4] Get hold of the input and output pins from the bank of GPIO
#| pins.
button = pins.pin(0, direction=In)
led = pins.pin(1, direction=Out)
#|.
#| [6] The with statement acquires the button and led pins and ensures
#| that they are always released when the body of the statement
#| finishes, whether successfully or by an exception being thrown.
with button, led:
#|.
print("ready")
#| [1] This is the core of the program: an infinite loop that
#| reads from and writes to the GPIO pins connected to the button
#| and LED. Each time round the loop, _blink_state_ alternates
#| between 1 (voltage high) and 0 (voltage low).
for blink_state in cycle([1,0]):
#| [2] Read the state of the button pin multiply it with
#| _blink_state_ to get the new state to be written to the LED
#| pin. When both the button pin and _blink_state_ are 1,
#| this will set the LED pin to 1. If either are 0, this will
#| set the LED pin to 0.
led.value = blink_state and button.value
#|.
#| [3] Sleep a bit before the next iteration, so that the LED
#| blinks on and off once per second.
sleep(0.5)
#|.
| true |
6ae60b6e70c34d84f2b78e16f2bfcf9f61cad7e1 | brzzzz/hw1.2 | /hw 1.10-13.py | 2,701 | 4.375 | 4 | import math
# ---------------------------------------------------
# Написать функцию, которая будет переводить градусы в радианы. Используя эту функцию вывести
# на экран значения косинусов углов в 60, 45 и 40 градусов.
def degrees_to_radians(degrees):
result = degrees * math.pi / 180
return result
var = degrees_to_radians(60)
var1 = degrees_to_radians(45)
var2 = degrees_to_radians(40)
result1 = math.cos(var)
result2 = math.cos(var1)
result3 = math.cos(var2)
print('Результат фунции перевода градусов в радианы при 60 будет равен %f, при 45 будет равен %f и 40 равен %f,' %
(var, var1, var2))
print('при этом значения консинсов углов для 60 градусов будут равны %.1f, для 45 равно %f и для 40 равно %f'
% (result1, result2, result3))
# ----------------------------------------------------
# Написать функцию, которая рассчитывает сумму всех цифр некоторого трехзначного числа, введенного
# пользователем в консоли, без использования операторов цикла.
# Реализовать задачу без использования строк
def amount(number):
numeral = number // 100
numeral1 = number % 100 // 10
numeral2 = number % 10
result = numeral + numeral2 + numeral1
return result
result1 = amount(123)
print('Результат суммы трёхзначного числа 123 будет равен %d' % result1)
# ----------------------------------------------------
# Пользователь вводит длины катетов прямоугольного треугольника.
# Написать функцию, которая вычислит площадь треугольника и его периметр.
# Результат работы функции вывести на печать.
def triangle_square_and_perimeter(a, b):
square = 0.5 * a * b
perimeter = a + b + math.sqrt(a**2 + b**2)
print('Площадь треугольника и его периметр равны %.d сантиметров квадратных и %.d сантиметров'
% (square, perimeter))
return square, perimeter
a = (int(input('Введите длину первого катета:')))
b = (int(input('Введите длину второго катета:')))
triangle_square_and_perimeter(a, b)
| false |
4bd58792abd15f0d5f315530bb56de049275e748 | rosavage/etudes | /python/p2.py | 228 | 4.15625 | 4 | #!/usr/bin/python3
"""Character Counter"""
def charcount():
str = input("What is the input string? ")
length = len(str)
print("{} has {} characters.".format(str,length))
if __name__=="__main__":
charcount()
| true |
28521a9496b6f5935ee132f946e0fc9b52269d45 | mathstronauts/IGNITE_TechExplore_2021_2022 | /python_activities/3_loops/2_word_guess_game_for.py | 974 | 4.46875 | 4 | """
* Copyright (C) Mathstronauts. All rights reserved.
* This information is confidential and proprietary to Mathstronauts and may not be used, modified, copied or distributed.
"""
# Word guessing game - For Loop
import mathstropy
random_word = mathstropy.randomword() # random word generator function
chances = 3 # number of trys to guess the number
hint = mathstropy.wordmask(random_word)
print("Your job is to guess the secret word.")
print("You will have", str(chances), "chances to guess.")
print(hint)
for i in range(chances): # the for loop will run 3 times, the upper limit is one above the highest number we want to count to
guess = input("Enter guess: ") #
if guess.lower() != random_word: # add this after, simple for loop just asking for guess
print("Sorry, guess incorrect.")
else:
print("You won!")
break
# once for loop is completed
print("The secret word was", random_word)
| true |
e40e61947aba362506f8413bbdd7d85196c904c9 | mathstronauts/IGNITE_TechExplore_2021_2022 | /python_activities/1_intro_to_python/7_shell_demo_math_operations.py | 1,523 | 4.3125 | 4 | """
* Copyright (C) Mathstronauts. All rights reserved.
* This information is confidential and proprietary to Mathstronauts and may not be used, modified, copied or distributed.
"""
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = 10
>>> b = 5
>>> c = 2
>>> d = 3
>>> sum_a_b = a + b
>>> sum_a_b
15
>>> a-d
7
>>> b*2
10
>>> c/2
1.0
>>> bedmas = (a+b)-a/c*d
>>> bedmas
0.0
>>> abs(-45) #absolute function
45
>>> abs(-10) #absolute function
10
>>> 2**2 #exponents
4
>>> 2**3 #exponents
8
>>> 2**4 #exponents
16
>>> 25**1/2 #square root wrong
12.5
>>> 25**(1/2) #square root correct (BEDMAS)
5.0
>>> import math #import the math library to really advance stuff
>>> math.sqrt(25) #square root
5.0
>>> math.sqrt(17) #square root
4.123105625617661
>>> math.sin(45) #sin...but result is weird
0.8509035245341184
>>> math.sin(90) #what is going on?
0.8939966636005579
>>> angle_rad = math.radians(90) #math trig functions accepts radians so we have to convert degrees to radians
>>> angle_rad
1.5707963267948966
>>> math.sin(angle_rad)#sin...thats more like it
1.0
>>> math.cos(angle_rad) #sin...result is basically 0
6.123233995736766e-17
>>> angle_rad = math.radians(45) #change 45 degrees
>>> math.sin(angle_rad)
0.7071067811865475
>>> math.cos(angle_rad)
0.7071067811865476
>>> math.tan(angle_rad) #tan...result is basically 1
0.9999999999999999
>>>
| true |
d706a7bbe09724cf7742957b109567713a990859 | mathstronauts/IGNITE_TechExplore_2021_2022 | /python_activities/2_conditional_execution/2_simple_calculator_TEMPLATE.py | 1,252 | 4.25 | 4 | """
* Copyright (C) Mathstronauts. All rights reserved.
* This information is confidential and proprietary to Mathstronauts and may not be used, modified, copied or distributed.
"""
#print greetings
print('Welcome to my simple calculator!')
#get user inputs
operation = input('Please enter operation(+,-,*,/,**): ')
if (conditional statment):
base = input('Please enter base integer: ')
exp = input('Please enter exponent: ')
else:
first_num = input('Please enter first integer: ')
second_num = input('Please enter second integer: ')
#if sum operation
if(condition statement):
#sum the two numbers
#output the sum to the user
#if subtract operation
elif(condition statement):
#subtract the two numbers
#output the difference to the user
#if multiply operation
elif(condition statement):
#multiply the two numbers
#output the product to the user
#if divide operation
elif(condition statement):
#divide the two numbers
#output the quotient to the user
#if exponent operation
elif(condition statement):
#base to the power of exponent
#output the total to the user
#operation not valid
else:
print()
| true |
690ed27a8e9bd0d3a72a4a452f4ba75dc981c452 | EpsilonHF/Leetcode | /Python/443.py | 1,128 | 4.125 | 4 | """
Given an array of characters, compress it in-place.
The length after compression must always be smaller than
or equal to the original array.
Every element of the array should be a character (not int)
of length 1.
After you are done modifying the input array in-place, return
the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should
be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is
replaced by "c3".
"""
class Solution:
def compress(self, chars: List[str]) -> int:
read = write = 0
l = len(chars)
while read < l:
ch = chars[read]
count = 0
while read < l and chars[read] == ch:
read += 1
count += 1
chars[write] = ch
write += 1
if count > 1:
for c in str(count):
chars[write] = c
write += 1
return write
| true |
25c73943bd291c07d141793b13f72977bd465f13 | EpsilonHF/Leetcode | /Python/1042.py | 1,057 | 4.25 | 4 | """
You have N gardens, labelled 1 to N. In each garden, you want
to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional
path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into
or leaving it.
Your task is to choose a flower type for each garden such that,
for any two gardens connected by a path, they have different
types of flowers.
Return any such a choice as an array answer, where answer[i] is
the type of flower planted in the (i+1)-th garden. The flower
types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.
Example 1:
Input: N = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]
"""
class Solution:
def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]:
G = [[] for i in range(N)]
ret = [0] * N
for x, y in paths:
G[x - 1].append(y - 1)
G[y - 1].append(x - 1)
for i in range(N):
ret[i] = ({1, 2, 3, 4} - {ret[j] for j in G[i]}).pop()
return ret
| true |
2702678a93585e66e89f4617f388281835eaf60f | EpsilonHF/Leetcode | /Python/965.py | 666 | 4.21875 | 4 | """
A binary tree is univalued if every node in the tree has the
same value.
Return true if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1]
Output: true
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
def dfs(node, val):
if not node:
return True
if node.val != val:
return False
return dfs(node.left, val) and dfs(node.right, val)
return dfs(root, root.val)
| true |
3b24a46d61197792a8e42c044240c32e83057389 | EpsilonHF/Leetcode | /Python/492.py | 1,081 | 4.375 | 4 | """
For a web developer, it is very important to know how to
design a web page's size. So, given a specific rectangular
web page’s area, your job by now is to design a rectangular
web page, whose length L and width W satisfy the following
requirements:
1. The area of the rectangular web page you designed must equal
to the given target area.
2. The width W should not be larger than the length L, which
means L >= W.
3. The difference between length L and width W should be as
small as possible.
You need to output the length L and the width W of the web
page you designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation:
The target area is 4, and all the possible ways to construct it
are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to
requirement 3, [4,1] is not optimal compared to [2,2]. So the
length L is 2, and the width W is 2.
"""
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(area ** 0.5)
while area % w:
w -= 1
return [area//w, w]
| true |
3f138808494abc8e6d6357e1aaed0d14cdd81bcf | EpsilonHF/Leetcode | /Python/717.py | 827 | 4.25 | 4 | """
We have two special characters. The first character can be
represented by one bit 0. The second character can be represented
by two bits (10 or 11).
Now given a string represented by several bits. Return whether
the last character must be a one-bit character or not. The given
string will always end with a zero.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
"""
class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
pos = 0
onebit = False
while pos < len(bits):
if bits[pos]:
pos += 2
onebit = False
else:
pos += 1
onebit = True
return onebit
| true |
3b65a0545f72ab6aa1fb14e815c659ba604aab6e | EpsilonHF/Leetcode | /Python/326.py | 298 | 4.15625 | 4 | """
Given an integer, write a function to determine if it is a
power of three.
Example 1:
Input: 27
Output: true
"""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 1:
if n % 3:
return False
n //= 3
return n == 1
| true |
52fa5bca59476d7de3b60ca7a8cb7b3b76665862 | EpsilonHF/Leetcode | /Python/830.py | 969 | 4.1875 | 4 | """
In a string S of lowercase letters, these letters form consecutive
groups of the same character.
For example, a string like S = "abbxxxxzyy" has the groups "a",
"bb", "xxxx", "z" and "yy".
Call a group large if it has 3 or more characters. We would like
the starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting 3 and
ending positions 6.
"""
class Solution:
def largeGroupPositions(self, S: str) -> List[List[int]]:
count = 1
ret = []
start = 0
for i in range(1, len(S)):
if S[i] == S[i-1]:
count += 1
else:
if count >= 3:
ret.append([start, i-1])
start = i
count = 1
if count >= 3:
ret.append([start, len(S)-1])
return ret
| true |
5acbb87fa8fbdd32ebf34e29aaab050d1df5f66d | EpsilonHF/Leetcode | /Python/125.py | 425 | 4.25 | 4 | """
Given a string, determine if it is a palindrome, considering
only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string
as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
s = [i.lower() for i in s if i.isalpha() or i.isdigit()]
return s == s[::-1]
| true |
fb6c4c9801abd2da9bf376fb99c31dc50bc082f8 | EpsilonHF/Leetcode | /Python/836.py | 696 | 4.15625 | 4 | """
A rectangle is represented as a list [x1, y1, x2, y2], where
(x1, y1) are the coordinates of its bottom-left corner, and
(x2, y2) are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is
positive. To be clear, two rectangles that only touch at the
corner or edges do not overlap.
Given two (axis-aligned) rectangles, return whether they overlap.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
"""
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
return not (rec1[2] <= rec2[0] or rec1[3] <= rec2[1] or
rec1[0] >= rec2[2] or rec1[1] >= rec2[3])
| true |
a471fe8c76bbcc84f85143de38578e258f28b005 | EpsilonHF/Leetcode | /Python/766.py | 816 | 4.3125 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right
has the same element.
Now given an M x N matrix, return True if and only if the matrix
is Toeplitz.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
"""
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
groups = {}
for row, lst in enumerate(matrix):
for col, val in enumerate(lst):
if row-col not in groups:
groups[row-col] = val
elif groups[row-col] != val:
return False
return True
| true |
5c9294fd549fd50ba112cf24d41c7ead06e8ced2 | EpsilonHF/Leetcode | /Python/455.py | 1,192 | 4.125 | 4 | """
Assume you are an awesome parent and want to give your children
some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor gi, which is the minimum size of
a cookie that the child will be content with; and each cookie j
has a size sj. If sj >= gi, we can assign the cookie j to the
child i, and the child i will be content. Your goal is to maximize
the number of your content children and output the maximum number.
Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.
Example 1:
Input: [1,2,3], [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors
of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1,
you could only make the child whose greed factor is 1 content.
You need to output 1.
"""
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
count = j = 0
for cookie in s:
if j == len(g):
break
if cookie >= g[j]:
j += 1
count += 1
return count
| true |
e36f7f835a9f660a32adfa4ab6e91d3edf7b17f2 | EpsilonHF/Leetcode | /Python/160.py | 1,189 | 4.125 | 4 | """
Write a program to find the node at which the intersection
of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5],
listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8
(note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head
of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before
the intersected node in A; There are 3 nodes before the
intersected node in B.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA is None or headB is None:
return None
pa, pb = headA, headB
while pa != pb:
pa = headB if pa is None else pa.next
pb = headA if pb is None else pb.next
return pa
| true |
4d28d82e04df7bac49a2e680fb21d7b94545f3ba | EpsilonHF/Leetcode | /Python/8.py | 2,071 | 4.15625 | 4 | """
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as
necessary until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial
plus or minus sign followed by as many numerical digits as possible,
and interprets them as a numerical value.
The string can contain additional characters after those that
form the integral number, which are ignored and have no effect
on the behavior of this function.
If the first sequence of non-whitespace characters in str is not
a valid integral number, or if no such sequence exists because
either str is empty or it contains only whitespace characters,
no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range: [−231, 231 − 1].
If the numerical value is out of the range of representable values,
INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
Input: "42"
Output: 42
"""
class Solution:
def myAtoi(self, str: str) -> int:
flag = 1
ret = 0
count = 0
valid = True
string = str.strip()
if string == "":
return 0
if not string[0].isdigit() and string[0] != "+" and string[0] != '-':
return 0
for c in string:
if c == "+" and valid:
count += 1
continue
elif c == '-' and valid:
count += 1
flag = -1
elif c.isdigit():
ret = ret * 10 + ord(c) - 48
valid = False
else:
break
if count > 1:
return 0
if flag * ret > (1 << 31) - 1:
return (1 << 31) - 1
elif flag * ret < -(1 << 31):
return -(1 << 31)
else:
return flag * ret
| true |
5a77c3abcdf015eebc6088f47823a898431881a4 | EpsilonHF/Leetcode | /Python/89.py | 737 | 4.125 | 4 | """
The gray code is a binary numeral system where two successive values
differ in only one bit.
Given a non-negative integer n representing the total number of bits
in the code, print the sequence of gray code. A gray code sequence
must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
"""
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
ans = [0]
for i in range(n):
ans += [2**i + num for num in ans[::-1]]
return ans
| true |
884c368d90dc713f40869165018488bee476d62a | EpsilonHF/Leetcode | /Python/543.py | 930 | 4.375 | 4 | """
Given a binary tree, you need to compute the length of the
diameter of the tree. The diameter of a binary tree is the
length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
path = 0
def dfs(node):
if node is None:
return 0
nonlocal path
left = dfs(node.left)
right = dfs(node.right)
path = max(path, left + right)
return max(right, left) + 1
dfs(root)
| true |
d8bab72b3b7770f040fb3d97b00cd2d22f2fefce | thenileshunde/ProgrammingConcepts | /closures.py | 1,729 | 4.78125 | 5 | #############################################################################
''' Simple Definition: A closure is an INNER FUNCTION that remembers and has
access to variables in local scope in which it was created even after
the Outer Function has Finished Executing.'''
################################# Example 1 ##################################
def take_msg(message):
edited_msg = message + ' edited by '
def give_msg(name):
print(edited_msg + name) # accessing Varaible outside scope
return give_msg # Function being returned
print("Name of outer Function: ", take_msg.__name__)
print('-->Executing Outer Function')
result = take_msg('Python is Awesome') # assigning returned function
for i in range(3):
print('.')
print('-->Finished Executing Outer Function')
print('\n')
'''Here Outer Function has Finished Executing But Inner Function still has access
to variable craeted in its scope'''
print("Name of inner Function: ", result.__name__)
print('-->Executing Inner Function')
result('Nilesh Unde')
print('-->Finished Executing Inner Function\n')
################################# Example 2 ##################################
import logging
logging.basicConfig(filename='closures.log', level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info('Runnning "{}" with arguments {}'.format(
func.__name__, args))
print(func(*args))
return log_func
def add(*args):
sum = 0
for i in args:
sum = sum + i
return sum
def mul(*args):
mul = 1
for i in args:
mul = mul * i
return mul
add_logger = logger(add)
mul_logger = logger(mul)
add_logger(12, 4, 5, 87, 9, 32)
mul_logger(4, 78, 5, 8, 4)
| true |
32c42e7f1dbfb30ece40edf9dc5dfef5efe53ebc | kadedemytgithub103/Python_pg | /11-1.py | 672 | 4.1875 | 4 | import math
class Circle:
PI = 3.1415
def calc_circcumference(self,radius):
res = 2* Circle.PI *radius
return math.floor(res * 10 ** 3) /(10 **3)
def calc_area(self,radius):
res = 2* Circle.PI *radius **2
return math.floor(res * 10 ** 3) /(10 **3)
class Main:
def execute(self):
circle = Circle()
radius = int(input("半径を整数値で入力"))
circumference = circle.calc_circcumference(radius)
area = circle.calc_area(radius)
print("円周の長さは{}です。".format(circumference))
print("円の面積は{}です。".format(area))
main = Main()
main.execute() | false |
4dcf37d6312559de251fedea17d2952d972abbe0 | AwaisMuhammadi/Selection-Sort | /selection sort.py | 871 | 4.25 | 4 |
list_of_numbers = []
# swap function take two indexes and swap the elements of those indexes
def swap(a, b):
c = list_of_numbers[a]
list_of_numbers[a] = list_of_numbers[b]
list_of_numbers[b] = c
#selection sort function
def selection_sort():
n = len(list_of_numbers)
i = 0
while i < n:
j = 0
max_index = 0
while j < n-i:
if list_of_numbers[max_index] < list_of_numbers[j]:
max_index = j
j = j + 1
swap(max_index, n - i-1) # Swap the maximum number with last element of unsorted subarray
i = i + 1
#Take list elements from user
def take_input(n):
for i in range(n):
list_of_numbers.append(input("Enter number:"))
take_input(int(input("Enter Length of the list:")))
selection_sort()
print("Sorted List:")
print(list_of_numbers) # print sorted array
| true |
a063f2357ff7bea7b706ef759421eea600191c83 | dinesh1987/python-samples | /OOPS/basic_class_obj.py | 617 | 4.3125 | 4 | #OOP-Exer-2
#Start writing your code here
class Employee:
def __init__(self):
print("An object has been created for employee class")
self.name=None
self.age=None
self.salary=None
print("----------------------------------------------------------")
emp1=Employee()
emp1.name="Jack"
emp1.age=24
emp1.salary=30000
print("Name:",emp1.name,",Age:",emp1.age,",Salary:",emp1.salary)
print("----------------------------------------------------------")
emp2=Employee()
emp2.name="Jill"
emp2.age=27
emp2.salary=40000
print("Name:",emp2.name,",Age:",emp2.age,",Salary:",emp2.salary)
| false |
9f80469c27f6b47e0947c4ef419d7f24e3a6f213 | dhamejanishivam/Python-Backup | /oop_1.py | 597 | 4.21875 | 4 | # class student:
# pass
#
# shivam = student()
# larry = student()
#
# shivam.name = "Shivam"
# shivam.std = 11
# shivam.section = 2
#
# print(shivam)
class Employee:
no_of_leaves = 10
shivam = Employee()
larry = Employee()
shivam.name = "Shivam"
shivam.salary = 455
shivam.role = "Instructer"
larry.name = "Rohan"
larry.salary = 0
larry.role = "Student"
# print(shivam.no_of_leaves)
Employee.no_of_leaves = 9 # To change a variable defined in class we have to use class name
print(larry.no_of_leaves)
print(larry.__dict__) # It print all variable of object in form of dictinary
| false |
f5227af30593ca08e6f4a7f917a3a4d7e7c51ecf | msahu2595/PYTHON_3 | /181_15_first_generators.py | 809 | 4.1875 | 4 | # create your first generators with generato function
# 1). generator function
# 2). generators comprehension
# 10, 1 to 10
# uses normal method
def nums(n):
for i in range(1,n+1):
print(i)
nums(10)
# useing generators
def numss(n):
for i in range(1,n+1):
yield(i) # can be used "yield i" also yield is not a function
for number in numss(10):
print(number)
# can be print no. of times
for number in numss(10):
print(number)
# using variable to assign generators on that
numbers = numss(10) # numbers variable have only one item at a time
for number in numbers:
print(number) # loop ---> 1-2-3-4-5-6-7-8-9-10-nothing
# after 10 ---> Nothing
# second time number variable dont have any no. so that cant print any no.
for number in numbers:
print(number)
| true |
8178601a1ec6bed49d8b32b674fc163cf7546ca7 | msahu2595/PYTHON_3 | /140_dict_comp.py | 320 | 4.125 | 4 | # dictionary comprehension
# square = {1:1, 2:4, 3:9}
square = {f"Square of {num} is":num**2 for num in range(1,11)}
print(square)
for k,v in square.items():
print(f"{k} : {v}")
# word count in string
str_1 = "manish kumar sahu"
word_count = {i:str_1.count(i) for i in str_1.replace(' ','')}
print(str_1)
print(word_count)
| false |
a5c151b08e5c3d2563cf4ac7dd61dcb85c2d78fc | msahu2595/PYTHON_3 | /158_iterators_vs_iterables.py | 641 | 4.3125 | 4 | # iterator vs iterables
numbers = [1,2,3,4] # tuples, strings ---> iterables
squares = map(lambda a : a**2, numbers) # iterator
# for i in numbers:
# print(i)
# number_iter = iter(numbers)
# print(next(number_iter))
# print(next(number_iter))
# print(next(number_iter))
# print(next(number_iter))
# # print(next(number_iter))
print(iter(numbers)) # list_iterator_object
print(next(squares)) # output ---> 1
print(next(squares)) # output ---> 4
print(next(squares)) # output ---> 9
print(next(squares)) # output ---> 16
# but when we pass numbers as argument with next function
print(next(numbers)) # list_object not an iterator
| false |
8c1cfcae24d77b49b21c941465ffa884978f4698 | msahu2595/PYTHON_3 | /list_inside_list_96.py | 314 | 4.15625 | 4 | # list inside list
matrix = [[1,2,3],[4,5,6],[7,8,9]] #2d list
# 3 items ---> 3 list ----> 3 items/list
print(matrix[2])
for sublist in matrix:
for i in sublist:
print(i)
# access list inside list values
print(matrix[1][0])
# find type of variable
s = "manish"
print(type(s))
print(type(matrix))
| true |
103bd2dd08422d3f3dcaf2488ecd4e3a9a340946 | netletic/pybites | /93/rps.py | 1,534 | 4.125 | 4 | from random import choice
defeated_by = dict(paper="scissors", rock="paper", scissors="rock")
CHOICES = list(defeated_by.keys())
lose = "{} beats {}, you lose!"
win = "{} beats {}, you win!"
tie = "tie!"
def _get_computer_move():
"""Randomly select a move"""
return choice(CHOICES)
def _get_winner(computer_choice, player_choice):
"""Return above lose/win/tie strings populated with the
appropriate values (computer vs player)"""
invalid = player_choice not in CHOICES
if invalid:
return "Invalid"
if computer_choice == player_choice:
return tie
player_loses = defeated_by[player_choice] == computer_choice
if player_loses:
return lose.format(computer_choice, player_choice)
player_wins = defeated_by[computer_choice] == player_choice
if player_wins:
return win.format(player_choice, computer_choice)
def game():
"""Game loop, receive player's choice via the generator's
send method and get a random move from computer (_get_computer_move).
Raise a StopIteration exception if user value received = 'q'.
Check who wins with _get_winner and print its return output."""
print("Welcome to Rock Paper Scissors")
while True:
player_choice = yield
computer_choice = _get_computer_move()
if player_choice == "q":
raise StopIteration
outcome = _get_winner(computer_choice, player_choice)
print(outcome)
if __name__ == "__main__":
g = game()
next(g)
g.send("paper") | true |
f4e2bd89cf8fad89ca26eae2d10ca1a60a717d01 | netletic/pybites | /53/text2cols.py | 834 | 4.21875 | 4 | from itertools import zip_longest
from textwrap import wrap, fill
COL_WIDTH = 20
def text_to_columns(text: str):
"""Split text (input arg) to columns, the amount of double
newlines (\n\n) in text determines the amount of columns.
Return a string with the column output like:
line1\nline2\nline3\n ... etc ...
See also the tests for more info."""
paragraphs = (line.strip() for line in text.split("\n\n"))
wrapped = (wrap(p, width=COL_WIDTH) for p in paragraphs)
lines = ("\t".join(line) for line in zip_longest(*wrapped, fillvalue=""))
return "\n".join(lines)
if __name__ == "__main__":
text = """My house is small but cosy."""
print(text_to_columns(text))
text = """My house is small but cosy.
It has a white kitchen and an empty fridge."""
print(text_to_columns(text))
| true |
ab2e2e72fe5e405117c00aab18e31bc59537e1d0 | lucadamian13/Class-Code | /rando_turt.py | 1,457 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 10:51:17 2020
@author: Dr. Z
Creates a turtle that randomly wanders around the screen using a WHILE LOOP.
Has a conditional block that keeps it from going out of bounds.
"""
import turtle, random #didja know you can do this? pretty cool.
w=600
h=600
turtle.setup(w,h) # start with calling setup to turn on listeners
# define variables
panel=turtle.Screen()
randTurt = turtle.Turtle(shape='turtle') # make it a turtle, cuz they're cute!
running = True # set up boolean for our while loop
pace = 25
span = 60
# set up the turtle
randTurt.color('green')
randTurt.shapesize(2) # make it big so we can see it clearly
randTurt.up() # don't draw, just move around
randTurt.speed(10)
randTurt.width(3) # made it bigger for visibility
while running:
randTurt.forward(pace) # go forward a random amount of times
randTurt.left(random.randint(-span,span)) # turn randomly left or right
# define our tests for the while loop
# use w and h instead of hard coding!
ybounds = randTurt.ycor()<-h/2 or randTurt.ycor()>h/2
xbounds = randTurt.xcor()<-w/2 or randTurt.xcor()>w/2
if xbounds or ybounds:
# moves the turtle back to center if it wanders out of bounds
randTurt.up() # don't draw the path home.
randTurt.home()
panel.mainloop() #keeps listeners on so we can get interactivity\
turtle.done() # turtle clean up
| true |
a68cdde8aa0206f30d557327448a961f35a2df10 | estevg/curso-de-python | /modulo_uno/ejemplo_dos.py | 249 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# Version en Python 2
# name = str(raw_input('¿ Cual es tu nombre ?'))
# raw_input()
# print('Hola ' + name + '!')
# Version en python 3
name = str(input('¿ Cual es tu nombre ?'))
# raw_input()
print('Hola ' + name + '!') | false |
3ea32bafd7f10592a6c60a8328ce0846de0bdd07 | Tejas-Naik/Python-ZTM-course-Andrei-Negoie | /Decorators/decorators.py | 1,446 | 4.34375 | 4 |
# the syntax of Decorators is they have @name_of_decorator
# @classmethod
# @staticmethod
def hello():
print('Hello')
greet = hello()
del hello
print(greet)
# functions in Python are the First Class Citizen
# they act as the Variables
def hello(func):
func()
def greet():
print("Helloooo")
print(hello(greet))
# TIP: Decorators Supercharge our functions
# Higher Order Function
# Higher order function is a function that accepts a function as a Parameter
# or a function that returns another function ex.map(), filter(), reduce()
# our first decorator
print("Decorators (****************************************)")
def my_decorator(func):
def wrap():
print("********")
func()
print("********")
return wrap
@my_decorator
def add_decorator():
print("Helllooo")
add_decorator()
print("Decorators (********************input********************)")
def my_decorator(func):
def wrap(x):
print("********")
func(x)
print("********")
return wrap
@my_decorator
def add_decorator(greet):
print(greet)
add_decorator('hii')
print("*******************Easy trick*******************")
def my_decorator(func):
def wrap(*args, **kwargs):
print("********")
func(*args, **kwargs)
print("********")
return wrap
@my_decorator
def add_decorator(greet, emoji='😁😁'):
print(greet, emoji)
add_decorator('hii')
| false |
1b86e52f9edbe0eaa8eb86055bed926897d8ae57 | danvc/PY4E_exercises | /RateHoursWithFunction.py | 1,000 | 4.34375 | 4 | #4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
def computepay(h,r):
payRate = 40 * r
remainder = 0
extraRate = 0
if h > 40:
remainder = h - 40
extraRate = r + (r/2)
return payRate + (remainder * extraRate)
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
p = computepay(float(hrs),float(rate))
print(p)
| true |
c1968fa25638a3ba03211e1e7260b3bdd8486597 | jaehojang825/CS-313E | /Pancake.py | 1,967 | 4.34375 | 4 | #File: Pancake.py
#Description: representation of the pancake sort
#Student's Name: Jaeho Jang
#Student's UT EID: jj36386
#Course Name: CS 313E
#Unique Number: 50300
#Date Created: 2/21/20
#Date Last Modified: 2/21/20
#finds largest pancake and created index for it
def findLargest(pancake,index):
largest_pan=pancake[index]
largest_ind=index
for i in range(index):
if pancake[i]>largest_pan:
largest_pan=pancake[i]
largest_ind=i
return largest_ind
#flip pancake at index to flip to top
def flip(pancake,index):
new_pan=pancake[:(index+1)]
new_pan.reverse()
new_pan+=pancake[(index+1):]
return new_pan
# Input: pancakes is a list of positive integers
# Output: a list of the pancake stack each time you
# have done a flip with the spatula
# this is a list of lists
# the last item in this list is the sorted stack
def sort_pancakes(pancake):
every_flip=[]
for i in reversed(range(len(pancake))):
pancake=flip(pancake,findLargest(pancake,i))
pancake=flip(pancake,i)
every_flip.append(pancake)
return every_flip
def main():
#open the file pancakes.txt for reading
in_file = open ("./pancakes.txt", "r")
line = in_file.readline()
line = line.strip()
line = line.split()
print (line)
pancakes = []
for item in line:
pancakes.append (int(item))
# print content of list before flipping
print ("Initial Order of Pancakes = ", pancakes)
# call the function to sort the pancakes
every_flip = sort_pancakes ( pancakes )
# print the contents of the pancake stack after
# every flip
for i in range (len(every_flip)):
print (every_flip[i])
# print content of list after all the flipping
print ("Final Order of Pancakes = ", every_flip[-1])
if __name__ == "__main__":
main() | true |
044ad1cdcbeb09bfc699b7a037c8feb25dd2461a | NewmanD12/Code_Immersives_Assignments | /assignments/Activity9.3-DakotaNewman.py | 692 | 4.25 | 4 | # Activity 9.3
# Write a function called isSorted which will be passed in as a list of numbers
# Your functions job is to determine if the list in the need of being sorted, or if it already came sorted
# Your function should return a boolean determining whether or not that is the case
sortedList = [1, 4, 5, 6, 7]
unsortedList = [83, 23, 198, 84]
def isSorted(list):
count = 0
for i in range(len(list)):
if(list[i] < list[i + 1]):
# print(list[i])
count += 1
if (count == len(list) -1):
print("This list is sorted already")
return True
else:
print("This list needs sorted")
return False
isSorted(sortedList)
isSorted(unsortedList) | true |
9f0272b132f6554d5efd35ad839c72989b18db28 | NewmanD12/Code_Immersives_Assignments | /assignments/Activity10.3-DakotaNewman.py | 2,868 | 4.1875 | 4 | import random
import statistics
# Activity 10.3 Create a function that plays rock paper scissors with you...
# You are to ask to user for input
# If the user inputs "Rock" -> "scissors" will lose, and 'Paper' will win
# If the user inputs 'Paper' -> 'Rock' will lose, and 'Scissor' will win
# If the user inputs 'Scissors' -> 'paper' will lose, and 'Rock' will win
def rockPaperScissors():
userInput = input("Please take a guess ").lower().replace(' ', '')
computerPick = ""
computerNum = random.randrange(1, 4)
# Logic for computer taking it's guess
if(computerNum == 1):
computerPick = 'rock'
if(computerNum == 2):
computerPick = 'paper'
if(computerNum == 3):
computerPick = 'scissors'
# Logic for actually playing
if(userInput == 'rock' and computerPick == 'paper'):
print(f"You lose, {computerPick} beats {userInput}")
elif(userInput == 'paper' and computerPick == 'scissors'):
print(f'You lose, {computerPick} beat {userInput}')
elif(userInput == 'scissors' and computerPick == 'rock'):
print(f'You lose, {computerPick} beats {userInput}')
elif(userInput == computerPick):
print("You guessed the same, try again")
else:
print(f"You win! {userInput} beats {computerPick}")
# rockPaperScissors()
def rockPaperScissors2():
dictOfGuesses = {
'1' : 'rock',
'2' : 'paper',
'3' : 'scissors'
}
userInput = input('Input your guess ').lower().replace(' ', '')
# print(userInput)
computerNum = random.randrange(1, 4)
computerNumToString = str(computerNum)
computerGuess = dictOfGuesses[computerNumToString]
# print(computerGuess)
if(userInput == 'rock' and computerGuess == 'paper'):
print(f"You lose, {computerGuess} beats {userInput}")
elif(userInput == 'paper' and computerGuess == 'scissors'):
print(f'You lose, {computerGuess} beats {userInput}')
elif(userInput == 'scissors' and computerGuess == 'rock'):
print(f'You lose, {computerGuess} beats {userInput}')
elif(userInput == computerGuess):
print("You guessed the same, try again")
else:
print(f"You win! {userInput} beats {computerGuess}")
# rockPaperScissors2()
def rockPaperScissors3():
myGuess = input('Input your guess ').lower().replace(' ', '')
computerOptions = ['rock', 'paper', 'scissors']
computerGuess = random.choice(computerOptions)
if(myGuess == 'rock' and computerGuess == 'paper'):
print(f"You lose, {computerGuess} beats {myGuess}")
elif(myGuess == 'paper' and computerGuess == 'scissors'):
print(f'You lose, {computerGuess} beats {myGuess}')
elif(myGuess == 'scissors' and computerGuess == 'rock'):
print(f'You lose, {computerGuess} beats {myGuess}')
elif(myGuess == computerGuess):
print("You guessed the same, try again")
else:
print(f"You win! {myGuess} beats {computerGuess}")
# print(computerGuess)
rockPaperScissors3()
| true |
c9fb901e791ec5210aad24174a0d32dcf6ab9369 | harishdasari1595/Personal_projects | /Algorithms and Datastructure/Trees/count_nodes_in_a_binarytree.py | 1,739 | 4.1875 | 4 |
class Node:
def __init__(self, key):
self.left = None
self.data = key
self.right = None
self.rightThread = False
##############################################################
# Recursive code for counting the number of nodes in a tree
##############################################################
def count_nodes(root):
if root is None:
return 0
return (1 + (count_nodes(root.left) + count_nodes(root.right)))
###############################################################
# Iterative approach for counting the number of nodes in a tree
###############################################################
# Function for finding the leftmost node
def leftmost(node):
while node is not None and node.left is not None:
node = node.left
return node
# Iterative approach for counting the nodes in a binary tree
# Function for performing an inorder traversal
def inorder(root):
if root is None:
return
# Finding the leftmost node
curr = leftmost(root)
while curr != None:
print ("current node", curr.data)
if curr.rightThread != True:
print ("!!!!!!!!!!!!!!!!!")
curr = curr.right
print(curr.data)
else:
curr = leftmost(curr.right)
print("\n")
if __name__ == "__main__":
root = Node('A')
root.left = Node('B')
root.right = Node('C')
root.left.left = Node('D')
root.left.right = Node('E')
root.right.left = Node('F')
root.right.right = Node('G')
root.left.left.left = Node('H')
root.left.left.right = Node('I')
root.right.left.right = Node('J')
print ("-------------------------")
#inorder(root)
print(count_nodes(root))
| true |
73c32e53f9a4809f86d75addbdc6c42efbc25e97 | harishdasari1595/Personal_projects | /Algorithms and Datastructure/Trees/count_leaf.py | 1,565 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Applying DFS strategy for traversing the list
def recursive_count_leaves(root):
# Base case of the recursion
if root is None:
return
while root:
count = 0
if root.left is None and root.right is None:
count +=1
return count
return recursive_count_leaves(root.left) + recursive_count_leaves(root.right)
# Applying BFS strategy for traversing
def iterative_count_leaves(root):
if root is None:
return
count = 0
queue = []
queue.append(root)
while len(queue) > 0:
Node = queue.pop(0)
# Condition for checking the parent nodes in a tree
if Node.left != None:
queue.append(Node.left)
if Node.right != None:
queue.append(Node.right)
# Condition for checking the leaf_nodes
if Node.left == None and Node.right == None:
count += 1
return count
if __name__ == "__main__":
root = Node(50)
root.left = Node(45)
root.right = Node(55)
root.left.left = Node(25)
root.left.right = Node(65)
root.right.left = Node(75)
root.right.right = Node(96)
recursive_result = recursive_count_leaves(root)
print ("There are total {} leaf nodes in the tree ".format(recursive_result))
iterative_result = iterative_count_leaves(root)
print ("There are total {} leaf nodes in the tree ".format(iterative_result)) | true |
adbec74bb5425f60435f186eece4bdabcf136fc2 | harishdasari1595/Personal_projects | /Algorithms and Datastructure/Trees/indentical.py | 1,571 | 4.125 | 4 | class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Function for inserting nodes into the binary tree
def insert_node(root, data):
# Condition check for empty tree
if root is None:
root = Node(data)
# Inserting nodes smaller values in the left subtree
if data < root.data:
root.left = insert_node(root.left, data)
# Inserting nodes larger values in the right subtree
if data > root.data:
root.right = insert_node(root.right, data)
return root
# Recursive check for checking the trees are identical or not
def identical_check(root1 , root2):
# Base case for the recursion
if root1 is None and root2 is None:
return
# Recurseive equation of the identical check
if root1 and root2:
return(root1.data == root2.data and identical_check(root1.left, root2.left)
and identical_check(root1.right, root2.right))
if __name__ == "__main__":
# Constructing nodes of the binary tree
root1 = None
root2 = None
root1 = insert_node(root1, 15)
root1 = insert_node(root1, 12)
root1 = insert_node(root1, 20)
root1 = insert_node(root1, 10)
root1 = insert_node(root1, 18)
root2 = insert_node(root2, 15)
root2 = insert_node(root2, 12)
root2 = insert_node(root2, 20)
root2 = insert_node(root2, 10)
root2 = insert_node(root2, 18)
if identical_check:
print ("Both the trees are identical")
else:
print ("Both the trees are not identical")
| true |
6e5dfc4cdcc1a6eb4870b8db806b9509d16b7a91 | jaye-j/python | /DCDay3.py | 2,140 | 4.125 | 4 | #lists
# daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# # print(daysOfWeek[0])
# # daysOfWeek[0] = "Christmas Eve"
# # print(daysOfWeek[0])
# # print(len(daysOfWeek))
# daysOfWeek.append("Funday")
# print(daysOfWeek[7])
# todos = ["pet the cat", "go to work", "shop for groceries",
# "go home", "feed the cat"]
# todos.append("binge watch a show")
# todos.append("go to sleep")
# index = 0
# while index < len(todos):
# print(f"{index + 1}: {todos[index]}")
# index += 1
# a = [1, 2, 3, 4]
# b = [5, 6, 7, 8]
# print(a)
# print(b)
# print(a + b)
# todos = ["pet the cat", "go to work", "shop for groceries",
# "go home", "feed the cat"]
# todos.extend(["eat dinner", "shower"])
# print(todos)
#How do I delete items from a List?
# a = ["1", "2", "3"]
# del a[1]
# print(a)
# b = ["1", "2", "3"]
# del b[1:3]
# print(b)
# items = []
# to_add = input('What do you need to add to your to-do list today? ')
# while len(to_add) > 0:
# items.append(to_add)
# print(items)
# to_add = input('What do you need to add to your to-do list today? ')
# print(items)
# numbers = [1, 2, 3, 4, 5]
# print(numbers[2:])
# numbers = [1, 2, 3, 4, 5]
# # numbers.insert(3, 6)
# # print(numbers)
# # numbers.pop(2)
# # print(numbers)
# # while (len(numbers) > 0):
# # print(numbers.pop())
# # print(numbers)
# # print('finished')
# result = numbers.index(3)
# print(result)
# students = ['Jaye', 'Austin', 'Daniel', 'Alex']
# result = students.index('Daniel')
# print(result)
# myList = [1, 2, 3, 4, 5]
# newList = myList
# newList[0] = "changed"
# print(myList)
# print(newList)
# my_string = "Hello World"
# print(my_string[1:]) #prints "ello World"
# print(list(range(2, 100, 2)))
# name = "Jacob"
# for letter in name :
# print(letter)
# for index in range(10) :
# print(index)
# for index in range(1, 1002, 2) :
# print(index)
# for o_index in range(1, 11) :
# for i_index in range(1, 11) :
# print(str(o_index) + " X " + str(i_index) + " = " + str(o_index * i_index))
| true |
e173427059047a9da77072be260ef3fbef05990a | jaye-j/python | /pyHomework/hwday4.py | 1,761 | 4.34375 | 4 |
#Homework day 4 Thursday January 16th 2020
# Small
#1 Madlib function
# def madlib(name, subject):
# result = (f"{name}\'s favorite subject is {subject}.")
# return result
# print(madlib("Jaye", "Science"))
#2 Celsius to Farenheit conversion
# def convertTemp(C):
# F = (C * 9/5) + 32
# return F
# print(convertTemp(24))
#3 Farenheit to Celsius conversion
# def convertTemp(F):
# C = (F - 32) * 5/9
# return C
# print(convertTemp(70))
# #4 is_even
# def is_even(n):
# if n % 2 == 0:
# return True
# else:
# return False
# print(is_even(13))
# #5 is_odd
# def is_odd(is_even):
# if is_even == True:
# return False
# else:
# return True
# print(is_odd(is_even))
#6 only_evens
# def only_evens(list_of_numbers):
# even_numbers = []
# for i in list_of_numbers:
# if (i % 2) == 0:
# even_numbers.append(i)
# return(even_numbers)
# print(only_evens([23, 454, 32, 35, 122, 334, 5]))
#7 only_odds
# def only_odds(list_of_numbers):
# odd_numbers = []
# for i in list_of_numbers:
# if (i % 2) != 0:
# odd_numbers.append(i)
# return(odd_numbers)
# print(only_odds([23, 454, 32, 35, 122, 334, 5]))
# Medium
#1 Find the smallest number
# def smallest(list_nums):
# return min(list_nums)
# print(smallest([2, 45, 6, 7, 89]))
#2 find the largest number
# def largest(list_nums):
# return max(list_nums)
# print(largest([2, 45, 6, 7, 89]))
#3 Find the shortest String
# def shortest(string):
# return (min(string, key=len))
# print(shortest(['cat', 'jack', 'it']))
#4 Find the longest string
# def longest(string):
# return (max(string, key=len))
# print(longest(['cat', 'jack', 'it'])) | false |
53a2e34c2d431b003aa79abaecf41989d2c48556 | MikelShifrin/Python1 | /Students/Daniel/assignment 1.py | 487 | 4.1875 | 4 | #assignement 1
#write a program that asks and showsthe following from the user:
# 1. Your name
# 2. Your age
# 3. Your favorite color
# 4. Your favorite animal
name = input("please enter your name:\n")
age = input("please enter your age:\n")
color = input("what is your favorite color:\n")
animal = input("what is your favorite animal:\n")
print("Hello my name is" ,name)
print("I am" ,age, "years old")
print("My favorite color is" ,color)
print("My favorite animal is" ,animal)
| true |
5e5a12b3ebcd3593b1b2bbe8662b3149b5715336 | MikelShifrin/Python1 | /Lectures/Lecture1.py | 1,648 | 4.25 | 4 | import turtle
turtle.setup(400, 400) #size of graphics screen (width, height) in pxs
turtle.showturtle() #shows pointer
turtle.hideturtle() #hides pointer
turtle.pencolor('red') #selects the pen color
turtle.forward(200) #draws forward in pxs
turtle.left(90) #turns pointer left in degrees based on current position
turtle.right(90) #turns pointer right in degrees based on current position
turtle.setheading(0) #turns pointer counter clockwise in degrees from initial pos
turtle.penup() #doesn't write but can move around
turtle.pendown() #starts writing
turtle.circle(50) #draws a circle with radius in pxs
turtle.dot() #draws a dot
turtle.pensize(10) #thickness of pen
turtle.bgcolor('blue') #sets background color
turtle.reset()
turtle.clear()
turtle.clearscreen()
turtle.goto(10, 10) #moves to position (0,0) and draws a line
turtle.pos() #returns current cartesian position on shell
turtle.xcor() #returns the x from the current cartesian position
turtle.ycor() #returns the y from the current cartesian position
turtle.speed(1) #controls animation speed number between 1-10 (slowest to fastest) or 0 with no animation
turtle.write('hello world') #writes text at current position of cursor
turtle.fillcolor('pink') #decide on shape fill color
turtle.begin_fill() #starts fill before drawing shape
turtle.circle(100)
turtle.end_fill() #ends fill after drawing shape
turtle.done() #keeps graphics window open
| true |
c3d30c2d1cbd27b7f507f3a3ca2cb6cba11cad13 | Mithun-shetty046/Assignment1 | /Assignment 1 - Fibonacci Series.py | 409 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Write a Python program to get the Fibonacci series between 0 to 50
#
#
#
# Note : The Fibonacci Sequence is the series of numbers :
#
# 0, 1, 1, 2, 3, 5, 8, 13, 21, ....
#
# Every next number is found by adding up the two numbers before it.
#
# Expected Output : 1 1 2 3 5 8 13 21 34
# In[1]:
x=0
y=1
while y<50:
print(y)
x,y = y, x+y
# In[ ]:
| true |
e0079bf418830ac1a9f69d318a6a6c6ba274f8b0 | ravneetsingh13/hello-world | /pythonpro/ReverseLLRecursion.py | 501 | 4.15625 | 4 | from LinkedList import LinkedList,Node
def reverseLL(node,prev):
if node:
next = node.next
node.next = prev
prev = node
node = next
reverseLL(node,prev)
else:
llist.head = prev
llist = LinkedList()
first = Node('a')
second = Node('b')
third = Node('c')
forth = Node('d')
fifth = Node('e')
llist.head = first
first.next = second
second.next = third
third.next = forth
forth.next = fifth
print("LL before recursion:",llist)
reverseLL(llist.head,None)
print("LL after recursion:",llist) | true |
598e49e77f6e136be8dd083f518529b9a9a0801c | navekazu/sandbox-python | /01 basic syntax/list.py | 668 | 4.25 | 4 | list = ["My", "name", "is", "John."]
print("list:", end=" ")
print(list)
# インデックスは0オリジン
print("list[0]:", end=" ")
print(list[0])
print("list[1]:", end=" ")
print(list[1])
print("list[2]:", end=" ")
print(list[2])
# マイナスのインデックスは後ろからアクセス
print("list[-1]:", end=" ")
print(list[-1])
# :を使ってスライスが出来る
print("list[1:]:", end=" ")
print( list[1:])
print("list[1:2]:", end=" ")
print( list[1:2])
print("list[:2]:", end=" ")
print( list[:2])
print("list[:]:", end=" ")
print( list[:])
# ,を使って部分抜き出しが出来る
print("list[1, 3]:", end=" ")
print( list[1, 3])
| false |
85ad0d0d96fcb06807de457eb54be87c184501b5 | msarch/py | /py ref/pyglet/swiftless-ogl-tutotials.zip Folder/5__color.py | 1,393 | 4.25 | 4 | #!/usr/bin/env python
"""
Lesson:
How to add colour to an object in OpenGL
Original Source for this lesson:
http://www.swiftless.com/tutorials/opengl/color.html
Notes:
none for this file
Dependencies:
python: hrrp://www.python.org
Pyglet: http://www.pyglet.org
Converted to pyglet in September 2009 by :
Jestermon
jestermon.weebly.com
jestermonster@gmail.com
"""
import pyglet
from pyglet.gl import *
from OpenGL.GLUT import *
import sys
def square ():
glColor3f(1.0, 0.0, 0.0) #this will set the square to red.
glBegin(GL_QUADS)
glVertex3f(-0.5, -0.5, 0.0)
glVertex3f(-0.5, 0.5, 0.0)
glVertex3f(0.5, 0.5, 0.0)
glVertex3f(0.5, -0.5, 0.0)
glEnd()
def display ():
glClearColor (0.0,0.0,0.0,1.0)
glClear (GL_COLOR_BUFFER_BIT)
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
square()
glFlush()
def reshape (w, h):
glViewport (0, 0, w, h)
glMatrixMode (GL_PROJECTION)
glLoadIdentity ()
gluPerspective (60, w / h, 1.0, 100.0)
glMatrixMode (GL_MODELVIEW)
def main ():
glutInit ()
glutInitDisplayMode (GLUT_SINGLE)
glutInitWindowSize (500, 500)
glutInitWindowPosition (100, 100)
glutCreateWindow ("A basic OpenGL Window")
glutDisplayFunc (display)
glutReshapeFunc (reshape)
glutMainLoop ()
main()
| true |
7a89bad890d69e0add99e8ad3224cbde1e25b9b7 | msarch/py | /py ref/_/01.os/renametest/ren.py | 2,991 | 4.5625 | 5 | # Python renamer script: creates a function called pyrename(). pyrename() will rename all files in a given folder.
# Usage: Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().
# Warning, this script will rename your files. There is no undo. Use with care.
def pyrename():
'Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().'
import os
#function to ignore the hidden . files in a directory. Note the use of the 'yield' keyword
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith('.'):
yield f
path = raw_input('path to folder?: ')
#get the files from the folder and put the filenames in a list called files
theFiles = listdir_nohidden(path)
files = []
for f in theFiles:
files.append(f)
#user supplied values
print 'Want to replace a character or string in your file names?'
want_to_replace = raw_input('Type y or n. Or to completely rename type w: ')
if want_to_replace == 'y':
replace = raw_input('Type the character or string that you want to replace (FYI can be a space!): ')
replace_with = raw_input('Type the character or string that you want to replace with: ')
elif want_to_replace == 'w':
replace = ''
replace_with = raw_input('Type new name: ')
else:
replace = ''
replace_with = ''
if want_to_replace != 'w':
want_numbers = raw_input('Want your files numbered? type y or n: ')
if want_numbers == 'y':
zeros = raw_input('Type the amount of padding zeros you need (using a single integer, like 4): ')
else:
zeros = 0
if want_to_replace == 'w':
zeros = raw_input('Type the amount of padding zeros you need (using a single integer, like "4"): ')
ext = raw_input('Please type the three letter extension you want to use ex: jpg (NOT the .): ')
#remove extension, put the filenames in a list called names
names = []
for f in files:
if f[-4] == '.':
names.append(f.replace(f[-4:], ''))
else:
names.append(f)
#add new names, add user supplied extension, put the filenames in a list called namesPlusEx
namesPlusEx = []
count = 0
for f in names:
if want_to_replace == 'w':
namesPlusEx.append(f.replace(f, replace_with)+ (('.%.')+zeros+('d'))% count +'.'+ ext)
elif want_to_replace != 'w' and want_numbers == 'y':
namesPlusEx.append(f.replace(replace, replace_with)+ (('.%.')+zeros+('d'))% count +'.'+ ext)
else:
namesPlusEx.append(f.replace(replace, replace_with)+'.'+ ext)
count += 1
#rename the actual files
c=0
for f in files:
os.rename(path+'/'+f, path+'/'+namesPlusEx[c])
c+=1
print 'You have re-named %d files' % len(files)
| true |
16a94ff286eb1561dd68cc0e03ac1728276aeb83 | SaqlainAI/Gender_Classifier | /gender_classifier.py | 2,289 | 4.1875 | 4 | #importing the dependencies
import pandas as pd
from sklearn.model_selection import train_test_split
#pandas for using the dataset
#sklearn i.e scikit learn is the machine learning library for using the algorithms
#creating a dataframe of the dataset to work with the dataset
dataset=pd.read_csv('500_Person_Gender_Height_Weight_Index.csv')
#creating features list
#features list is a list of tuples having height and weight of each person
features=list(zip(dataset['Height'],dataset['Weight']))
#creating an array of target values(i.e the one which we are predicting )
value=dataset['Gender']
#splitting the dataset into train and test set
#X_train contains the features for training the model
#X_test contains the features for testing the model
#y_train contains the target values for training the model
#y_train contains the real target values
X_train,X_test,y_train,y_test=train_test_split(features,value,test_size=0.3)
#Using Decision trees
#importing dependency
from sklearn import tree
#creating a decision tree classifier
tree_model=tree.DecisionTreeClassifier()
#training the model
tree_model=tree_model.fit(X_train,y_train)
#predicting the target values i.e gender for the test set
tree_predicted =tree_model.predict(X_test)
#Using k-nearest neighbours
#importing dependency
from sklearn.neighbors import KNeighborsClassifier
#creating a k-nearest neighbour classifier and setting nearest_neighbours i.e n to 3
knn_model=KNeighborsClassifier(n_neighbors=3)
#training the model
knn_model.fit(X_train,y_train)
#predicting the target values i.e gender for the test set
knn_predicted=knn_model.predict(X_test)
#using Multinomial Naive Bayes
#importing dependency
from sklearn.naive_bayes import MultinomialNB
#training the model
nb_model=MultinomialNB().fit(X_train,y_train)
#predicting the target values i.e gender for the test set
nb_predicted=nb_model.predict(X_test)
#finding the accuracy of each model
from sklearn import metrics
print("Accuracy of decision tree model",metrics.accuracy_score(y_test,tree_predicted))
print("Accuracy of k-nearest neighbour model",metrics.accuracy_score(y_test,knn_predicted))
print("Accuracy of multinomial naive bayes model",metrics.accuracy_score(y_test,nb_predicted)) | true |
2cc5cce2f3d0e2a80ea29c638904aa8a14caa1f6 | chandraprakashh/machine_learning_code | /my_project/my_project_knn.py | 1,495 | 4.1875 | 4 | '''
this is the data set of many peoples in which we are trying to predict the affair of a women.
'''
# K-Nearest Neighbors (K-NN)
# Importing the libraries
import numpy as np
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('affairs.csv')
features = dataset.iloc[:, :-1].values
labels = dataset.iloc[:, 8].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = 0.25, random_state = 40)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
# Fitting K-NN to the Training set
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 5, p = 2) #When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2
classifier.fit(features_train, labels_train)
# Predicting the class labels
labels_pred = classifier.predict(features_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test, labels_pred)
print(cm)
# finding the accuracy of training
print("Training Accuracy: ",classifier.score(features_train,labels_train))
print("Test Accuracy: ",classifier.score(features_test,labels_test))
| true |
34eaef1b04c6bc96f82c2a1ebf4013fe1f2c8bee | varunchandan2/python | /math_problems.py | 2,935 | 4.625 | 5 | # This program is a menu of different math problems such as Algebra and geometry which will ask the user to select the option
# It will create random values and ask the user to solve it and then will display the result
import random
print("Please select an option to solve your math problem :")
print("1. Algebra practice, 2. Geometry practice,3. End practice")
# Throw an exception to verify the file and then open and read from it else give an error
try:
option = int(input("Please enter the option from 1 to 3: "))
except:
print("ERROR, Please select a numeric value")
else:
# If the option is 1,2 or 3 it will execute the following statements. If any other option is selected it will display an error
# If the user selects the 1 option, it will create random values in the given range and store it in the respective variables
if option == 1:
num1 = random.randint(45, 56)
num2 = random.randint(100,166)
num3 = random.randint(-11, 11)
result = num1-num2-num3
# Then it will display the randomly generate values to the user and asks the user to solve the equation
print("You have selected Algebra practice: ")
print("num1: ", num1)
print("num2: ", num2)
print("num3: ", num3)
user_sol = int(input("What is the result of num1-num2-num3?\n "))
# If the user value is equal to the result it will display the correct message else it will display the answer with wrong solution message
if user_sol == result:
print("Your answer is correct!")
else:
print("Your answer is not correct and the solution is: ", result)
# If the user selects the 2 option, it will create random values in the given range and store it in the respective variables
elif option == 2:
side1 = random.randint(45,56)
side2 = random.randint(10,66)
side3 = random.randint(18,46)
perimeter = side1+side2+side3
# Then it will display the randomly generate values to the user and asks the user to solve the equation
print("You have selected Geometry practice: ")
print("side1: ", side1)
print("side2: ", side2)
print("side3: ", side3)
user_solution = int(input("What is the perimeter of the triangle with side of lenghts side1, side2, side3?\n "))
# If the user value is equal to the result it will display the correct message else it will display the answer with wrong solution message
if user_solution == perimeter:
print("Your answer is correct!")
else:
print("Your answer is not correct and the solution is: ", perimeter)
# If option 3 is selected it will end the program
elif option == 3:
print("You have ended your practice")
else:
print("ERROR, please select from the given options")
| true |
b6c9b5e40e901e5343c62d2639540a308f7fd2b5 | varunchandan2/python | /dayOfTheWeeks.py | 872 | 4.4375 | 4 | #This program will display the day of the week entered in number 1 to 7 from the user
finalDay = ""
print('Please enter a number between 1 to 7 to see the corresponding day of the week:')
for num in range(1):
day = input("Please enter the number: ")
day = int(day)
# This function will take the input and according to the number will display the day of the week and if it is not in the range will display error
if day == 1:
week = 'Monday'
elif day == 2:
week = 'Tuesday'
elif day == 3:
week = 'Wednesday'
elif day == 4:
week = 'Thursday'
elif day == 5:
week = 'Friday'
elif day == 6:
week = 'Saturday'
elif day == 7:
week = 'Sunday'
else:
week = 'Error the number should be in the range'
finalDay = finalDay + week
# this will display the output
print("The day of the week is:", finalDay)
| true |
07e9d7dc25610019ed1a7e7d7a4a67f1e456b2ee | JohnCetera/Python-Programs | /Week 5 - Pay Increases.py | 1,492 | 4.25 | 4 | def raises():
# get current salary
salary = input("Enter your current pay rate: ")
# try to convert input to float
try:
# convert input to float
pay = float(salary)
# calculate next 3 years worth of pay increases, round 2 decimal places
a = pay*0.05
b = a+a*0.05
c = b+b*0.05
# format pay increase with comma and 2 decimal places
pay_increase_1 = "{:,.2f}".format(a)
pay_increase_2 = "{:,.2f}".format(b)
pay_increase_3 = "{:,.2f}".format(c)
# calculate next 3 years salary based on pay increases
d = pay*1.05
e = pay+a+b
f = e+c
# format salary with comma and 2 decimal places
pay_rate_1 = "{:,.2f}".format(d)
pay_rate_2 = "{:,.2f}".format(e)
pay_rate_3 = "{:,.2f}".format(f)
# print the results
print("\n" "Pay increase next year: $" + str(pay_increase_1), "\n" "Your pay will be: $" + str(pay_rate_1), "\n"
"\n" "Pay increase in two years: $" + str(pay_increase_2), "\n" "Your pay will be: $" + str(pay_rate_2), "\n"
"\n" "Pay increase in three years: $" + str(pay_increase_3), "\n" "Your pay will be: $" + str(pay_rate_3))
# pause program until key is pressed
input("Press enter to quit.")
# catch non-numbers being entered
except:
print("Please enter numbers only!")
# restart program
raises()
# call the program
raises()
| true |
fea04ba74d6151302ee9758e04449ff604eac050 | donaghy/Programming | /Python/jp.tmp/Ejercicios/Certamen I/2-Estructuras condicionales/1-2-06b-Letra_o_numero.py | 271 | 4.34375 | 4 | #! /usr/bin/env python
#coding: utf-8
char = raw_input('Ingrese caracter: ')
char = char[0]
if 'z'>=char>='a':
print 'Es letra minúscula'
elif 'Z'>=char>='A':
print 'Es letra mayúscula'
elif '9'>=char>='0':
print 'Es número'
else:
print 'No es letra ni número' | false |
0f108cb81c129b31cbe05dc38188c83cd8539d56 | Shiraz-Musaddique/CodeItBestWay | /CodeItBestWay/Python/Checking-number-is-3-digit-or-not.py | 225 | 4.1875 | 4 | # Python Code for checking the number is 3 digit or not.... Written by Shiraz Musaddique
i=int(input("Enter your number:"))
if (i < 1000 and i > 99):
print(i, "is a 3 digit number ")
else:
print(i, "is not a 3 digit number ")
| true |
87608b6dc769cca0f5ead6636949aa906c979fd8 | cesarnml/Algorithms | /climbing_stairs/climbing_stairs.py | 1,085 | 4.34375 | 4 | #!/usr/bin/python
import sys
# climbing_stairs(n) = climbing_stairs(n-3) + climbing_stairs(n-2) + climbing_stairs(n-1)
# Analogues solution to recursive Fibonacci sequence with memoization implementation
# runtime O(?) definitely better than O(2^n) ... probably O(n)
# space O(n) [due to memoization hash] + stack-size ... ?
# According to Stackoverflow ... probably O(n) in both space and time
def climbing_stairs(n, cache={}):
if n <= 0:
return 1
if n == 1:
return 1
if n == 2:
return 2
if n >= 3:
if n in cache:
return cache[n]
else:
value = climbing_stairs(
n-3, cache) + climbing_stairs(n-2, cache) + climbing_stairs(n-1, cache)
cache[n] = value
return value
if __name__ == "__main__":
if len(sys.argv) > 1:
num_stairs = int(sys.argv[1])
print("There are {ways} ways for a child to jump {n} stairs.".format(
ways=climbing_stairs(num_stairs), n=num_stairs))
else:
print('Usage: climbing_stairs.py [num_stairs]')
| false |
4abbab06182e4207aff8afa43bfcc696461301af | brpadilha/exercicioscursoemvideo | /Desafios/Desafio 057.py | 731 | 4.21875 | 4 | '''Ler o sexo, mas aceitar somente M ou F, caso digite errado
pedir para digitar novamente'''
'''sexo = ''
print ('------Digite o seu sexo-------')
print ('[M]/[F]')
while sexo !='M' and sexo !='F':
sexo=str(input ('Digite o seu sexo: ')).upper()
if sexo !='M' and sexo !='F':
print ('Digitou errado, digite novamente.')
if sexo=='M':
print ('Sexo Masculino,registrado com sucesso.')
elif sexo =='F':
print ('Sexo Feminino,registrado com sucesso.')
print('Fim') '''
sexo=str(input('Digite seu sexo [M/F]: ')).strip().upper()
while sexo not in 'MmFf':
sexo=str(input('Dados invalidos, digite nocamente [M/F]: '))
print ('Sexo {} registrado com sucesso.'.format(sexo))
| false |
ce46d1d3e76dc5ee1f5131a2e403bf4c8baebdc7 | sushantkumar-1996/Python_GeeksForGeeks | /Python_Circle_Area.py | 246 | 4.25 | 4 | """Area Of circle= pi * (r*r) Where r= radius of the circle"""
def findarea(radius):
pi = 3.142
return pi * (radius * radius)
radius = int(input("Enter Radius of circle"))
print("Area Of circle is:", findarea(radius))
| false |
7c14dbfd1cd08de93478f8d04dfc1539bdea86e0 | sushantkumar-1996/Python_GeeksForGeeks | /Python_Factorial.py | 218 | 4.21875 | 4 | # Python Program to find The factorial of a number
def factorial(n):
return 1 if n == 0 or n == 1 else n * factorial(n - 1)
num = int(input("Enter a Number :"))
print("factorial of", num, "is", factorial(num))
| true |
36bc9a488eb386eb3e302e8b7cb70fe04468c12c | muh-nasiruit/object-oriented-programming | /OOP 08/Lab 8 Assignment.py | 2,290 | 4.875 | 5 | '''
Task 2:
Create an ABC class of Bank and add some abstract method AccountName,
rate of interest, deposit, withdraw,
Now add some classes in which you will implement
Bank abstract class and its methods.
'''
from abc import ABC, abstractmethod
class Bank(ABC):
def AccountName(self):
pass
def IntRate(self):
pass
def Deposit(self):
pass
def Withdraw(self):
pass
class AutoMotors(Bank):
def AccountName(self):
print("Company Account.\n")
def IntRate(self):
print("2.5% Annual Interest Rate.\n")
def Deposit(self):
print("Company revenue deposited.\n")
def Withdraw(self):
print("Money withdrawal successful.\n")
class Customer(Bank):
def AccountName(self):
print("Savers Account.\n")
def IntRate(self):
print("1.5% Annual Interest Rate.\n")
def Deposit(self):
print("Savings Deposited.\n")
def Withdraw(self):
print("Money withdrawal successful.\n")
c1 = AutoMotors()
c2 = Customer()
for i in (c1,c2):
i.AccountName()
i.IntRate()
i.Deposit()
i.Withdraw()
'''
Task 3:
Find out one real world example of abstract class
and abstract method and implement it
by using python code.
'''
class OnlineSystem(ABC):
def AccountType(self):
pass
def Courses(self):
pass
def Transaction(self):
pass
class Student(OnlineSystem):
def AccountType(self):
print("Student Account.\n")
def Courses(self):
print("Student is enrolled in 6 courses.\n")
def Transaction(self):
print("Student has paid subscription fee.\n")
class Teacher(OnlineSystem):
def AccountType(self):
print("Teacher Account.\n")
def Courses(self):
print("Teacher is assigned 2 courses.\n")
def Transaction(self):
print("Teacher has been paid subscription fee.\n")
s1 = Student()
t1 = Teacher()
def info(x):
x.AccountType()
x.Courses()
x.Transaction()
info(s1)
info(t1)
| true |
7c1aac7faa733098fc0b8ce737fac0d32b8c6ea5 | avizmarlon/numbers_written_out | /logic.py | 1,314 | 4.34375 | 4 | from ext_nums_data import *
# todo.*add hyphen in the extensive form of some numbers
# todo.* make it scalable to even bigger numbers
# maybe wrap all the code into a function to be used by other scripts
# take the input, check if its a valid integer
# also eliminates redundant zeroes in case of something like 01 or 00001
number = input("Type the number to be written out: ")
try:
number = int(number)
except ValueError:
print("Your input was not an integer!")
exit()
# converts back to str to be iterable
number = str(number)
# breaks the number into "smaller pieces" to easily work with the dict (e.g.: 435 becomes 400+30+5)
simple_numbers = []
c = 0
for character in number:
current_iteration_number = number[c:]
simple_number = character + ('0' * (len(current_iteration_number) - 1))
c += 1
simple_numbers.append(int(simple_number))
# print the extensive form, number by number (iterated through the list of decimal numbers)
for simple_number in simple_numbers:
print(ext_nums[simple_number], end=' ')
# testing string format for output of 3-characters number (NOT FINISHED)
# '{num1}{num2}{num3}'.format(num1=ext_nums[simple_numbers[0]],
# num2=ext_nums[simple_numbers[1]],
# num3=ext_nums[simple_numbers[2]])
| true |
926a3c34e9ac5fea38a92a2aa12384fb4226c607 | gileno/aulas-poli | /simulador.py | 299 | 4.15625 | 4 | import random
quantidade = int(input("Digite a quantidade: "))
maximo = 0
soma = 0
for i in range(quantidade):
numero = random.randint(1, 6)
print(numero)
if maximo < numero:
maximo = numero
soma += numero
print("O número máximo foi:", maximo)
print("A soma foi:", soma)
| false |
8d576b195e597f33b1e5217fc69fd4f09df090fe | bswalsh247/Harvard-CS50 | /Week 8 - Python/miscellanous/struct1.py | 1,114 | 4.34375 | 4 | # We can see another convenient feature:
import cs50
import csv
from student import Student
students = []
for i in range(3):
print("name: ", end="")
name = cs50.get_string()
print("dorm: ", end="")
dorm = cs50.get_string()
students.append(Student(name, dorm))
file = open("students.csv", "w")
writer = csv.writer(file)
for student in students:
writer.writerow((student.name, student.dorm))
file.close()
# Now, instead of printing the students to the screen, we can write them to a
# file students.csv by opening it and using a built-in module, csv, that writes
# comma-separated values files.
# With csv.writer(file), we pass in the file we open to get back a writer object
# that will take in tuples, and write them to the file for us with just writerow.
# If we were to run this program without import csv, the interpreter would start
# the input, collecting input like name and dorm and creating students, but only
# when it reaches the line that calls for csv will it notice that it wasn’t defined,
# and raise an exception (stop the program because there is an error). | true |
d26c13053f3aefe0af3d90c82b471013aab9069b | xiangcao/PythonLeetcode | /291_word_pattern_ii.py | 1,826 | 4.1875 | 4 | """
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.
Examples:
pattern = "abab", str = "redblueredblue" should return true.
pattern = "aaaa", str = "asdasdasdasd" should return true.
pattern = "aabb", str = "xyzabcxzyabc" should return false.
Notes:
You may assume both pattern and str contains only lowercase letters.
"""
class Solution(object):
def wordPatternMatch(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
lettermapping={}
strmapping={}
patternlen = len(pattern)
strlen = len(str)
def dfs(pIndex, strIndex):
if pIndex == patternlen and strIndex == strlen:
return True
if pIndex == patternlen or strIndex == strlen:
return False
if pattern[pIndex] in lettermapping:
mappedStr = lettermapping[pattern[pIndex]]
if str[strIndex:strIndex+len(mappedStr)] != mappedStr:
return False
else:
return dfs(pIndex+1, strIndex+len(mappedStr))
for ending in range(strIndex+1, strlen- (patternlen-pIndex-1)+1):
substring = str[strIndex:ending]
if substring in strmapping:
continue
lettermapping[pattern[pIndex]] = substring
strmapping[substring] = pattern[pIndex]
if dfs(pIndex+1, ending):
return True
lettermapping.pop(pattern[pIndex])
strmapping.pop(substring)
return False
return dfs(0, 0)
| true |
084f2ddc1e0dcff823318021b39bc3cb97429fec | 221910308036/p | /5.py | 667 | 4.125 | 4 | """
You are given a string animals and another string dinosaurs. Every letter in animals represents a different type of animal and every unique character in dinosaurs represents a different dinosaur.
Return the total number of dinosaurs in animals.
Example 1
Input
animals = "abacabC"
dinosaurs = "bC"
Output
3
Explanation
There's two types of dinosaurs "b" and "C". There's 2 "b" dinosaurs and 1 "C" dinosaur. Note we didn't count the lowercase "c" animal as a dinosaur.
"""
class Solution:
def solve(self, animals, dinosaurs):
res = 0
dinosaurs = set(dinosaurs)
for c in dinosaurs:
res += animals.count(c)
return res
| true |
399666daf1eb8b5c57f46ce0f5905a06209b263d | PrekshaShah17/PythonCodeChallenges | /sort_string.py | 791 | 4.3125 | 4 | def sort_string(input_str: str) -> str:
"""
sort space separated string keeping case intact
:param input_str: string of words, separated by space
:return: string of words, sorted alphabetically
"""
return ' '.join(sorted(input_str.split(), key=str.casefold)) # casefold method is used for case-less matching
if __name__ == "__main__":
# test cases
assert sort_string("car") == "car"
assert sort_string("test set") == "set test"
assert sort_string("apple strawberry banana") == "apple banana strawberry"
assert sort_string("what is this") == "is this what"
assert sort_string("weird sentences WEIRD") == "sentences weird WEIRD"
assert sort_string("apple APPLE strawberry 123 BANANA ORANGE") == "123 apple APPLE BANANA ORANGE strawberry"
| true |
b633d390d3698f7526e7ba03ab83a4f64e2ec969 | AbdulAhadSiddiqui11/PyHub | /Miscellaneous/XOR calculator.py | 1,943 | 4.34375 | 4 | """
Program defination :
For two positive integers, lo and hi, and a limit k, find two integers,a and b, satisfying the following criteria.
Return the value of a*b. The * symbol denotes the bitwise xor operator. Write a python function to return the value
of a*b. The function will accept lo, hi, and k values as input arguments.
lo <= a < b <= hi, the value of a*b is minimal for a*b <= k.
Example : lo = 3, hi = 5, k = 6.
╔═════╦═════╦═════╗
║ a ║ b ║ a*b ║
╠═════╬═════╬═════╣
║ 3 ║ 4 ║ 7 ║
╠═════╬═════╬═════╣
║ 3 ║ 5 ║ 6 ║
╠═════╬═════╬═════╣
║ 4 ║ 5 ║ 1 ║
╚═════╩═════╩═════╝
The maximal usable XORed value is 6 because it is the maximal value that is less thank or equal to the limit k = 6.
"""
def calculator(lo, hi, k):
a = lo
b = a + 1
max = -1
while(a<b and b<=hi):
while(b<=hi):
value = (a^b)
print(a, "xor", b, "=", value)
if(value > max and value <= k):
max = value
b = b + 1
a = a + 1
b = a + 1
print("Maximal value is", max)
if __name__ == "__main__":
lo = int(input("Enter one number : "))
hi = int(input("Enter the second number : "))
k = int(input("Enter the limit : "))
print("Results : ")
calculator(lo, hi, k) | false |
e399c520245abc589e472aca35cbe0dd68ca5616 | AbdulAhadSiddiqui11/PyHub | /Basics/Operators.py | 1,234 | 4.4375 | 4 | # Arithmetic and Assignment Operators :
x = 5 # Assignment operator
print("X :", x)
x += 5
print("X + 5 =" , x)
def SimOperators():
"""
Similar Operators :
+=
-=
/=
x=
%=
**= #Multiplies the variable by the number of times, eg : x = 5; x**=3 ans is 125
//= #Floor Divison
&= #And operation
|= #Or Operation
^=
>>= Right Shift
<<= Left Shift
"""
print("\n",SimOperators.__doc__)
y = 10
print("Y :" , y)
print("Is X = Y ?" , (x is y))
y = 5
print("Y :",y)
print("Is X = Y ?" , (x is y))
def SimOperators1():
"""
Similarly,
Identity Operators :
is #Checks whether both the operands refer to the same object or not.
is not #Opposite of is operator.
Membership Operators :
in #Returns true if specified value is present in the object, else returns false.
Not in #Opposite of in operator.
"""
print("\n",SimOperators1.__doc__)
print("X :", x)
print("Y :" , y)
if(x==y):
print("X is equal to Y")
if(x!=y):
print("X is not equal to Y")
def SimOperators2():
"""
Comprison Operators :
==
!=
<>
>
<
>=
<=
Logical Operators :
& #Logical And
| #Logical Or
~ #Logical Not
"""
print("\n",SimOperators2.__doc__)
input("Press any key to exit ") | true |
8d98429bd8681e2acedc76f0997169d91b18fc69 | AbdulAhadSiddiqui11/PyHub | /Basics/Sets.py | 815 | 4.3125 | 4 | x = set([1,2,3])
print("Set X : " , x)
y = set([3,4,5])
print("Set Y : " , y)
union = x.union(y)
print("X union Y : " , union)
intersection = x.intersection(y)
print("X intersection Y : " , intersection)
diff = x - y #elements present in x that are not present in y
print("X - Y : " , diff)
sysdiff = x^y #Symetric difference -> uncommon elements in both x and y
print("Uncommon elements in both X and Y : " , sysdiff)
z = x.issubset(y) #checks if x is a subset of y or not. Returns true or false.
print("Is X a subset of Y ?" , z)
#You can also add or remove an element from the set by using add and remove function, eg :
x.add(5) # adds 5 to set x
print("After adding 5 to set X : " , x)
y.remove(5) #removes 5 from set y
print("After removing 5 from set Y : " , y)
input("Press any key to exit ") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.