blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4f8a39f29bb77bf7b18a5dc89a97eaeec35e66f6 | JayMackay/PythonCodingFundamentals | /[Session 1] Basic Syntax & String Manipulation/[4] String Manipulation/06 Reverse A String/3_reverse_string_slice.py | 427 | 4.5 | 4 | def reverse_string(str):
"""Reverse the given string with slicing"""
# start = 0, stop = len(str), hence range is whole string.
# step = -1, hence go backwards through range.
reversed_str = str[::-1]
return reversed_str # return the reversed string to the caller
str = "TechTalent Academy"
print(f"The original string is: {str}")
print(f"The reverse string is : {reverse_string(str)}") # call function
| true |
2991f4875e4a0a23cdbf1933afc19f5f08e8536f | JayMackay/PythonCodingFundamentals | /[Session 1] Basic Syntax & String Manipulation/[3] While Loops/06 if_else_menu.py | 328 | 4.1875 | 4 | def menu():
menuOption = int(input("Select an option 1, 2 or 3"))
if menuOption == 1:
print("These are all the Running Trainers")
elif menuOption == 2:
print("These are all the Classics")
elif menuOption == 3:
print("These are all the Boots and Shoes")
else:
print("You didn't choose the correct option")
menu()
| true |
712d2ebf67b42ef038d0e649f81cabfd4bcabdf9 | JayMackay/PythonCodingFundamentals | /[Session 2] File Handling/File Handling Application/by_titles.py | 1,174 | 4.125 | 4 | """
A CSV file exists that contains data for women tennis players.
Use this file to display the players in ascending order of titles won.
Output should include first name, last name and number of titles.
"""
import csv
from operator import itemgetter
from pprint import pprint
def csv_to_list_of_dicts(csv_file_to_convert):
list_of_dicts = []
with open("women_tennis_players.csv") as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
list_of_dicts.append(line)
return list_of_dicts
# Read in CSV file
player_list = csv_to_list_of_dicts("women_tennis_players.csv")
# Convert Titles to integers so sort will work properly
for player in player_list:
player["Titles"] = int(player["Titles"])
# Sort by Titles
players_by_titles = sorted(player_list, key=itemgetter("Titles"))
# Display result
#pprint(players_by_titles)
for player in players_by_titles:
#print(f"{player['First Name']} {player['Last Name']}: {player['Titles']} titles")
# The line above is too long. Can reformat it as:
print(
f"{player['First Name']} {player['Last Name']}: "
f"{player['Titles']} titles"
)
| true |
4ba03cc32a3b257e11f46daa017c7e58d8c67e3f | reneenie/python_for_evy | /m2w1.py | 532 | 4.125 | 4 | # changes from python2 to python3
# 1. print '' -> print('')
# 2. raw_input() -> input()
# 3. how to handle complex charaxters
# data structure 1: String
# input() always gives you strings
# SLICING begining and up to but not including
word = 'banana'
print(word[2:4])
print(word[:5])
print(word[2:])
# String comparison
'A' < 'a' # true
'z' > 'a' # return true
'Z' > 'A' # return true
# functions in string library
greet = 'Hi'
print(greet.lower())
# str.find()
# str.strip()
## str.lstrip()
## str.rstrip()
# str.replace()
| true |
259de94aad23814c5ff90351a0f597524ca734e9 | MarcoANT9/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 634 | 4.25 | 4 | #!/usr/bin/python3
"""
This module opens a file, reads a defined number of
lines and print them into the stdout.
"""
def read_lines(filename="", nb_lines=0):
"""
This function takes a file and opens it to print a determined
number of lines.
"""
with open(filename, mode="r", encoding="utf-8") as myfile:
if nb_lines <= 0 or nb_lines >= sum(1 for lines in myfile):
myfile.seek(0)
print(myfile.read(), end="")
else:
myfile.seek(0)
for i in range(0, nb_lines):
print(myfile.readline(), end="")
if __name__ == "__main__":
main()
| true |
f4d74bf14b5a545c0fcfec5764cc64374c7e0c75 | FUNMIIB/Election_Analysis | /Python_practice.py | 791 | 4.375 | 4 | counties = ["Arapahoe", "Denver", "Jefferson"]
if "El paso" in counties:
print("El paso is in the list of counties")
else:
print("El paso is not the list of counties")
if "Jefferson" in counties:
print("Jefferson is in the list of counties")
else:
print ("Jefferson is not the list of counties")
for county in counties:
print(county)
candidate_votes = int(input("How many votes did the candidate get in the election? "))
total_votes = int(input("What is the total number of votes in the election? "))
message_to_candidate = (
f"You received {candidate_votes:,} number of votes."
f"The total number of votes in the election was {total_votes:,}. "
f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes. ")
print(message_to_candidate)
| true |
009ff8126a624bed136f3266783f8a9d677bd579 | athul-vinayak/HeadSpin | /Date.py | 2,953 | 4.15625 | 4 | def monthcheck(month):
if month > 0 and month <= 12:
return True
else:
return False
def daycheck(month,day,year):
monthlist1 = [1,3,5,7,8,10,12]
monthlist2 = [4,6,9,11]
monthlist3 = 2
for mon in monthlist1:
if month == mon:
if day >=1 and day <= 31:
return True
else:
return False
for mon in monthlist2:
if month == mon:
if day >= 1 and day <= 30:
return True
else:
return False
if month == monthlist3:
if(year % 4)==0:
if(year % 100)==0:
if(year % 400)==0:
if day >=1 and day <= 29:
return True
else:
return False
else:
if day >=1 and day <= 28:
return True
else:
return False
else:
if day >=1 and day <= 29:
return True
else:
return False
else:
if day >=1 and day <= 28:
return True
else:
return False
def yearcheck(year):
if len(year) >= 1 and len(year) <= 4:
return True
else:
return False
def main():
date = str(input("Enter the date in mm/dd/yyyy format: ")) ## Input date in the given format.
month,day,year = date.split("/")
monthvalidity = monthcheck(int(month))
dayvalidity = daycheck(int(month),int(day),int(year))
yearvalidity = yearcheck(year)
currentDate="02/22/2020" ##Hard code the date as built-in functions are prohibited
currentMonth,currentDay,currentYear=currentDate.split("/")
# print(currentDay)
# print(currentMonth)
# print(currentYear)
# print(day)
# print(month)
# print(year)
if monthvalidity == True and dayvalidity == True and yearvalidity == True :## check if all 3 variables are valid or True
if((int(currentDay)<int(day) and int(currentMonth)==int(month) and int(currentYear)==int(year)) or
(int(currentDay)>=int(day) and int(currentMonth)<int(month) and int(currentYear)<=int(year)) or
(int(currentDay)>=int(day) and int(currentMonth)>=int(month) and int(currentYear)<int(year)) or
(int(currentDay)<int(day) and int(currentMonth)>=int(month) and int(currentYear)<int(year)) or
(int(currentDay)>=int(day) and int(currentMonth)<int(month) and int(currentYear)<int(year)) or
(int(currentDay)<int(day) and int(currentMonth)<int(month) and int(currentYear)<int(year))):
print("1.The date {0} is invalid.".format(date))
else:
print("The date {0} is valid.".format(date))
else:
print("2.The date {0} is invalid.".format(date))
main()
| false |
f0904e7e1db3dc7d1da7c86be5b8262a536d1f09 | nmessa/Stratham-Girls-Coding-Club | /Code for 11.15.2017/function4.py | 1,221 | 4.1875 | 4 | ##def printRamp(letter, level):
## for i in range(1, level+1):
## for j in range(i):
## print(letter, end = "")
## print()
####
##printRamp('X', 40)
## Output
## Q
## QQ
## QQQ
## QQQQ
## QQQQQ
## QQQQQQ
## QQQQQQQ
## QQQQQQQQ
## QQQQQQQQQ
## QQQQQQQQQQ
# Create a function printRamp2 which prints the following pattern
## BBBBBBBBBB
## BBBBBBBBB
## BBBBBBBB
## BBBBBBB
## BBBBBB
## BBBBB
## BBBB
## BBB
## BB
## B
# when called with printRamp2("B", 10)
# Create a function printRamp3 which prints the following pattern
## X
## XX
## XXX
## XXXX
## XXXXX
## XXXXXX
## XXXXXXX
## XXXXXXXX
## XXXXXXXXX
## XXXXXXXXXX
# when called with printRamp3("X", 10)
##def printRamp2(letter, level):
## for i in range(level, 0, -1):
## for j in range(i):
## print(letter, end = "")
## print()
##
##printRamp2('B', 10)
def printRamp3(letter, level):
for i in range(level):
for j in range(level-1-i, 0, -1):
print(' ', end = "")
for k in range(i+1):
print(letter, end = "")
print()
printRamp3('X', 40)
| false |
470a7c03c303d47f19bfb6c6588f61bfd18ccd8d | nmessa/Stratham-Girls-Coding-Club | /Code for 3.21.2018/caesarCipherMaker.py | 811 | 4.28125 | 4 | # caesarCipherMaker.py
alphabet = "abcdefghijklmnopqrstuvwxyz"
def make_code(text, key):
code_text = ""
# loop through the letters and build the code text
for letter in text:
if letter in alphabet:
i = alphabet.find(letter) + key
code_text = code_text + alphabet[i % 26]
else:
code_text = code_text + letter
return code_text
# Get message
plain_text = input("Please enter your text to be encoded:\n")
# Change user input to lower case:
plain_text = plain_text.lower()
# Get cipher key
cipher_key = int(input("Please enter a numerical key between 1 and 26:\n"))
# Create coded message
code_text = make_code(plain_text, cipher_key)
print("Here is your code:\n", code_text.upper())
#To Do
#Modify this program to create a decoder
| true |
77acf9dc2e1d24b2557ee1963e6a810b1de96f00 | nmessa/Stratham-Girls-Coding-Club | /Code for 5.2.2018/Secret Message Starter/secretMessage.py | 938 | 4.4375 | 4 |
#This function generates a key value based on your name
#This function adds up the ASCII values of all letters in your name
def nameValue(name):
#Add code here
#return a value from 1 to 127
#This function takes plainText and a key and encrypts it using Caesar Cipher
def encrypt(plainText, key):
cipherText = ""
#Add code here
return cipherText
#This function takes cipherText and a key and decrypts it using Caesar Cipher
def decrypt (cipherText, key):
plainText = ""
#Add code here
return plainText
#Test code
plainText = input("Enter a message: ")
name = input("Enter your first name: ")
key = nameValue(name)
cipherText = encrypt(plainText, key)
print('Encrypted message =', cipherText)
print()
name = input("Enter your first name to decrypt: ")
key = nameValue(name)
plainText = decrypt(cipherText, key)
print('Original message =', plainText)
| true |
e228f80dd8345a40e7334fef8e631bdee01608d7 | viveksyngh/CTCI-6th-Edition-Python-Solution | /Chapter-10/5_sparse_search.py | 1,738 | 4.1875 | 4 | """
Given a sorted aaray of strings that is interspersed with empty strings, write a method to find the location of a given string.
EXAMPLE
Input: ball, {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
Ouput: 4
"""
import unittest
def search(strings, s, first, last):
if first > last:
return -1
mid = (first + last)//2
if strings[mid] == "":
left = mid - 1
right = mid + 1
while True:
if left < first or right > last:
return -1
elif left >= first and strings[left] != "":
mid = left
break
elif right <= last and strings[right] != "":
mid = right
break
left -= 1
right += 1
if strings[mid] == s:
return mid
elif strings[mid] < s:
return search(strings, s, mid + 1, last)
else:
return search(strings, s, first, mid - 1)
def search_sparse(strings, s):
if len(strings) == 0 or s == "":
return -1
return search(strings, s, 0, len(strings)-1)
class TestSearchSparse(unittest.TestCase):
def setUp(self):
pass
def test_empty_array(self):
self.assertEqual(search_sparse([], "abc"), -1)
def test_empty_string(self):
self.assertEqual(search_sparse(["abc", "", ""], ""), -1)
def test_positive(self):
self.assertEqual(search_sparse(["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""], "ball"), 4)
def test_negative(self):
self.assertEqual(search_sparse(["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""], "pad"), -1)
if __name__ == "__main__":
unittest.main() | true |
f0c131b69d93c4394e3504dcac2b3709041ff3fa | ayushdas/PythonCodes | /sample.py | 2,142 | 4.1875 | 4 | ### Code to get the most frequently used words in a text document
### Concepts Used:
### 1. Dictionary 2. Tuple 3. File Reading
fileName = raw_input('Enter a file name: ')
if len(fileName) < 1:
fileName = 'trial.txt'
try:
fileHandle = open(fileName)
print ('Searching file: '+fileName)
except:
print('Cannot open file: '+fileName)
quit()
print('File ready for reading...')
print ('Counting words...')
countOfWords = dict()
for line in fileHandle:
line = line.strip()
words = line.split(' ')
for word in words:
if word=='':
continue
countOfWords[word] = countOfWords.get(word,0) + 1
print ('Counting completed...')
print ('Computing the top 10 words in the document WITHOUT dynamic lists...')
wordList = list()
for key,value in countOfWords.items():
newTup = (value,key)
wordList.append(newTup)
wordList = sorted(wordList, reverse=True)
print ('The top 10 words in the document WITHOUT dynamic lists...')
for item in wordList[:10]:
print(item)
print ('Computing the top 10 words in the document WITH dynamic lists...')
print(sorted([(v,k) for k,v in countOfWords.items()],reverse=True)[:10])
### Object Oriented programming in Python
### Creating classes, methods and using inheritance
class PartyAnimal:
x = 0
name = ''
def __init__(self, name):
self.name = name
print('I am constructed')
def party(self):
self.x +=1
print ('The value of x so far: ',self.x)
def __del__ (self):
print('I am destructed')
class DummyClass:
def __init__(self):
print ('I am contructed')
def dummyFunction(self):
print('This is a dummyFunction')
def __del__(self):
print ('I am destructed')
class FootballFan(PartyAnimal,DummyClass):
points = 0
def touchdown(self):
self.points = self.points+7
self.party()
self.dummyFunction()
print(self.name,self.points)
an = PartyAnimal('Ayush')
an.party()
an.party()
an.party()
an=42
print(an)
ab = FootballFan('Ayush')
ab.dummyFunction()
ab.touchdown()
| true |
0ebad36e8e2c2f95d209c216baba9a04eb5409a3 | AndreeaParlica/Codewars-Python-Fundamentals-Kata-Solutions | /Get the Middle Character.py | 583 | 4.34375 | 4 | # You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd,
# return the middle character. If the word's length is even, return the middle 2 characters.
#
# #Examples:
#
# Kata.getMiddle("test") should return "es"
#
# Kata.getMiddle("testing") should return "t"
#
# Kata.getMiddle("middle") should return "dd"
#
# Kata.getMiddle("A") should return "A"
# return a str
def get_middle(s):
return s[(len(s) - 1) // 2:(len(s) + 2) // 2]
print(get_middle("testing"))
# ,"t")
print(get_middle("middle"))
# ,"dd") | true |
50c03161749ab1bff570595b142607642619e20d | igor91m/homework_2 | /task_2.py | 953 | 4.1875 | 4 | '''
2. Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить
на своем месте. Для заполнения списка элементов необходимо использовать функцию input().
'''
# Добавление элементов списка путем input
second_list = []
# Количество элементов для списка
count = int(input('Enter number of elements: '))
i = 0
el = 0
while i < count:
second_list.append(input('Enter next number: '))
i += 1
for elem in range(int(len(second_list)/2)):
second_list[el], second_list[el + 1] = second_list[el + 1], second_list[el]
el += 2
print(second_list) | false |
796631a9b232251e00c68bbfda3ecfa030a72231 | Siddhant6078/Python | /Python Tasks/duplicate.py | 1,114 | 4.375 | 4 | # Duplicate the elements of a list.
# Example:
# ?- dupli([a,b,c,c,d],X).
# X = [a,a,b,b,c,c,c,c,d,d]
print 'Duplicate each element of list'
list1 = ['a','b','c','c','d']
result1 = []
def duplcate_each(l1,r1):
for i in l1:
r1.extend([i, i])
return r1
print duplcate_each(list1,result1)
# Duplicate the elements of a list.
# Example:
# ?- dupli([a,b,c,d],X).
# X = [a,b,b,c,c,c,d,d,d,d]
print 'Print each element of list as per its index number'
list2 = ['a','b','c','d']
result2 = []
def duplcate_index_times(l2,r2):
for index, item in enumerate(l2):
for x in range(index+1):
r2.append(item)
return r2
print duplcate_index_times(list2,result2)
print 'Duplicate the elements of a list a given number of times.'
# Duplicate the elements of a list a given number of times.
# Example:
# ?- dupli([a,b,c],3,X).
# X = [a,a,a,b,b,b,c,c,c]
# What are the results of the goal:
# ?- dupli(X,3,Y).
list3 = ['a','b','c','d']
result3 = []
def duplcate_n_times(l3,n,r3):
for index, item in enumerate(l3):
for x in range(n):
r3.append(item)
return r3
print duplcate_n_times(list3,4,result3) | true |
5a60e54f959066c13d1929ae82043c7d90b034b0 | Gamertoc/University-EPR | /Tasks01/logical.py | 1,101 | 4.25 | 4 | __author__ = "7146127, Theobald"
# This program receives a sentential formula and calculates the value of it
# We assume that the input has the format BOOL connection BOOL
# with BOOL being either True or False and connection being "and" or "or"
formula = input("Please enter a sentential formula (BOOL and/or BOOL): ")
# We split the input in parts so we can analyze it
parts = formula.split()
a = parts[0]
b = parts[2]
connection = parts[1]
# Determine whether the first statement is true or false
if a == "True":
a = True
else:
a = False
# Same goes for the second
if b == "True":
b = True
else:
b = False
# Check whether the connection is an "and" or an "or" and act accordingly
if connection == "and":
result = a & b
else:
result = a | b
print(result)
# Test cases incoming with the type: Input : Output
# True and True : True
# True and False : False
# False and True: False
# False and False : False
# True or True : True
# True or False : True
# False or True : True
# False or False : False
# With these all possible value combinations are covered and verified
| true |
c54c2abc7c01bbb7c632d0800c172af2fa57abd9 | Gamertoc/University-EPR | /Tasks03/functions.py | 2,514 | 4.15625 | 4 | """Getting two integers and doing a bunch of things with them."""
__author__ = "7146127, Theobald"
def average(first_number, second_number):
"""Returning the average of two integers and printing the average and the
type of the average.
:param first_number: int
:param second_number: int
:return: int or float
"""
avg = (int(first_number) + int(second_number)) / 2
# If the average is an integer, we can convert it to one
if avg // 1 == avg / 1:
avg = int(avg)
print(avg, type(avg))
return avg
def first_last_digit(avg):
"""Printing the first and last digit of the average and returning its
length.
:param avg: int or float
:return: int
"""
# If the average is negative (starting with a minus), we have to skip that to get the first
# digit
if avg < 0:
avg = str(avg)
print(avg[1], avg[-1], sep="")
else:
avg = str(avg)
print(avg[0], avg[-1], sep="")
return len(avg)
def reverse(avg):
"""Reversing the average.
:param avg: int or float
:return: string
"""
avg = str(avg)
avg_reversed = ""
# We iterate through all of the string and reverse it by attaching the [-i-1] element to
# the new string
for i in range(len(avg)):
avg_reversed += avg[-i - 1]
return avg_reversed
def main():
"""Starting the program"""
# We need to make sure that we get valid inputs
while True:
first = input("Please enter the first integer: ")
try:
first = int(first)
except ValueError:
continue
break
# The same goes for the second integer
while True:
second = input("Please enter the second integer: ")
try:
second = int(second)
break
except ValueError:
continue
# Now we can start working with that stuff
avg = average(first, second)
# noinspection PyTypeChecker
first_last_digit(avg)
print(avg, "is reversed", reverse(avg))
if __name__ == '__main__':
main()
# Test cases:
# 10, 5 : "7.5 <class 'float'>", "75", "7.5 is reversed 5.7"
# -1234, -765 : "-999.5 <class 'float'>", "95", "-999.5 is reversed 5.999-"
# lol : "Please enter the first integer: "
# 870965437895424892631548654526437, 26954786387265987436278564873265876432 :
# "13477828676351940767776228213878947840 <class 'int'>", "10",
# "13477828676351940767776228213878947840 is reversed 04874987831282267776704915367682877431"
| true |
d2a31423ec572ce252090fbcb8c1a1583f6c8fc1 | ShinJustinHolly3317/stanCode101 | /stanCode_hailstone/hailstone.py | 1,332 | 4.53125 | 5 | """
File: hailstone.py
Name: Justin Kao
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Use while loop to keep doing Hailstone sequence.
If the number entered is a Even number, divided by 2.
If the number entered is a Odd number, make 3n+1.
Use another variable(num_old) to store the previous number when printing out.
"""
print("This program computes Hailstone sequences!")
num = int(input("Enter a number: "))
print("----------------------------------")
count = 0
while True:
if num == 1:
break
if num % 2 == 1: # Odd number
num_old = num # Previous number
num = int(num*3+1)
print(str(num_old) + " is odd, so I make 3n+1: " + str(num))
else: # Even number
num_old = num # Previous number
num = int(num / 2)
print(str(num_old) + " is even, so I take half: " + str(num))
count += 1
print("I took " + str(count) + " steps to reach 1.")
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
97d8613b6151db219d165201c00a42eba2ec2e99 | krishajivani/Atwood | /Main.py | 2,302 | 4.375 | 4 | #Original way to create a basic screen
# import pygame
# pygame.init()
#
# win = pygame.display.set_mode((500, 500))
#
# pygame.display.set_caption("First Game")
#
# x = 50
# y = 50
# width = 40
# height = 60
# vel = 5
#
# run = True
# while run:
# pygame.time.delay(100)
#
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# run = False
#
# pygame.quit()
#The link below shows and explains how to drop spheres with gravity playing a role with Pymunk and Pygames interacting.
#https://github.com/viblo/pymunk/blob/08fb141b81c0240513fc16e276d5ade5b0506512/docs/html/_sources/tutorials/SlideAndPinJoint.rst.txt
import sys, random
import pygame
from pygame.locals import *
import pymunk
import pymunk.pygame_util
def add_ball(space):
mass = 1
radius = 20
moment = pymunk.moment_for_circle(mass, 0, radius) #sets moment of inertia
body = pymunk.Body(mass, moment) #creates body
x = random.randint(120, 380)
body.position = x, 550 #sets position, (x, y) coordinate with x generated randomly
shape = pymunk.Circle(body, radius) #body needs to be defined as a shape to collide with things
space.add(body, shape) #add shape to the space
return shape
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Object Dropping, Affect of Gravity")
clock = pygame.time.Clock()
space = pymunk.Space()
space.gravity = (0, -980) #x-coordinate is for gravity in x-direction, y-coordinate for gravity in y-direction
balls = []
draw_options = pymunk.pygame_util.DrawOptions(screen)
ticks_to_next_ball = 10
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit(0)
elif event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit(0)
ticks_to_next_ball -= 1
if ticks_to_next_ball <= 0:
ticks_to_next_ball = 25
ball_shape = add_ball(space)
balls.append(ball_shape)
space.step(1/50.0) #amount of steps the object takes downwards at a time.
screen.fill((255,255,255))
space.debug_draw(draw_options)
pygame.display.flip()
clock.tick(40)
if __name__ == '__main__':
main() | true |
93660230e119895b4540e20651faeccce46ac939 | pawarspeaks/HackFest21 | /sudokusolver.py | 2,145 | 4.125 | 4 | def next_empty_space(puzzle):
#finds the next row, col that is empty ;; returns (row,col) or ((None,None) if empty)
for r in range(9):
for c in range(9):
if puzzle[r][c]==-1:
return r,c
return None, None #if no space is empty
def is_valid(puzzle,guess,row,col):
#checks the guess at row of the puzzle is valid
row_vals= puzzle[row]
if guess in row_vals:
return False
#checks the guess at col of puzzle is valid
col_vals=[puzzle[i][col] for i in range(9)]
if guess in col_vals:
return False
#checks in 3X3 matrix
row_start= (row//3)*3
col_start= (col//3)*3
for r in range(row_start,row_start+3):
for c in range(col_start,col_start+3):
if puzzle[r][c]==guess:
return False
return True
def solve_sudoku(puzzle):
#solve sudoku using backtracking
#puzzle is a list of lists where each row is the inner list
row, col= next_empty_space(puzzle)
#when theres no free space left that means our puzzle is complete
if row is None:
return True
#if theres a free space then guess between 1 to 9
for guess in range(1,10):
if is_valid(puzzle,guess,row,col): #check if the guess is valid
puzzle[row][col]=guess
#recursively calls the function
if solve_sudoku(puzzle):
return True
#if not valid then we need to backtrack and try a new number
puzzle[row][col]= -1
#if this puzzle is unsolvable
return False
if __name__ == '__main__':
example_board= [
[-1,-1,-1, -1,-1,-1, 2,-1,-1],
[-1,8,-1, -1,-1,7, -1,9,-1],
[6,-1,2, -1,-1,-1, 5,-1,-1],
[-1,7,-1, -1,6,-1, -1,-1,-1],
[-1,-1,-1, 9,-1,1, -1,-1,-1],
[-1,-1,-1, -1,2,-1, -1,4,-1],
[-1,-1,5, -1,-1,-1, 6,-1,3],
[-1,9,-1, 4,-1,-1, -1,7,-1],
[-1,-1,6, -1,-1,-1, -1,-1,-1]
]
print(solve_sudoku(example_board))
print(example_board) | true |
bf517b7e68dfbe6a48daae41e430347ef587a705 | pawarspeaks/HackFest21 | /Python Scripts/caesar_cypher.py | 1,458 | 4.21875 | 4 | LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(string, shift=1):
'''
Caesar Cypher shifts the letters by the given shift, for example, if key=1
then, a becomes b, be becomes c, and c becomes d, etc
'''
assert 1<=shift<26
words = string.split() #Splitting by spaces
words_list = []
for word in words:
current_word = ''
for letter in word:
letter = letter.upper()
index = LETTERS.index(letter)+shift
current_word += LETTERS[index%26]
words_list.append(current_word)
return ' '.join(words_list)
def decrypt(string, shift):
words = []
for word in string.split():
print(f'Current word: {word}')
current_word = ''
for letter in word:
index = LETTERS.index(letter)
current_word += LETTERS[index-shift]
words.append(current_word)
return ' '.join(words)
def main():
choice = int(input("1) To Encrypt a String\n2) To Decrypt a string\nYour Choice: "))
if choice == 1:
string = input("Enter the string you want to encrypt: ")
shift = int(input("Enter the value of shit: "))
print(encrypt(string, shift))
elif choice == 2:
string = input("Enter the string you want to decrypt: ")
shift = int(input("Enter the value of shit: "))
print(decrypt(string, shift))
else:
print("Wrong Choice!")
if __name__ == "__main__":
main() | false |
d0e291e25712d09f036e15c53ccb1b720503a670 | pawarspeaks/HackFest21 | /Patterns/multi_piramids.py | 332 | 4.28125 | 4 | col= int(input(" Enter number of columns :"))
pir=int(input("Enter number of pyramids"))
print("generated patter is :\n")
# for example use col=80, pir=5
d=col//pir
for i in range(1, d):
for j in range(1, col):
if(j%(d) <(d-i)):
print(" ", end="")
else:
print("$", end="")
print("")
| false |
14d525d7f862716a24403593c8947c625ee25d3b | kbaeten/Intro_to_python | /Python_101/class_code_day2.py | 275 | 4.125 | 4 | import pandas as pd
#looping through str
#loop through letters
for letter in str:
print letter
#loop through words
for word in str.split():
print word
df = pd.read_csv('/Users/MikeLewis/Intro_to_python/us-united-states/8--co-colorado--rocky-mountains/beers.csv')
| false |
153545782afcc61355590a13e7a5a43eb8d70d4a | amasterous/for_dan | /main.py | 1,343 | 4.15625 | 4 | starting_home = int(input("введите номер дома откуда начинаем: "))
ending_home = int(input("введите номер дома до которого идём: "))
result = 0
if starting_home < ending_home:
if starting_home % 2 == 0 and ending_home % 2 == 0:
result = int((ending_home-starting_home) / 2)
elif starting_home % 2 == 0 and ending_home % 2 != 0:
starting_home -= 1
result = int((ending_home - starting_home) / 2)
elif starting_home % 2 != 0 and ending_home % 2 == 0:
starting_home += 1
result = int((ending_home - starting_home) / 2)
elif starting_home % 2 != 0 and ending_home % 2 != 0:
result = int((ending_home - starting_home) / 2)
else:
print("watafaaaaak")
else:
if starting_home % 2 == 0 and ending_home % 2 == 0:
result = int((starting_home-ending_home) / 2)
elif starting_home % 2 == 0 and ending_home % 2 != 0:
ending_home += 1
result = int((starting_home - ending_home) / 2)
elif starting_home % 2 != 0 and ending_home % 2 == 0:
ending_home -= 1
result = int((starting_home- ending_home) / 2)
elif starting_home % 2 != 0 and ending_home % 2 != 0:
result = int((starting_home - ending_home) / 2)
else:
print("watafaaaaak")
print(result)
| false |
4807360e6b9e934472a8df29a7afd25fd53ef962 | ShaneKelly89/Programming2021Coursework | /Week_06Task/function.py | 461 | 4.25 | 4 | # Write a program that takes a positive floating-point number as input and outputs an
# approximation of its square root.
#This is part 1 of this program, where I will create a function used to approximate square root.
#Author Shane Kelly
def sqRt(number, number_iters = 500):
a = float(number) #the number we will be getting the square root on
for i in range(number_iters):
number = 0.5 * (number + a / number)
return number
print(sqRt(9)) | true |
ae911458aa5a343fd8fc74b1b2756413f9f0ce07 | ShaneKelly89/Programming2021Coursework | /Week_02/hello2.py | 279 | 4.15625 | 4 | #Hello2.py
#This file will read in a person’s name and prints out hello 'name'
#Author - Shane Kelly
name = input("Enter your Name\n")
print ('Hello ' + name + '\nNice to meet you')
#Or alternatively you could 'print' as follows
print ('Hello {}\nNice to meet you'.format(name))
| true |
1b48be4bc4f3dd1ab16fcc4d0ba412d481453cc3 | ShaneKelly89/Programming2021Coursework | /Week_07/json01.py | 421 | 4.15625 | 4 | #Using json module for the first time
#Json can be used to store more complicated data structures and store them in a readable way
#This program will hold a function which stores a simple Dict to a file as JSON
#Author Shane Kelly
import json
filename = "testdic.json"
sample = dict(name='fred', age=31, grades= [1,34,55])
def writeDict(obj):
with open(filename, 'wt') as f:
json.dump(obj,f)
writeDict(sample) | true |
d8c62c57e6272631114fa1cfaa949358ee6f112d | abccba123/my_projects | /Chp6_20.py | 525 | 4.3125 | 4 | '''
(Geometry: display angles) Rewrite Listing 2.9, ComputeDistance.py, using the
following function for computing the distance between two points.
def distance(x1, y1, x2, y2):
'''
import math
def distance(x1, y1, x2, y2):
distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
return distance
x1, y1 = eval(input("Enter the fist point in (x1, y1) format: "))
x2, y2 = eval(input("Enter the second point in (x2, y2) format: "))
print("The distance between the two point is: ", distance(x1, y1, x2, y2))
| true |
0a7d10d4d1135476167c23a91d5e8f00365fa4f7 | abccba123/my_projects | /Chp4_6.py | 620 | 4.21875 | 4 | '''
(Health application: BMI ) Revise Listing 4.6, ComputeBMI.py, to let users enter
their weight in pounds and their height in feet and inches. For example, if a person
is 5 feet and 10 inches, you will enter 5 for feet and 10 for inches.
'''
intWeight = eval(input("Enter weight in pounds: "))
intFeet = eval(input("Enter feet: "))
intInches = eval(input("Enter inches: "))
floatHeight = (intFeet*12) + intInches
bmi = (intWeight/floatHeight**2)*703
print("Bmi is:", bmi)
if bmi < 18.5:
print("You are Underweight")
elif bmi < 25:
print("You are Normal")
elif bmi < 30:
print("You are overweight")
print()
| false |
f75d123535a5837a3cdc319bf0b3d31e2af06138 | abccba123/my_projects | /Chp5_20.py | 972 | 4.34375 | 4 | '''
(Display four patterns using loops) Use nested loops that display the following
patterns in four separate programs:
Pattern A Pattern B Pattern C Pattern D
1 1 2 3 4 5 6 1 1 2 3 4 5 6
1 2 1 2 3 4 5 2 1 1 2 3 4 5
1 2 3 1 2 3 4 3 2 1 1 2 3 4
1 2 3 4 1 2 3 4 3 2 1 1 2 3
1 2 3 4 5 1 2 5 4 3 2 1 1 2
1 2 3 4 5 6 1 6 5 4 3 2 1 1
'''
print("Pattern A")
for m in range(1,7):
for n in range(1, m+1):
print(n, end=' ')
print("")
print("Pattern B")
for m in range(6, 0, -1):
for n in range(1, m+1):
print(n, end=' ')
print("")
print("Pattern C")
for m in range(1, 6+1):
for n in range(6, 0, -1):
print(n if n < m else " ", end=' ')
print()
print("Pattern D")
for m in range(6, 0, -1):
for n in range(1, m+1):
print(n, end=' ')
print("")
| false |
0f6b4d441b142ccad4abf5948dd5a4fde33b6a5e | ExCurio/Codecademy_Python_Course | /Codecademy_Week3Day1_Sals Shipping.py | 1,147 | 4.125 | 4 | #Week 3, Day 1 - Project: Sal's Shipping
def cost_of_ground_shipping(weight):
if weight <= 2:
price_per_pound = 1.50
elif weight <= 6:
price_per_pound = 3.00
elif weight <= 10:
price_per_pound = 4.00
else:
price_per_pound = 4.75
return 20 + (price_per_pound * weight)
cost_of_premium_ground_shipping = 125.00
def cost_of_drone_shipping(weight):
if weight <= 2:
price_per_pound = 4.50
elif weight <= 6:
price_per_pound = 9.00
elif weight <= 10:
price_per_pound = 12.00
else:
price_per_pound = 14.25
return price_per_pound * weight
def print_cheapest_shipping(weight):
ground = cost_of_ground_shipping(weight)
premium = cost_of_premium_ground_shipping
drone = cost_of_drone_shipping(weight)
if ground < premium and ground < drone:
method = "Ground shipping"
cost = ground
elif premium < ground and premium < drone:
method = "Premium shipping"
cost = premium
else:
method = "Drone shipping"
cost = drone
print("The cheapest shipping rate available is $%.2f with %s." % (cost, method))
print_cheapest_shipping(4.8)
print_cheapest_shipping(41.5) | false |
3193a08dc238dd65c1e54318fe5045d0996933c7 | sanathanan/Ineuron_Assignments | /Assignment_4/Question_1.1.py | 994 | 4.34375 | 4 | """
1.1 Write a Python Program(with class concepts) to find the area of the triangle
using the below formula.area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
Function to take the length of the sides of triangle from user should be defined
in the parent class and function to calculate the area should be defined in subclass.
"""
# Parent Class
class Length_of_Sides_of_Traingle:
def __init__(self):
self.a = int(input("Enter the length of side a: "))
self.b = int(input("Enter the length of side b: "))
self.c = int(input("Enter the length of side c: "))
# Child class inheriting the properties of Parent class
class Area_of_Triangle(Length_of_Sides_of_Traingle):
def area(self):
s = (self.a + self.b + self.c) /2
area = (s*(s-self.a)*(s-self.b)*(s-self.c)) ** 0.5
return area
a1=Area_of_Triangle() # Creating an object for child class
print("The area of traingle is", a1.area())
| true |
4b3856d07b7bc5cfee2164293a9b10cd3ee14284 | sanathanan/Ineuron_Assignments | /Assignment_4/Question_1.2.py | 810 | 4.1875 | 4 | """
1.2 Write a function filter_long_words() that takes a list of words and an
integer n and returns the list of words that are longer than n.
"""
# Using Function
def filter_long_words(lst_of_words,num):
l1=[]
txt= lst_of_words.split(" ")
for i in txt:
if len(i) > num:
l1.append(i)
return l1
lst_of_words = input("Enter the Words in String Format: ")
num = int(input("Enter the length of the words you need: "))
longer_words = filter_long_words(lst_of_words,num)
print(longer_words)
# Using Filter and lamda function
def filter_long_words(str,num):
return filter(lambda x: len(x)>num, str)
longer_words = filter_long_words(["The", "quick","brown","fox","jumps","over","the","lazy","dog"],3)
print(list(longer_words)) | true |
30780b7eac41ce2de065e79f846237bc91b624db | gadodia/Algorithms | /algorithms/Strings/reverseWithSpecials.py | 1,009 | 4.46875 | 4 | '''
Given a string, that contains special character together with alphabets (a to z and A to Z), reverse the string in a way that special characters are not affected.
Examples:
Input: str = "a,b$c"
Output: str = "c,b$a"
Note that $ and , are not moved anywhere.
Only subsequence "abc" is reversed
Input: str = "Ab,c,de!$"
Output: str = "ed,c,bA!$"
Time: O(n)
Space: O(n) -> converting string to list
'''
class Solution:
def reverseStr(self, str):
str = list(str)
i, j = 0, len(str)-1
while i <= j:
while i < len(str) and not str[i].isalpha():
i += 1
while j >= 0 and not str[j].isalpha():
j -= 1
if i <= j:
str[i], str[j] = str[j], str[i]
i += 1
j -= 1
return ''.join(str)
print(Solution().reverseStr('abcdefgh'))
print(Solution().reverseStr('abcd$fgh'))
print(Solution().reverseStr('@#$abcd$fgh*'))
print(Solution().reverseStr('Ab,c,de!$'))
| true |
e34f029b02c1718a8c9a7f5d7934a34bd904f338 | gadodia/Algorithms | /algorithms/Arrays/3numsort.py | 682 | 4.125 | 4 | '''
This problem was recently asked by Google:
Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Time: O(n)
Space: O(1)
'''
def sortNums(nums):
if not nums:
return nums
p0, p1, p2 = 0, 0, len(nums)-1
while p1 <= p2:
if nums[p1] == 1:
nums[p0], nums[p1] = nums[p1], nums[p0]
p0 += 1
p1 += 1
elif nums[p1] == 3:
nums[p1], nums[p2] = nums[p2], nums[p1]
p2 -= 1
else:
p1 += 1
return nums
print(sortNums([3, 3, 2, 1, 3, 2, 1]))
# [1, 1, 2, 2, 3, 3, 3]
| true |
1c4b5de91180b76e425bbe4f80c91f0434665f1f | ravi4all/PythonWE_EveningAug | /IfElse/LogicalOperators.py | 385 | 4.15625 | 4 | # AND, OR, NOT
while True:
msg = input("Enter your message : ")
if msg == "hello" or msg == "hey" or msg == "hi":
print("Hi There...")
elif msg == "bye" or msg == "bie" or msg == "see you":
print("Bye")
elif msg == "python" or msg == "java" or msg == "php":
print("Programming language")
else:
print("I don't understand") | true |
e8b9ffac555a5ce978082744eb7d209972404570 | ravi4all/PythonWE_EveningAug | /01-Python/PrintStrinfs.py | 379 | 4.25 | 4 | firstname = input("Enter first name : ")
lastname = input("Enter last name : ")
# msg = "Hello" + " " + firstname.lower() + " " + lastname.lower()
# msg = "Hello" + " " + firstname.swapcase() + " " + lastname.swapcase()
# msg = "Hello" + " " + firstname.upper() + " " + lastname.upper()
#print(msg)
print("Hello {} {}".format(firstname.upper(), lastname.upper()))
| false |
72c0a3337d3a3b58de0a31cfc07673a5716e665e | water-sect/python_book_exercise | /pg_322_7.1_list-methods.py | 523 | 4.1875 | 4 | def main():
name_list = []
again = 'y'
while again == 'y':
name = input("Enter a name: ")
name_list.append(name)
print('Do you want to add another name ?')
again = input('y = yes, anything else = no: ')
print(name_list)
name_list.insert(8, "Ramesh")
print("In the name_list the index of Ramesh is given below.")
print(name_list.index('Ramesh'))
print("Here are the names you entered.")
for name in name_list:
print(name)
main() | true |
8c7199ce8a9f1a8f8ec9605e39eae135822a6064 | odai1990/data-structures-and-algorithms | /Data-Structures/trees/trees/queue.py | 1,292 | 4.15625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
'''
create a constructor
'''
self.front = None
self.rear = None
def enqueue(self, value):
'''
enqueue method to add element to queue
'''
node = Node(value)
if self.rear is None:
self.front = node
self.rear = node
else:
node.next=self.rear
self.rear = node
def dequeue(self):
'''
dequeue method to return and delete first element in queue
'''
if self.rear is None:
raise Exception('You cant dequeue from empty queue')
else:
if self.rear == self.front:
temp= self.front.value
self.front=None
self.rear=None
return temp
else:
temp =self.front.value
current=self.rear
while current.next.next:
current=current.next
self.front=current
self.front.next=None
return temp
| true |
d1bb79104e93a4ca2d5c78ea1f681f4ac1040374 | aryan68125/python-GUI-programs | /full_app_scrollbar_with_scrollable_widgets.py | 1,299 | 4.46875 | 4 | from tkinter import *
from tkinter import ttk
window = Tk()
window.title("full app scroll bar")
#inorder to add a scrollbar to our application
#step 1 create a main frame which holds everything
#.pack(fill=BOTH,expand=True) frame will fill the entire application window
main_frame = Frame(window).pack(fill=BOTH,expand=True)
#step 2 create a canvas
canvas = Canvas(main_frame)
canvas.pack(side=LEFT,fill=BOTH,expand=True)
#step 3 add a scrollbar to the canvas
#set the scrollbar to the main frame
#set the yScroll to the canvas and not to the main frame
Scrollbar = ttk.Scrollbar(main_frame,orient=VERTICAL,command = canvas.yview)
Scrollbar.pack(side=RIGHT,fill=Y)
#step 4 configure the canvas so that it has the scrollbar
canvas.configure(yscrollcommand = Scrollbar.set)
#now we need to bind this configure (Lambda e is the event)
canvas.bind("<Configure>", lambda e : canvas.configure(scrollregion = canvas.bbox("all")))
#step 5 then we are going to create another frame inside the canvas
second_frame = Frame(canvas)
#step 6 then we will add that new frame to the window in our canvas
canvas.create_window((0,0),window=second_frame,anchor="nw")
#create 100 buttons
for i in range(100):
Button(second_frame, text=f"Button {i}").grid(row=i,column=0,padx=3,pady=5)
window.mainloop() | true |
f26af0766383d41082c0f8f45f693cec783e9cf2 | AFRothwell/Initial-Commit | /lambda_practice/question_2.py | 476 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 15:40:28 2021
@author: Andrew Rothwell
"""
'''
Write a Python program to create a function that takes one argument, and that
argument will be multiplied with an unknown given number.
'''
def func1(arg1):
return lambda λ : λ * arg1
'''
Calling the function with lambda in it allows us to define a variable that
will take an argument for the value of lambda later
'''
# arg 1 = 2
result = func1(2)
# λ = 15
print(result(15)) | true |
0bc0831587b683ae6b613d2b364025e113bbc41f | AFRothwell/Initial-Commit | /Object Oriented Programming/OOP 1.py | 1,777 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 10:37:37 2021
@author: Andrew Rothwell
"""
'''
-------------------------------------------------------------------------------
Python Object-Oriented Programming (OOP)
Exercise: Classes and Objects Exercises
-------------------------------------------------------------------------------
Source: https://pynative.com/python-object-oriented-programming-oop-exercise/
Python Object-oriented programming (OOP) is based on the concept of “objects,”
which can contain data and code:
Data in the form of instance variables
(often known as attributes or properties).
Code in the form method: I.e., Using OOP, we encapsulate related
properties and behaviors into individual objects.
This OOP exercise covers questions on the following topics:
- Class and Object creation
- Instance variables and Methods, and Class level attributes
- Model systems with class inheritance i.e., inherit From Other Classes
- Parent Classes and Child Classes
- Extend the functionality of Parent Classes using Child class
- Object checking
References
- https://pynative.com/python-object-oriented-programming/
- https://pynative.com/python-inheritance/
-------------------------------------------------------------------------------
OOP Exercise 1
-------------------------------------------------------------------------------
Create a class - "Vehicle"
with 2 attributes - "max_speed" and "mileage".
-------------------------------------------------------------------------------
'''
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
modelX = Vehicle(240, 18)
print(modelX.max_speed, modelX.mileage)
| true |
758e348264670ff40c8b2a149a8d213386c99e23 | prasadnh/samples | /differentsmallsamples.py | 2,602 | 4.46875 | 4 | st = 'Print only the words that start with s in this sentence'
#Code here
for word in st.split():
if word[0] == 's':
print word
#Use range() to print all the even numbers from 0 to 10.
#Code Here
for num in range(0,10):
if (num % 2 == 0):
print num
range(0,11,2)
#Use List comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.
#Code in this cell
lst = [num for num in range(1,50) if num % 3 == 0]
lst
**Go through the string below and if the length of a word is even print "even!"**
st = 'Print every word in this sentence that has an even number of letters'
#Code in this cell
for word in st.split():
if len(word) % 2 == 0:
print 'this word %s has even number' %word
#Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz".
#For numbers which are multiples of both three and five print "FizzBuzz".
#Code in this cell
for num in range(1,100):
if num %3 == 0 and num % 5 == 0:
print 'FizzBuzz'
elif num % 5 == 0:
print 'Buzz'
elif num % 3 == 0:
print 'Fizz'
#Use List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
#Code in this cell
for word in st.split():
print word[0]
print st
[word[0] for word in st.split()]
def is_prime(val):
"""
INPUT: A number
OUTPUT: prints prime or not
This function checks for prime numbers
"""
lst = []
for num in range(1,val):
if num <= 1:
print str(num) + ' is not a prime number'
elif num == 2:
print str(num) + ' is prime number'
lst.append(num)
else:
for n in range(2, num):
if num % n == 0:
print '%s is Not a Prime number' %num
break
else:
print 'The number %s is prime' %num
lst.append(num)
print lst
l = [1,1,1,1,2,2,3,3,3,3,4,5]
def unique_list(l):
#return set(l)
x = []
for num in l:
if num not in x:
x.append(num)
return x
unique_list(l)
def palindrome(s):
return s[::-1]
def palindrome(s):
#return s[::-1]
s=s.replace(" ", "")
return s[::-1]
import string
str1 = "The quick brown fox jumps over the lazy dog"
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower()) | true |
404f3ea323bbd07c9b78659ce221890d8698da81 | MohammedTarafdar/BasicPython | /operatorsExample/ArithmeticOperators.py | 1,018 | 4.53125 | 5 |
"""
Arithmetic Operators are as follows:
"+" => addition
"""
num1 = 6
num2 = 7
num3 = 20
num4 = 5
num5 = 3
num6 =2
Total = num1+num2
print( Total)
print("*****************")
"""
"-" => subtraction
"""
sum_of_two_number = num3 - num2
print(sum_of_two_number)
print("*****************")
"""
" * " => multiplication
"""
multi_of_two_number = num1 * num2
print(multi_of_two_number)
print("*****************")
"""
" / " => division
"""
division1_of_two_number = num3 / num4
division2_of_two_number = num2 / num5
print(division1_of_two_number)
print(division2_of_two_number)
print("*****************")
"""
" % " => reminder
"""
rem_of_two_number = num1 % num4
print(rem_of_two_number)
print("*****************")
"""
" // " => floor division
"""
div1 = num2 / num5
print(div1)
print("*****************")
div2 = num2 // num5
print(div2)
print("*****************")
"""
" ** " => exponent
"""
exponent_value1 = num5 ** num6
exponent_value2 = num1 ** num6
print(exponent_value1)
print(exponent_value2)
| false |
f5ceaebad0f9375073daaa7376e6872aee4c3a96 | JustinHodge/C950 | /hash_table.py | 2,243 | 4.25 | 4 | # this contains the class definitions for a custom Hash Map
class HashMap:
# we will initialize an empty hash with an optional parameter to adjust the map size if needed
# O(1)
def __init__(self, map_size=40):
self.map = []
for i in range(map_size):
self.map.append([])
# this private method is only used to find what map container any key passed in should exist at
# O(1)
def _create_hash(self, key):
map_container = int(key) % len(self.map)
return map_container
# this method will associate a key-value pair and place them at the correct location in the map
# O(1)
def insert_item(self, key, value):
hash_value = self._create_hash(key)
self.map[hash_value] = [key, value]
# this method will find a key value in the map and replace any member there with an empty space
# O(1)
def delete_item(self, key):
hash_value = self._create_hash(key)
self.map[hash_value] = []
# This method takes in a variable number of args consisting of keys in the map
# it will return a list of values associated with those keys
# O(N)
def get_value(self, *args):
return_list = []
for key in args:
hash_value = self._create_hash(key)
if self.map[hash_value] is None:
return_list.append(None)
else:
return_list.append(self.map[hash_value][1])
return return_list
# this method will return a list consisting of all values for each possible map location.
# O(N)
def get_all_values(self):
return [item[1] for item in self.map]
# this method will return a list of all keys found in each possible location of the map
# O(N)
def get_keys(self):
return [item[0] for item in self.map]
# this method is a simple output helper for showing a maps contents in a human readable form.
# O(1)
def __str__(self):
string_representation = ''
for i in self.map:
string_representation += str(i[0])
string_representation += " : "
string_representation += str(i[1])
string_representation += "\n"
return string_representation
| true |
b689681153e746bfcc43e2738c165b37fcc39019 | AnimeshGA/PyhtonProjects | /area of cirlce.py | 241 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 10 22:55:35 2021
@author: Royal
"""
from math import pi
r = float(input("Input the radius of the circle : "))
print("The area of the circle with radius"+ str(r)+"is:"+ str(pi*r**2)) | true |
c04e2ee1b680dc96aef593f08a17040460b32f63 | kkmjkim/python-for-coding-test | /pythonTutorial/lib_itertools.py | 970 | 4.1875 | 4 | ###########################################################################################
# itertools: deals with iterative data
# most useful classes in coding tests: permutation, combination
from itertools import permutations, combinations, product
data = ['A', 'B', 'C'] # 데이터 준비
result = list(permutations(data, 3)) # 모든 순열 구하기
print(result)
result = list(permutations(data, 2)) # # 2개를 뽑는 모든 순열 구하기 (중복 X)
print(result)
result = list(product(data, repeat=2)) # 2개를 뽑는 모든 순열 구하기 (중복 허용)
print(result)
result = list(combinations(data, 2)) # 2개를 뽑는 모든 조합 구하기
print(result)
###########################################################################################
###########################################################################################
###########################################################################################
| false |
e97a5a8cd857158f0644553d070300d91fa87a8a | sheamus-hei/whiteboarding | /trees-and-graphs/level_max_value.py | 1,743 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
# 1
# / \
#2. 3
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
def print_nodes(root):
if root:
print(root.data)
print_nodes(root.left)
print_nodes(root.right)
# print_nodes(tree)
# Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
# Example 1:
# Input: root = [1,3,2,5,3,null,9]
# Output: [1,3,9]
# Example 2:
# Input: root = [1,2,3]
# Output: [1,3]
# Example 3:
# Input: root = [1]
# Output: [1]
# Example 4:
# Input: root = [1,null,2]
# Output: [1,2]
# Example 5:
# Input: root = []
# Output: []
# method to find how tall a tree is
def height(node):
if not node:
return 0
l_height = height(node.left)
r_height = height(node.right)
return max(l_height, r_height) + 1
# following two methods print breadth first traversal
# source: https://www.geeksforgeeks.org/level-order-tree-traversal/
def evaluate_level(root, level, max):
if not root:
return
print("node", root.data, "level tracker", level)
if level == 0:
if root.data > max[0]:
max[0] = root.data
elif level > 0:
evaluate_level(root.left, level - 1, max)
evaluate_level(root.right, level - 1, max)
import sys
def find_largest_val(root):
h = height(root)
output = []
for i in range(h):
print("i equals", i)
current_max = [-sys.maxsize]
evaluate_level(root, i, current_max)
output.append(current_max[0])
return output
# Input: root = [1,3,2,5,3,null,9]
tree = Node(1)
tree.left = Node(3)
tree.right = Node(2)
tree.left.left = Node(5)
tree.left.right = Node(3)
tree.right.right = Node(9)
print(find_largest_val(tree)) | true |
661a9fb613952159f5c7f15c58935524a5c03709 | sheamus-hei/whiteboarding | /trees-and-graphs/mirror_tree.py | 1,229 | 4.25 | 4 | # Problem from LeetCode: https://leetcode.com/problems/symmetric-tree/
# Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
# Example 1:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
# -> True
# Example 2:
# 1
# / \
# 2 2
# / /
# 3 3
# -> False
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_mirror(root):
return check_halves(root.left, root.right)
def check_halves(left, right):
if not left and not right:
return True
if left and right:
if left.data == right.data:
left_half = check_halves(left.left, right.right)
right_half = check_halves(left.right, right.left)
return left_half and right_half
return False
tree1 = TreeNode(1)
tree1.left = TreeNode(2)
tree1.right = TreeNode(2)
tree1.left.left = TreeNode(3)
tree1.right.right = TreeNode(3)
tree1.left.right = TreeNode(4)
tree1.right.left = TreeNode(4)
tree2 = TreeNode(1)
tree2.left = TreeNode(2)
tree2.right = TreeNode(2)
tree2.left.left = TreeNode(3)
tree2.right.left = TreeNode(3)
print(is_mirror(tree1))
print(is_mirror(tree2))
| true |
7866945da85549f6f429e7799cf0cd8808bb3beb | sheamus-hei/whiteboarding | /misc/valid_parens.py | 1,025 | 4.15625 | 4 |
# Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
# Example 1:
# Input: s = "(()"
# Output: 2
# Explanation: The longest valid parentheses substring is "()".
# Example 2:
# Input: s = ")()())"
# Output: 4
# Explanation: The longest valid parentheses substring is "()()".
# Example 3:
# Input: s = ""
# Output: 0
def find(s, backwards):
curr_s = ""
count = 0
max = 0
key = {
"(": 1 - int(backwards) * 2,
")": -1 + int(backwards) * 2
}
for i in range(len(s)):
value = s[i] #(
if backwards:
value = s[-i]
count += key[value] # +1 = 1
# print(value, count, curr_s)
if count < 0:
# reset
curr_s = ""
count = 0
else:
curr_s += value
# evaluate
if count == 0 and len(curr_s) > max:
max = len(curr_s)
return max
def longest_paren(s):
if len(s) < 2:
return 0
return max(find(s, True), find(s, False))
print(longest_paren("((())(()"))
| true |
6a111878778d81af0cb3b32892ca861ec3e9f545 | jobkinyua21/text-transform-with-no-prints | /3b.py | 430 | 4.125 | 4 | # import sys
import sys
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words)).upper()
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
line = input("enter sentence: ")
sys.stdout.write(rev_sentence(line))
| true |
05a78d139e5ad49d0612318801d813bd1f91278b | leahlang4d/tic_tac_toe | /tic_tac_toe.py | 1,828 | 4.21875 | 4 | '''
Tic tac toe game against the computer
'''
def makegrid(board):
print(' | ')
print(''+ board[7] + ' | ' + ''+ board[8]+' | '+''+board[9])
print(' | ')
print(''+ board[4]+ ' | '+''+ board[5]+' | '+''+board[6])
print(' | ')
print(''+ board[1]+ ' | '+ ''+ board[2] +' | '+''+board[3])
def makeachoice():
print("Welcome to Tic Tac Toe! Please Enter an X or O to get this game started!")
letter = input().upper()
if letter == 'X':
print("You are X and the Computer will be O")
return ['X','O']
elif letter == 'O':
print("You are O and the Computer will be X")
return ['O', 'X']
else:
print("Please enter an X or O")
def comp_or_player_first( ):
if random.randint(0,1) == 1:
return 'player'
else:
return 'computer'
def play_again():
print("Do you want to play again? (yes or no)")
#starts with is used to check if a string starts with a certain string or character
return input().lower().startswith('y')
def makeamove(board, move,letter):
board[move] = letter
def is_winner(board_pos, play_lett):
return((board_pos[7] == play_lett and board_pos[8] == play_lett and board_pos[9] == play_lett) or
(board_pos[4] == play_lett and board_pos[5] == play_lett and board_pos[6] == play_lett) or
(board_pos[1] == play_lett and board_pos[2] == play_lett and board_pos[3] == play_lett) or
(board_pos[7] == play_lett and board_pos[5] == play_lett and board_pos[3] == play_lett) or #across from left
(board_pos[9] == play_lett and board_pos[5] == play_lett and board_pos[1] == play_lett) or #across from right
(board_pos[8] == play_lett and board_pos[5] == play_lett and board_pos[2] == play_lett))
| false |
cc5385b3e0f5a9a292ebfc118063971129d6d1cb | vasvi1203/PPL | /Assignment1/4_random.py | 880 | 4.53125 | 5 | '''Make a program that randomly chooses a number to guess and then the user will have a few chances to guess the number correctly. In each wrong attempt, the computer will give a hint that the number is greater or smaller than the one you have guessed.'''
import random
def guess_num(n) :
while True :
guess = int(input('Guess the number : '))
if guess == n :
print('You guessed the right number!')
break
elif guess > n:
print('You guessed the wrong number!')
print('Hint : The number is smaller than %d\n' %(guess))
elif guess < n:
print('You guessed the wrong number!')
print('Hint : The number is greater than %d\n' %(guess))
if __name__ == '__main__' :
ran = input('Enter the range in which you want to guess the number separated by a space :\n').split()
s = int(ran[0])
e = int(ran[1])
n = random.randint(s, e)
guess_num(n)
| true |
812a62956dd1cbef9e87d18b10c971b87ad45271 | phouse512/bounded-queue | /queue.py | 1,791 | 4.125 | 4 | class Queue:
""" A bounded queue implementation in Python using only arrays and integers.
Attributes:
current_size: An integer representing the current size of the queue
front: An integer that holds the index of the first element in the queue
back: An integer that holds the index of the last element in the queue
queue_array: An array of set size that holds the objects of the queue
"""
def __init__(self, size):
""" Initialize an empty queue of user-defined size """
self.queue_array = [None] * size
self.current_size = 0
self.front = 0
self.back = -1
def enqueue(self, value):
""" Attempts to add an integer to the queue
- return True if value successfully added
- retur False if queue is already full
"""
if self.current_size == len(self.queue_array): return False
self.back = self.__increment(self.back)
self.queue_array[self.back] = value
self.current_size += 1
return True
def dequeue(self):
""" Attempts to remove the first element from the queue
- return the 'oldest' item in the queue if not empty
- return False if the queue was already empty
"""
if self.current_size == 0: return False
to_return = self.queue_array[self.front]
self.front = self.__increment(self.front)
self.current_size -= 1
return to_return
def __increment(self, value):
""" increment moves the index that front/back holds up in
the case of enqueue or dequeue
- private method that returns the new index value
"""
return 0 if value == len(self.queue_array)-1 else value + 1
| true |
fd394c02d2b2cee07e518e829a25fca4ea11bebb | tiwariutkarsh422/python-advanced | /python-advanced/Shallow-deep-copying/shallow-deep-copy.py | 1,596 | 4.5625 | 5 | import copy
original_list = [2, 4 ,['ada lovelace'], 1965, [7,8,9], [11, 12, 13]]
''' Shallow copies can be created using factory function such as list(), dict() etc.
However shallow copies only create references to the child object present in the original lists.'''
shallow_copy_list = list(original_list)
print('original list before append:', original_list)
print('shallow copied list before append', shallow_copy_list)
print()
original_list.append(['new_append'])
print('original list after append:', original_list)
print('shallow copied list after append', shallow_copy_list)# appending value sin original copy does not affect shallow copy
print()
original_list[2][0] = 'Ed'
print('original list after specified change', original_list)
print('shallow copied list after specofied change:', shallow_copy_list)
print()
''' As we can see above that since shallow copy is a one level deep copy, it
is not truly independent of the original list and it changes the shallow
copied list as well when original list is modified as it is only a reference
to the child objects of original_list before the append.'''
original_list = [2, 4 ,['ada lovelace'], 1965, [7,8,9], [11, 12, 13]]
''' Deep copy can be created usinfg deepcopy() function of copy module.'''
deep_copy_list = copy.deepcopy(original_list)
print('original list before change:', original_list)
print('deep copied list before change', deep_copy_list)
print()
original_list[2][0] = 'Ed'
print('original list after specified change', original_list)
print('deep copied list after specified change:', deep_copy_list)
| true |
57d8d96d26bd705a265a961c96f89fc51370cd90 | ankidwiv/shell_Script | /exe3ex1.py | 437 | 4.40625 | 4 | #!/usr/bin/python
print "I will now count chickens:"
print "Hens", 25 + 30 / 6
print "Rosters", 100.0-25*3%4
print 'Now I wil count the eggs:'
print 3+2+1-5+4%2-1/4+6
print 'Is it true that 3+2< 5-7?'
print 3+2<5-7
print 'what is 3+2?', 3+2
print 'what is 5-7?', 5-7
print "oh, that's why its false."
print "How about some more."
print " IS it greater?", 5>-2
print "Is is greater or equal?", 5>=-2
print "Is is less or equal?", 5 <= -2
| true |
5e3355c71d7b259868b2cab0c6a9c5f36926dbc7 | flmscs/Summer_2021_Python | /3_2_even_or_odd.py | 311 | 4.3125 | 4 | n = int (input ('enter a number: ')) #set n to be the number entered by the user
r = n % 2 #set r to be the remainder when n is divided by 2
if r == 0: #if the remainder is equal to 0, then print 'even'
print ('n is even')
else: #if the remainder is not equal to 0, then print 'odd'
print (' n is odd')
| true |
6deb25bcd2c85c323887b608bdb228411c8cb93d | HareemArsh/ps-1 | /ps1b.py | 1,097 | 4.46875 | 4 | #Saving, with a raise
annual_salary = float(input("kindly Enter your annual sallary : "))
#portion_saved is the certain amount of salary you saved for payment
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
#the total cost of your dream house
total_cost = float(input("Enter the cost of your dream home: "))
semi_annual_raise = float(input("Enter the semi annual raise , as a decimal:"))
portion_down_payment = 0.25 * total_cost
current_savings = 0 #the amount you have saved
months = 0 #nno. of months to save money to make down_payment
r = 0.04 #investments earn a Annual return of r
while current_savings < portion_down_payment:
monthly_sallary = annual_salary / 12
monthly_return = (monthly_sallary) * portion_saved #additional savings at end of month to put in saving
additional_savings = (current_savings*r/12)
current_savings += monthly_return + additional_savings
months += 1
if months % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
print("No. of month :" , months)
| true |
b44880ac792f2d4be52dacdda49c3dd36a641133 | ewoodworth/calculator-1 | /arithmetic.py | 1,078 | 4.375 | 4 | def add(num1, num2):
"""Add two numbers
Add num1 to num2 to get an integer output"""
return num1 + num2
def subtract(num1, num2):
"""Find the difference between two numbers
Subtract num2 from num1 to get an integer output"""
return num1 - num2
def multiply(num1, num2):
"""Find the product of two numbers
Multiply num1 by num2 to get an integer output
"""
return num1 * num2
def divide(num1, num2):
"""Find the quotient of two numbers
Divide num1 by num2 to get a float
"""
return float(num1) / float(num2)
def square(num1):
""" Square a number.
Square num1 to get an integer output
"""
return num1 * num1
def cube(num1):
""" Cube a number
Cube num1 to get an integer output
"""
return num1 ** 3
def power(num1, num2):
"""Find the nth power of a number
Raise num1 to the power of num2 to get an integer output
"""
return num1 ** num2
def mod(num1, num2):
"""Find the remainder after the division of two numbers
Returns the remainder integer after dividing num1 by num2
"""
return num1 % num2
print mod(7,4)
| true |
2113be0149b3d61cc54901cdd7fde0720f3f1593 | ciarabautista/WWCodeManila-Python | /basic_concepts/samples/my_strings.py | 380 | 4.34375 | 4 | firstname = "Adam"
lastname = "Dough"
# We can access each character by using <your string>[<index>]
# Each character in a string is represented by an index number
# starting from 0
print(firstname[0], firstname[1])
print(lastname[0], lastname[1])
# TRY TO PRINT THE LAST CHARACTER
#
# TRY TO PRINT AN INDEX GREATER THAN THE LENGTH BY UNCOMMENTING THE CODE BELOW
# firstname[10]
| true |
e323633d3ac7d6ee6c561ecffc81b947d94537d9 | lucaspereirag/pythonProject | /ex033.py | 507 | 4.15625 | 4 | num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite o segundo número: '))
num3 = float(input('Digite o terceiro número: '))
if num1 > num2 and num1 > num3:
print('Número 1 é maior.')
elif num2 > num1 and num2 > num3:
print('Número 2 é maior')
else:
print('Número 3 é maior.')
if num1 < num2 and num1 < num3:
print('Número 1 é menor.')
elif num2 < num1 and num2 < num3:
print('Número 2 é menor')
else:
print('Número 3 é menor.')
| false |
400fe3146e7ed8a3a80e4c8e0bbc3b2e89a940d1 | 815382636/python_practice_notes | /pro_6.py | 2,225 | 4.125 | 4 | #自定义函数
#1.函数参数可以设置默认值
# 例:def func(param = 0) ----------------当传参时覆盖
#2.Python 是 dynamically typed 的,可以接受任何数据类型(整型,浮点,字符串等等),因此生产环境中一般要进行数据类型判断
# if not isinstance(l, list):
# print('input is not type of list')
#3.Python支持函数嵌套
#def f1():
# print('hello')
# def f2():
# print('world')
# f2()
#函数嵌套的优势:
# (1)保证内部函数的隐私
# (2)合理的使用函数嵌套,能够提高程序的运行效率
#求阶乘,下面程序使用了函数嵌套,外部函数进行了类型判断,内部函数进行运算,如果不进行函数嵌套,那么每一步的递归都需要进行类型判断,降低了运行效率
def factorial(input):
# validation check
if not isinstance(input, int):
raise Exception('input must be an integer.')
if input < 0:
raise Exception('input must be greater or equal to 0' )
...
def inner_factorial(input):
if input <= 1:
return 1
return input * inner_factorial(input-1)
return inner_factorial(input)
#4.局部变量与全局变量
# (1)我们不能在函数内部随意改变全局变量的值。
#要修改全局变量的值,需要在函数内部用global再重新声明一遍
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
global MIN_VALUE
...
MIN_VALUE += 1
...
# (2)同样的,对于嵌套函数来说,里面的函数不能修改外部函数变量的值
#要修改外部函数变量的值,需要在里面的函数内部用nonlocal再声明一遍
def outer():
x = "local"
def inner():
nonlocal x # nonlocal关键字表示这里的x就是外部函数outer定义的变量x
x = 'nonlocal'
print("inner:", x)
inner()
print("outer:", x)
#5.闭包
#闭包常常和装饰器(decorator)一起使用。
def nth_power(exponent):
def exponent_of(base):
return base**exponent
return exponent_of
square =nth_power(2) #求2的平方
cube =nth_power(3) #求2的立方
print(square(2))
print(cube(2))
| false |
d180bdbe9567844cd5e00daea6c63542c33f26cc | 815382636/python_practice_notes | /pro_1.py | 2,624 | 4.34375 | 4 | #
#
# python学习笔记
#
# 一、
# 列表和元组基础
# 列表是动态的,长度大小不固定,可以随意地增加、删减或者改变元素(mutable)。
# 而元组是静态的,长度大小固定,无法增加删减或者改变(immutable)。
#
# Python 中的列表和元组都支持负数索引。
# 列表和元组都支持切片操作。 l[1:3]
# 两者也可以通过 list() 和 tuple() 函数相互转换
#
# count(item) 表示统计列表 / 元组中 item 出现的次数。index(item) 表示返回列表 /
# 元组中 item 第一次出现的索引。list.reverse() 和 list.sort() 分别表示原地倒转列表和排序(注意,元组没有内置的这两个函数)。
# reversed() 和 sorted() 同样表示对列表 / 元组进行倒转和排序,reversed() 返回一个倒转后的迭代器(上文例子使用 list() 函数再将其转换为列表);sorted() 返回排好序的新列表
# 元组不能增添与删除元素,列表可以
tup =(1,2,3,4)
tup1 =tup + (5,)
print(tup1)
list =[1,2,3,4]
list.append(5)
print(list)
# 元组和列表都支持负数索引
print(tup1[-1])
print(list[-1])
# 元组和列表都支持切片操作
print(tup1[1:3])
print(list[1:3])
# 元组和列表都可以随意嵌套
l =[(1,2),5]
print(l)
t =([1,2],5)
print(t)
# 元组和列表可以互相切换
# print(list(tup1)) -----------出现错误,因为使用了list变量
print(tuple(list))
# 列表和元组的内置函数 count 出现次数 index 第一次索引 reverse反转 sort排序
print(list.count(3))
print(list.index(3))
list.reverse()
print(list)
list.sort()
print(list)
# print(list(reversed(tup1)))
print(sorted(tup1))
# 列表比元组分配的空间要多,存储指针
l = [1, 2, 3]
print(l.__sizeof__())
tup = (1, 2, 3)
print(tup.__sizeof__())
# l = []
# l.__sizeof__() // 空列表的存储空间为40字节
# 40
# l.append(1)
# l.__sizeof__()
# 72 // 加入了元素1之后,列表为其分配了可以存储4个元素的空间 (72 - 40)/8 = 4
# l.append(2)
# l.__sizeof__()
# 72 // 由于之前分配了空间,所以加入元素2,列表空间不变
# l.append(3)
# l.__sizeof__()
# 72 // 同上
# l.append(4)
# l.__sizeof__()
# 72 // 同上
# l.append(5)
# l.__sizeof__()
# 104 // 加入元素5之后,列表的空间不足,所以又额外分配了可以存储4个元素的空间
# 为了减小每次增加 / 删减操作时空间分配的开销,Python 每次分配空间时都会额外多分配一些,
# 这样的机制(over-allocating)保证了其操作的高效性:增加 / 删除的时间复杂度均为 O(1)。
| false |
81de52b8604c2ad0266c6c53650ff0acbba460d5 | BlackBloodLT/URI_Answers | /Python3/1_INICIANTE/uri1012.py | 1,337 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Área
Escreva um programa que leia três valores com ponto flutuante de dupla
precisão: A, B e C. Em seguida, calcule e mostre:
a) a área do triângulo retângulo que tem A por base e C por altura.
b) a área do círculo de raio C. (pi = 3.14159)
c) a área do trapézio que tem A e B por bases e C por altura.
d) a área do quadrado que tem lado B.
e) a área do retângulo que tem lados A e B.
Entrada
O arquivo de entrada contém três valores com um dígito após o ponto decimal.
Saída
O arquivo de saída deverá conter 5 linhas de dados. Cada linha corresponde a
uma das áreas descritas acima, sempre com mensagem correspondente e um espaço
entre os dois pontos e o valor. O valor calculado deve ser apresentado com 3
dígitos após o ponto decimal.
"""
"""
Created on Sat May 8 23:19:43 2021
@author: lamarkscavalcanti
"""
entrada = input().split(" ")
valorA = float(entrada[0])
valorB = float(entrada[1])
valorC = float(entrada[2])
triangulo = valorA*valorC/2
circulo = 3.14159 * (valorC ** 2)
trapezio = (valorA+valorB)*(valorC/2.0)
quadrado = valorB**2
retangulo = valorA*valorB
print("TRIANGULO: %0.3f" %triangulo)
print("CIRCULO: %0.3f" %circulo)
print("TRAPEZIO: %0.3f" %trapezio)
print("QUADRADO: %0.3f" %quadrado)
print("RETANGULO: %0.3f" %retangulo) | false |
14f3995db5e03128411b91d3485ba7014a182821 | BharathC15/myAnime | /Turtle/turtleBasic3.py | 1,179 | 4.125 | 4 | import turtle
import time
def quitfn():
turtle.bye()
if __name__=="__main__":
turtle.onkey(quitfn,'q') #call quit function when q key is pressed
turtle.title("Bharath's programming")
s = turtle.Screen()
t = turtle.Turtle()
t.goto(100,100) # Go to the given location
t.setpos(-100,100) # Go to the given location
t.right(90)
t.forward(90)
t.left(90)
t.forward(90)
t.penup() # stop drawing
t.setx(-150)
t.sety(-150)
t.pendown() # start drawing
t.circle(25)
t.pensize(5) #Change the pen size
t.goto(-75,175)
t.dot(25)
s.bgcolor(0.5,0,0.5)
#print(s.colormode()) -> Default = 1
# fill
t.goto(75,-200)
t.pencolor("Green")
t.fillcolor("orange")
t.begin_fill()
t.fd(100)
t.lt(120)
t.fd(100)
t.lt(120)
t.fd(100)
t.end_fill()
#Cloning Turtles
s.bgcolor('white')
t.home() # goto origin
c = t.clone()
t.color("magenta")
c.color("red")
t.circle(100)
c.circle(60)
t.hideturtle() # Hide the arrow mark
turtle.listen() #Listen to the input commands
turtle.done() #Hold the screen from quitting | false |
5f979201c2786dd8f4dc7a5b26b774dcd93d4bb6 | liuhanru98/firstpython | /first.py | 2,712 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#上面一句是设置字符编码格式的,如果在setting的encoding中设置了编码格式,这个地方就不需要在设置了
print "Hello World!"
print 'hello';print 'runoob';
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
x="a"
y="b"
# 换行输出
print x
print y
print '---------'
# 不换行输出
print x,
print y,
# 不换行输出
print x,y
print "===============变量赋值============"
count = 100 #赋值整型变量
miles = 1000.0 #浮点型
name = "John" #字符串
print count
print miles
print name
print "++++++++++++++++字符串截取++++++++++++"
str = "Hello Python!"
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第六个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串
print "------------------列表截取---------------"
list = ['runoob', 786, 2.23, 'john', 70.2]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
list[1] = 1000
print list
print "------------------元组截取---------------"
tuple = ('runoob', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print tuple # 输出完整元组
print tuple[0] # 输出元组的第一个元素
print tuple[1:3] # 输出第二个至第四个(不包含)的元素
print tuple[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple + tinytuple # 打印组合的元组
#tuple[2] = 1000 # 会报错,不能修改
print "#################Python字典###############"
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
#pyth内置函数
#abs() 函数返回数字的绝对值。
print "==============abs() 函数=============="
print "abs(-45) : ", abs(-45)
print "abs(100.12) : ", abs(100.12)
print "abs(119L) : ", abs(119L)
| false |
06f3f8497fab1113cea5f1e5cf764333ce1afdd7 | ire-and-curses/python_examples | /object_orientation/dvd_player.py | 2,799 | 4.125 | 4 | #!/usr/bin/env python
'''
dvd_player.py - Example of a simple object.
An implementation of an idealised dvd player, for learning purposes.
Author: Eric Saunders
January 2011
'''
class DVDPlayer(object):
def __init__(self):
self.current_disc = None
def insert_disc(self, dvd):
if self.current_disc:
name = self.current_disc.name
print 'Try taking the current disc ("%s") out first, numbskull.' % name
else:
print "Slurp ... CLICK ... Chug chug chug ..."
self.current_disc = dvd
def eject(self):
if self.current_disc:
print "CLICK ... grrrrr ... POP ..."
print '[the DVD "%s" glides out of the player.]' % self.current_disc.name
disc_to_return = self.current_disc
self.current_disc = None
return disc_to_return
else:
print "Having trouble ejecting a disc that isn't there, eh?"
def play(self):
if self.current_disc:
content_length = len(self.current_disc.content)
tv_screen_width = content_length + 4
print ""
print " " + "-" * tv_screen_width
print "| " + self.current_disc.content + " |"
print "|" + " " * tv_screen_width + "|"
print "|" + " [FIN]" + " " * (tv_screen_width - 6) + "|"
print "-" * tv_screen_width
else:
print "Play? With what? You idiot. INSERT A DISC FIRST, MORON."
def get_disc_info(self):
if self.current_disc:
print "Current disc:", self.current_disc.name
print "Running time: %s minutes" % self.current_disc.running_time
else:
print ("Do you find asking unanswerable questions a gratifying"
" experience? Do you? DO YOU?")
def burn_disc(self):
if self.current_disc:
answer = raw_input('Current disc is "%s". Do you really want to record over this? '
% self.current_disc.name )
if answer == 'n': return
print "Activating video device..."
print "Do stuff (hit enter to stop recording):"
new_content = raw_input()
self.current_disc.content = new_content
print "DVD burning complete."
else:
print ("Go borrow the braincell from your moron cousin, come back"
" and try again. I'll wait.")
class DVD(object):
def __init__(self, name, running_time, content):
self.name = name
self.running_time = running_time
self.content = content
if __name__ == '__main__':
dvd = DVD("Heathers", 103, "F*** me gently with a chainsaw!")
player = DVDPlayer()
player.insert_disc(dvd)
| true |
d28e6303160ba38b994913e86ebb01f78be360f7 | sabnitkaur01/kaur_spython3 | /game.py | 1,124 | 4.15625 | 4 | # import the random package so that we can generate a random choice
from random import randint
from gameFunctions import winlose, gameVar, compare
choices = ["rock", "paper", "scissors"]
computer = choices[randint (0, 2)]
while gameVar.player is False:
# set player to True
print("**********************************")
print("Computer lives: ", gameVar.computer_lives, "/5\n")
print("Player lives: ", gameVar.player_lives, "/5\n")
print("Choose your weapon!\n")
print("**********************************")
player = input("choose rock, paper or scissors: ")
player = player.lower()
print("computer chose ", computer, "\n")
print("player chose ", player, "\n")
###this is where you would call compare
compare.comparechoices(player,computer)
### end compare stuff
# handle all lives lost for player or AI
if gameVar.player_lives is 0:
winlose.winorlose("lost")
elif gameVar.computer_lives is 0:
winlose.winorlose("won")
else:
# need to check all of our conditions after checking for a tie
print("********************************")
gameVar.player = False
computer = choices[randint(0, 2)]
| true |
882319aff7e813acc5c77aa49c993cdc33836915 | mdmmsrhs/Learning_Python | /point3.py | 860 | 4.25 | 4 | #!/bin/Python
"""
define a class called Point and initialise it
rewritten in a more OOP style
"""
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def __add__(self,other):
return Point((self.x + other.x), (self.y + other.y))
def __mul__(self,other):
return self.x * other.x + self.y * other.y
def __rmul__(self,other):
return Point(other * self.x, other * self.y)
def main():
p = Point(3,4)
print p
test = 3+4
print test
p1 = Point(3,4)
p2 = Point(5,7)
p3 = p1 + p2
print p1, p2, p3
print p1 * p2
print 2 * p2
print 2 * p1
if __name__ == '__main__':
# execute only if run as a script
main() | false |
943e47063c309148fd6ba099d73891234152c484 | Aditya-Lamaniya/PythonLearning | /sequences/dictionarypractice.py | 651 | 4.5 | 4 | d={1:"hello",2:"there",3:"whatever"} #basic dictionary
print(d)
print(d.items()) #will return the items in dictionary
k=d.keys() #will return all key index in dictionary
for i in k: print(i)
v=d.values() #will return the value in dictionary
for i in v: print(i)
# indexing
print(d[2]) #will print the value for given key
del d[2] #will delete value of of particular given key
print(d) | false |
72e878e64a863ca3ee2fd5b578fbe6e0de18314c | 26tanishabanik/Interview-Coding-Questions | /DynamicProgramming/MaxProductSubArray.py | 519 | 4.34375 | 4 |
'''
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
It is guaranteed that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
'''
def maxProduct(A) -> int:
B = A[::-1]
for i in range(1, len(A)):
A[i] *= A[i - 1] or 1
B[i] *= B[i - 1] or 1
return max(A + B)
| true |
44cf8127596ba3991078da3265b3789f030e28f8 | 26tanishabanik/Interview-Coding-Questions | /BackTrackingNdRecursion/ShortestPathWothObstacleElimination.py | 1,424 | 4.3125 | 4 |
'''
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.
Example 1:
Input:
grid =
[[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
Example 2:
Input:
grid =
[[0,1,1],
[1,1,1],
[1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.
'''
def shortestPath(self, grid, k: int) -> int:
m, n = len(grid), len(grid[0])
start = m-1, n-1, k
queue = [(0, start)]
seen = {start}
for steps, (i, j, k) in queue:
if k >= i + j - 1:
return steps + i + j
for i, j in (i+1, j), (i-1, j), (i, j+1), (i, j-1):
if m > i >= 0 <= j < n:
state = i, j, k - grid[i][j]
if state not in seen and state[2] >= 0:
queue.append((steps + 1, state))
seen.add(state)
return -1
| true |
8617da4e9767d361d992f5dc24ce7b03c10ea319 | 26tanishabanik/Interview-Coding-Questions | /LinkedLists/MergeTwoSortedLL.py | 698 | 4.125 | 4 | """
Merge two sorted linked lists and return it as a sorted list.
The list should be made by splicing together the nodes of the first two lists.
"""
class ListNode:
def __init__(self, data) -> None:
self.val = data
self.next = None
def mergeTwoLists(ll1: ListNode, ll2: ListNode) -> ListNode:
if not ll1 or not ll2:
return ll1 or ll2
if ll2.val < ll1.val:
ll1, ll2 = ll2, ll1
x = ll1
y = ll2
l2 = ListNode(0)
tmp = ll1
while x and y:
if x.val <= y.val:
l2.next = x
x = x.next
else:
l2.next = y
y = y.next
l2 = l2.next
l2.next = x or y
return tmp
| true |
57643c52563a4c8baca1a73c96229420d828047a | 26tanishabanik/Interview-Coding-Questions | /Graphs/Dijkstra'sAlgo.py | 813 | 4.15625 | 4 | '''
Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph.
'''
from heapq import heappush, heappop
from collections import defaultdict
def ShortestPath(n, m, src):
dt = defaultdict(list)
for _ in range(m):
x, y, w = map(int, input().split())
dt[x].append([y, w])
dt[y].append([x, w])
dist = [float('inf')]*(n+1) # 1 indexed
dist[src] = 0
h = [(0, src)]
while h:
d, u = heappop(h)
for v, w in dt[u]:
if dist[v] > dist[u]+w:
dist[v] = dist[u]+w
heappush(h, (dist[v], v))
return dist
Distances = ShortestPath(8, 13, 1)
for i, n in enumerate(Distances[1:]):
print(f"Shortest Distance form A - {chr(ord('@')+i+1)} is :", n)
| false |
2bb685500ffafc73b4c188d15fe6cbf7f3f095d9 | 26tanishabanik/Interview-Coding-Questions | /DynamicProgramming/WordBreak.py | 937 | 4.125 | 4 | '''
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, also being asked by many other companies now a days.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Input: ilikesamsung
Output: Yes
The string can be segmented as "i like samsung"
or "i like sam sung".
'''
def wordBreak(line, dic):
def recurr(st):
print(st)
if st in dic:
return 1
if len(st) == 0:
return 1
ans = 0
for i in range(1, len(st)):
temp = st[:i] in dic and recurr(st[i:])
ans = ans or temp
return 1 if ans else 0
return recurr(line)
| true |
eab651981e9c2686e46f808bc328ec9200b3fa8f | 26tanishabanik/Interview-Coding-Questions | /Strings/LongestSubstringWithoutRepeatingCharacters.py | 585 | 4.125 | 4 | """
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
"""
from icecream import ic
from collections import defaultdict
def lengthOfLongestSubstring(st: str) -> int:
f = 0
ans = 0
dt = defaultdict(int)
for i, n in enumerate(st):
if n in dt:
f = max(f, dt[n]+1)
ic(n, f)
dt[n] = i
ans = max(ans, i-f+1)
ic(ans)
return ans
print(lengthOfLongestSubstring("abba"))
| true |
f1a0b1620fd1328821efee7cea82bdd3be3e010f | TanayaMarathe/Python-programs | /comparison.py | 362 | 4.28125 | 4 | a= 20
b= 20
if (a==b):
print (" is equal to ")
else:
print ("a is not equal to b")
if (a!=b):
print ("a is not equal to b")
else:
print ("a is equal to b")
if (a<b):
print ("a is less than b")
else:
print ("a is greater than b")
if (a>b):
print ("a is greater than b")
else:
print ("a is less than b") | false |
ddaa8970646ea589a77de0dff73cc9063f4d37b6 | bryonb97/Coding_Dojo | /CodingDojo/Python/Python/OOP/SinglyLinkedLists/SList.py | 1,789 | 4.1875 | 4 | import SLNode
class SList:
def __init__(self):
self.head = None
def add_to_front(self, val):
new_node = SLNode.SLNode(val)
current_head = self.head # Save the current head in a variable
new_node.next = current_head # SET the new node's next TO the list's current head
self.head = new_node # SET the list's head TO the node we created in the last step
return self # Return self to allow for chaining
def add_to_back(self, val):
if(self.head == None): # if the list is empty
self.add_to_front(val) # run the add_to_front method
return self # let's make sure the rest of this function doesn't happen if we add to the front
new_node = SLNode.SLNode(val) # create a new instance of our Node class with the given value
runner = self.head # set an iterator to start at the front of the list
while (runner.next != None): # iterator until the iterator doesn't have a neighbor
runner = runner.next # increment the runner to the next node in the list
runner.next = new_node # increment the runner to the next node in the list
return self # return self to allow for chaining
def print_values(self):
runner = self.head # a pointer to the list's first node
while (runner != None): # iterating while runner is a node and not None
print(runner.value) # print the current node's value
runner = runner.next # set the runner to its neighbor
return self # return self to allow for chaining
my_list = SList() # create a new instance of a list
my_list.add_to_front("are").add_to_front("Linked Lists").add_to_back("fun!").print_values()
# output should be:
# Linked lists
# are
# fun!
| true |
1ce87c7260a3330d3f3273eeac955e632a285e30 | mfern7/Python_files | /program6.py | 312 | 4.25 | 4 |
ingresenum = int(input("ingrese numero: "))
def collatz(numero):
if numero % 2 == 0:
return str(numero) + " // 2 = " + str(numero // 2)
elif numero % 2 == 1:
return str(numero) + " * 3 + 1 = " + str(3 * numero + 1)
#while collatz(ingresenum) != 1:
print(collatz(ingresenum))
| false |
fd5120478af1aa8c55c231cb4ba164867d12fa36 | subhanlitun/GitDemo | /6_loop.py | 1,208 | 4.21875 | 4 | #While loop
'''
while expression:
statement(s)
'''
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
#else with loop
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
#single statement suite
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
#for loop
'''
for iterating_var in sequence:
statements(s)
'''
'''
>>> list(range(5))
[0, 1, 2, 3, 4]
'''
for var in list(range(5)):
print (var)
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
print ("Good bye!")
#iterating by index
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")
#else in loop
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2 == 0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number') | true |
960239b1e174a7f67d2e3044ad4c1e575ac24fd5 | ipudu/leetcode | /solutions/005_longest-palindromic-substring.py | 823 | 4.15625 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
result = ''
def polindrome(s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
for i in range(len(s)):
p1 = polindrome(s, i, i)
if len(p1) > len(result):
result = p1
p2 = polindrome(s, i, i+1)
if len(p2) > len(result):
result = p2
return result | true |
d1c76c6afe88f46a6f32bac67f5c9412726867c8 | aavila320/comp401 | /project05/DragonCurve.py | 1,431 | 4.28125 | 4 | # This program will create a fractal dragon curve using turtle graphics.
# The results are saved as an eps.
# A dragon curve is created by recursive 90 degree angles.
from turtle import *
def draw_fractal(length, angle, level, initial_position, target, replacement, new_target, new_replacement):
position = initial_position
# Determining where the next line is drawn
for counter in range(level):
new_position = ''
for character in position:
if character == target:
new_position += replacement
elif character == new_target:
new_position += new_replacement
else:
new_position += character
position = new_position
# Drawing the dragon curve
for character in position:
if character == 'F':
forward(length)
elif character == '+':
right(angle)
elif character == '-':
left(angle)
if __name__ == '__main__':
draw_fractal(7, 90, 10, 'FX', 'X', 'X+YF+', 'Y', '-FX-Y')
myTurtle = turtle.Turtle()
x = myTurtle.getscreen()
x.getcanvas().postscript(file = "DragonCurveOutput.eps")
# x.getcanvas().postscript(file = "DragonCurveOutput.svg")
# x.getcanvas().postscript(file = "DragonCurveOutput.jpeg")
# x.getcanvas().postscript(file = "DragonCurveOutput.png")
exitonclick() # click to exit
| true |
e4cc13da34e321cb21ed53636af72c5e6a923b21 | wartrax13/exerciciospython | /Fluent_Python/Exemplos/Exemplo_2.9.py | 328 | 4.28125 | 4 | #TUPLAS NOMEADAS é uma fábrica que gera subclasses de tuple melhoradas com nomes de campos e um nome de classe.
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
print(tokyo)
print(tokyo.population)
print(tokyo[1]) | false |
e089901610401904a4ec20788e6f9d51df6b4402 | wartrax13/exerciciospython | /Lista de Exercícios PYTHON BR/EstruturadeRepetição/17 - EstruturadeRepetição.py | 264 | 4.125 | 4 | '''
Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5!=5.4.3.2.1=120
'''
from math import factorial
n = int(input('Digite um número: '))
x = 0
while x < n:
x += 1
print(x, end=' x ')
print(f'= {factorial(n)}') | false |
44be9c50c29dd135943f16013dd0f9acddf8b564 | wartrax13/exerciciospython | /Lista de Exercícios PYTHON BR/ExerciciosListas/15 - ExerciciosListas.py | 1,076 | 4.125 | 4 | '''
Faça um programa que leia um número indeterminado de valores,
correspondentes a notas, encerrando a entrada de dados quando for informado
um valor igual a -1 (que não deve ser armazenado).
Após esta entrada de dados, faça:
Mostre a quantidade de valores que foram lidos;
Exiba todos os valores na ordem em que foram informados, um ao lado do outro;
Exiba todos os valores na ordem inversa à que foram informados, um abaixo do outro;
Calcule e mostre a soma dos valores;
Calcule e mostre a média dos valores;
Calcule e mostre a quantidade de valores acima da média calculada;
Calcule e mostre a quantidade de valores abaixo de sete;
Encerre o programa com uma mensagem;
'''
x = 0
lista = []
abaixosete = []
c = 0
while x != 1:
c += 1
x = int(input('Digite um valor: '))
if x != 1:
lista.append(x)
if x < 7:
abaixosete.append(x)
print(f'Foram lidos {len(lista)} valores')
media = sum(lista) / c
print(lista)
print(lista[::-1])
print(sum(lista))
print(round(media, 2))
print(f'São {len(abaixosete)} valores abaixo de sete.')
| false |
62599572c53e6ee7ab5028022d77ab133bc903e8 | wartrax13/exerciciospython | /Livro Nilo Ney - Programação Python/Exercicios/Exercicio_5.27.py | 273 | 4.21875 | 4 | '''
Escreva um programa que verifique se um número é palindromo.
Um número é palindromo se continua o mesmo caso seus dígitos sejam invertidos.
'''
n = int(input('Digite:'))
q = str(n)
if int(q[::-1]) == n:
print('É um palindromo.')
else:
print('Não é.') | false |
ff516136a1080a6f021ef5f49cfd8f737050b5db | Spenstine/python_practice | /protoTimeV2.py | 2,813 | 4.3125 | 4 | class Time():
'''
attr: integer to represent time in seconds
'''
def __init__(self, seconds = 0):
self.minute, self.second = divmod(seconds, 60)
self.hour, self.minute = divmod(self.minute, 60)
def __str__(self):
"""Returns a string representation of the time."""
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
def print_time(self):
"""Prints a string representation of the time."""
print(str(self))
def time_to_int(self):
"""Computes the number of seconds since midnight."""
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
def is_after(self, other):
"""Returns True if t1 is after t2; false otherwise."""
return self.time_to_int() > other.time_to_int()
def __add__(self, other):
"""Adds two Time objects or a Time object and a number.
other: Time object or number of seconds
"""
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def __radd__(self, other):
"""Adds two Time objects or a Time object and a number."""
return self.__add__(other)
def add_time(self, other):
"""Adds two time objects."""
assert self.is_valid() and other.is_valid()
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
def increment(self, seconds):
"""Returns a new Time that is the sum of this time and seconds."""
seconds += self.time_to_int()
return int_to_time(seconds)
def is_valid(self):
"""Checks whether a Time object satisfies the invariants."""
if self.hour < 0 or self.minute < 0 or self.second < 0:
return False
if self.minute >= 60 or self.second >= 60:
return False
return True
def int_to_time(seconds):
"""Makes a new Time object.
seconds: int seconds since midnight.
"""
return Time(seconds)
def main():
start = Time(9*3600 + 45*60)
start.print_time()
end = start.increment(1337)
#end = start.increment(1337, 460)
end.print_time()
print('Is end after start?')
print(end.is_after(start))
print('Using __str__')
print(start, end)
start = Time(9*3600 + 45*60)
duration = Time(3600 + 35*60)
print(start + duration)
print(start + 1337)
print(1337 + start)
print('Example of polymorphism')
t1 = Time(7*3600 + 43*60)
t2 = Time(7*3600 + 41*60)
t3 = Time(7*3600 + 37*60)
total = sum([t1, t2, t3])
print(total)
if __name__ == '__main__':
main() | true |
781cb523d9545b8012c185be30e2d65b4ca46a16 | Spenstine/python_practice | /turtleSipe.py | 462 | 4.34375 | 4 | import turtle
length = int(input("length: "))
sides = int(input("sides: "))
bob = turtle.Turtle()
def polygon(pointer, length, sides):
"""pointer: turtle object
length: length of each side of desired polygon
sides: number of sides of desired polygon
"""
angle = (sides - 2) * 180 / sides
for _ in range(sides):
pointer.fd(length)
pointer.lt(180 - angle)
turtle.mainloop()
polygon(bob, length, sides) | true |
bbfa9940ce115956fc67c11494af4f2c330195a2 | anfbermudezme/PythonCourse | /03_areacirc.py | 754 | 4.15625 | 4 | pi=3.14159
radio=20
area=pi * radio**2
print(area)
#Ejemplo que contextualiza el funcionamiento de un programa
#Variables y expresiones:
# Las expresiones se componen de valors conctados por operadores
# Cuando la computadora evalúa una expresión, el resultado es otro valor
# Los valores pueden guardarse en variables
# Las variables se pueden reasignar
# Nombres para variables:
# Nombres significativos, relacionados con lo qu expresa la variable
# Palabras que no se pueden usar:
# False, None, True, and, as, assent, break, class, continue, def, del, elif, else, except,
# finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise
# return, try, while, with, yield
# Los strings se deben poner dentro de ' ' | false |
564c630f3ab077c72784aa411ab29c95983a71db | SolangeUG/wiki-application | /util/security.py | 1,522 | 4.3125 | 4 | import hmac
from pybcrypt import bcrypt
SECRET = "ThomasBeaudoin"
def hash_str(string):
"""
Return the hashed value of a given string parameter.
THe HMAC method is used to compute the hashed value.
:param string: input parameter
:return: the corresponding hashed value
"""
return hmac.new(SECRET, string).hexdigest()
def make_secure_val(value):
"""
Return the secure equivalent of a given value.
:param value: input parameter
:return: its equivalent secure value
"""
return "%s|%s" % (value, hash_str(value))
def check_secure_val(hash_value):
"""
Check that a hashed value is secure
:param hash_value: input hashed value
:return: True if it is secure
False otherwise
"""
value = hash_value.split('|')[0]
if make_secure_val(value) == hash_value:
return value
def hash_password(password):
"""
Return the hashed equivalent of a password
:param password: input password
:return: equivalent encrypted value using the bcrypt algorithm
"""
if password:
return bcrypt.hashpw(password, bcrypt.gensalt())
def check_password(password, stored_hash_value):
"""
Check if provided password is what is expected
:param password: input password
:param stored_hash_value:
:return: True if the input value corresponds to what is expected
False otherwise
"""
hash_value = bcrypt.hashpw(password, stored_hash_value)
return hash_value == stored_hash_value
| true |
aad98b581f0901d9a6cfe34d15765ecaa749b5a1 | rburrito/python_gists | /unicode_to_words.py | 590 | 4.1875 | 4 | #!/usr/bin/env python
import sys
#Converts ASCII encoded characters from a file to words
#Use test file unicode_to_words.txt
def ordinary_words(filename):
fileS = open(filename, 'r')
content = fileS.read()
new_content = content.split(" ")
converted_str = ""
for num_str in new_content:
if '\n' in num_str:
num_str = num_str.rstrip('\n')
char = chr(int(num_str))
converted_str += char
return converted_str
def main():
first_arg = sys.argv[1]
print(ordinary_words(first_arg))
if __name__ == '__main__':
main()
| true |
529c06f4991bfab3a306952ce44a30ac87f5c1e1 | Subiyamaheen/Data-Structures | /pangram.py | 261 | 4.34375 | 4 | #To check whether the given string is a pangram:
a='abcdefghijklmnopqrstuvwxyz'
b=input("enter the string")
count=0
for i in a:
if i in b:
count+=1
if(count==26):
print('Yes!It is a pangram')
else:
print('No!It is not a pangram')
| false |
5f37f7c483106c4966f8152be2bc239b7795c884 | taiyipan/file_encryption_decryption | /decrypt.py | 2,488 | 4.25 | 4 | # This program uses a cipher to decrypt messages
def main():
# intro
print('\nWelcome to Decryption Program!')
# load cipher and store in dictionary
cname = 'cipher.txt'
cipher = load_cipher(cname)
# read and encrypt message
read_decrypt(cipher)
# output result
print('\nFile decryption successful.')
# load cipher and store in dictionary
def load_cipher(cname):
print('Searching for cipher...')
# open file, read mode
try:
infile = open(cname, 'r')
print('Cipher located.')
except IOError:
print('Error: cipher not found.')
quit()
# create an empty dictionary
cipher = dict()
# read line by line
for line in infile:
# remove whitespace
line.rstrip()
# split the line into a list of 2 parts
parts = line.split()
# add each key/value pair to dictionary in a reverse order
cipher[parts[1]] = parts[0]
# close file
infile.close()
print('Cipher installed successfully.')
# return dictionary
return cipher
# read and decrypt message
def read_decrypt(cipher):
# get user input
in_fname = input('\nPlease name the input file for decryption: ')
print('Searching...')
# open input file, read mode
try:
infile = open(in_fname, 'r')
print('File located.')
except IOError:
print('Error: file cannot be located.')
quit()
# get user input
out_fname = input('\nPlease name the output file for decryption: ')
# open output file, write mode
outfile = open(out_fname, 'w')
print('File created.')
# read input file line by line
for line in infile:
# remove whitespace
line.rstrip()
# split line into a list of words
words = line.split()
# go through each word in the list
for word in words:
# go through each character in individual word
for char in word:
# use cipher to encrypt the character
nchar = cipher.get(char, '-1')
if nchar != '-1':
outfile.write(nchar)
else:
outfile.write('ERROR')
# add a space after word
outfile.write(' ')
# add a new line after each line
outfile.write('\n')
# close files
infile.close()
outfile.close()
main()
| true |
2a7ef2dd5a746c67f7f87e6f815ddc968b8a958f | supersede-project/big_data | /data_analysis/FeedbackAnalysis/src/main/resources/scripts/nonRepeated.py | 1,689 | 4.1875 | 4 | def nonRepeated(bigram):
"""This function receives a dictionary whose keys are tuples (bigrams) and the values are integers (frequencies)
and returns a new dictionary without the same key value pairs but without repeated. So, for example, if the following
values are in 'bigram':
('a','b'): x
('b','a'): y
this funcion replaces the values in the following way:
('a','b'): x+y
('b','a'): 0
and then returns the new dictionary."""
keys = bigram.keys()
start = 0
newvalues = bigram.copy()
while start<len(keys):
for i in range(start+1,len(keys)):
if keys[start][0] == keys[i][1] and keys[start][1] == keys[i][0]:
# Uncomment this to debug!
# print ("repeated!")
# print ("{0} {1} == {2} {3}".format(keys[start][0],keys[start][1],keys[i][0],keys[i][1]))
# print ("values before(bigram): {0} , {1}".format(bigram[keys[start]],bigram[keys[i]]))
# print ("values before(newvalues): {0} , {1}".format(newvalues[keys[start]],newvalues[keys[i]]))
newvalues[keys[start]] = newvalues[keys[start]]+newvalues[keys[i]]
newvalues[keys[i]] = 0
# print ("values after(newvalues): {0} , {1}".format(newvalues[keys[start]],newvalues[keys[i]]))
break
start = start + 1
return newvalues
def eliminateFromList(bigram,textList):
"""Function to discard words that are not in the textList"""
keys = bigram.keys()
newBigram = bigram.copy()
for value in keys:
if not isInDict(value,textList):
newBigram[value] = 0
return newBigram
def isInDict(value,textList):
""" check whether the strings in value are in textList"""
for item in textList:
if item == value[0] or item == value[1]:
return True
return False
#def mynonRepeated(bigram)
| true |
6f6dcf6bd1548189231a78751691f6e58cee06ab | eunice-pereira/Python-practice | /ex11.py | 510 | 4.1875 | 4 | # practicing input
# When input() function executes program flow will be stopped until user have given an input
# end= ' ' tells print to not end the line with a newline character and go to next line
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print("What is your diet preference?", end=' ')
diet = input()
print(f"So, you're {age} old, {height} tall, {weight} heavy and eat a {diet} diet.")
| true |
dc18ee16b70617651dfd0f13ecdc91fd856f8f2c | Bhasheyam/ALgorithms-PythonSolved | /Linepalindrome.py | 610 | 4.25 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example:
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
'''
def isPalindrome(A):
loop = A.strip()
i = 0
ans = ""
while ( i < len(loop)):
if loop[i].isalnum():
ans = ans + loop[i].lower()
i += 1
print(ans)
print(ans[::-1])
return ans == ans[::-1]
print( isPalindrome("A man, a plan, a canal: Panama")) | true |
3dd38e34a1fb2096193016dda9278e11b92cf478 | Bhasheyam/ALgorithms-PythonSolved | /Treesymentry.py | 574 | 4.28125 | 4 | '''Given a binary tree t, determine whether
it is symmetric around its center,
i.e. each side mirrors the other.'''
#
# Definition for binary tree:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def isTreeSymmetric(t):
return mirro(t,t)
def mirro(t,t1):
if t ==None and t1 == None:
return True
if (t is not None and t1 is not None):
if t.value == t1.value:
return (mirro(t.left, t1.right)and
mirro(t.right, t1.left))
return False
| true |
7cf6ded8d4a2b0d4e60d7eb5696ac67c55bf1bce | alejandroge/PyDocs | /Pandas.py | 1,771 | 4.1875 | 4 | """
author: Alejandro Guevara
"""
import pandas as pd
import numpy as np
df = pd.read_csv('salaries.csv') # Create a DataFrame from a CSV file
print(df)
print(df['Name']) # Accessing data using its column name
print(df[['Name', 'Salary']]) # Accessing more than one column, using a list
# of names
ageMean = df['Age'].mean() # Computes average on the data in the 'Age' column
print("Age average is: "+ str(ageMean))
print(df['Age'] > 30 ) # Applies the comparator to every element in the column
# and returns the boolean results
age_filter = df['Age'] > 30 # It can be saved and used as a filter
print(df[age_filter])
data = np.random.randint(0, 100, (10, 5))
df = pd.DataFrame(data, columns=list('ABCDE')) # Create a DataFrame from a numpy
print(df) # array, letting Pandas create a
# default index.
print(df.head()) # Returns the first 5 rows of the Dataframe
print(df.tail()) # Returns the last 5 rows of the Dataframe
dates = pd.date_range('20180221', periods=10) # Returns an index made of datetime
df = pd.DataFrame(data, columns=list('ABCDE'), index=dates)
print(df) # Create a DataFrame from a numpy
# array, using DateTime as index
print(df.describe()) # Returns valuable statistical info about the data
print(df.describe().T) # Transposes a Dataframe
print(df.sort_values(by='B')) # Sorts the DataFrame by the values in one of the
# columns
print(df[0:3]) # Dataframes accept slicing
print(df['20180225':'20180228']) # it is also a valid way to slice a dataframe
df.plot(x='A', y='B', kind='scatter') # DataFrames can be plotted
| true |
9a88a919aadab6e2271f98e13cbaa7b5aecbc517 | VishwajeetSaxena/selenium_python | /methods/methods_part1.py | 826 | 4.1875 | 4 | #Method with parameters
def sum_num(num1, num2):
'''
:param num1:
:param num2:
:return:
'''
print(num1 + num2)
sum_num(2, 3)
sum_num(34, 4)
sum_num('hello', ' how are you')
#Method with return value
def sum_num_with_return(num1, num2):
'''
:param num1:
:param num2:
:return:
'''
return (num1 + num2)
returned_value = sum_num_with_return(45, 55)
print("The returned value is: ", returned_value)
def conditional_return(city):
metro_cities = ['Newyork', 'Boston', 'Mumbai', 'New Delhi']
if city in metro_cities:
return True
else:
return False
city_name = 'Boston'
conditional_return_value = conditional_return(city_name)
print(city_name, 'is a metro: ', conditional_return_value)
print('Bangalore is a metro: ', conditional_return('Bangalore'))
| false |
9a54f2fed3a924964bb72975bd57696dd2499aa2 | VishwajeetSaxena/selenium_python | /datatypes/string_part2.py | 1,080 | 4.34375 | 4 | #Access specific character of string
string1 = "This is sample string"
string2 = string1[3]
print("full string:", string1,"with type: ", type(string1))
print("specific character of string: ", string2, "with type: ", type(string2))
#Get length of string
print("Length of string is: ", len(string1))
#Get lower case data of string
print("The lower case of the string is: ", string1.lower())
#Get uppper case data of string
print("The upper case of the string is: ", string1.upper())
#Concat the strings
string3 = "Hello"
string4 = "World"
string5 = string3+string4
print("Merged string is: ", string5)
#Replace strings
string6 = "1abc2abc3abc4abc"
print("Replace all 'abc' with 'ABC' :", string6.replace('abc', 'DEF'))
print("Replace first two 'abc' with 'ABC' :", string6.replace('abc', 'DEF', 2))
#different ways to parameterize the printed strings
print("I just want to add", string3, "in this line along with", string4)
print("I just want to add "+string3+" in this line along with "+string4)
print("I just want to add %s in this line along with %s" % (string3, string4))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.