blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ec327f48426bedaf3bad862a9a0ebe5e6afb366b | sleibrock/form-creator | /fcl/RectData.py | 1,483 | 4.125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
__author__ = 'Steven'
class Rect(object):
"""
Class to store rectangle information
Stores (x,y,w,h), the type of Rect, the ID of the rect, and now the value of the rect
"""
def __init__(self, x, y, w, h, idtag="", typerect="text", value=""):
self.x, self.y, self.w, self.h = x, y, w, h
self.data = (x, y, w, h)
self.idtag = idtag # name tag of the Rect
self.typerect = typerect # default
self.value = value # used for check/radio boxes
def __iter__(self):
"""
The ability to unpack a rectangle into multiple functions is nice (via *rect)
Normally you would use __iter__ for a collection of data
but the only important data in a rectangle is it's positioning data
"""
return self.data
def __eq__(self, other):
"""
The __eq__ method determines equality of one rect to another
However this could be extended to normal lists/tuples as well if necessary
"""
return self.data == other.data
def collide(self, rect):
"""
Collision code (not used in the main program)
This doesn't take into calculation any offset data so it's not used
Deprecated
"""
x1, y1, w1, h1 = self.data
x2, y2, w2, h2 = rect.data
if all([x1 < x2 + w2, x1+w1 > x2, y1 < y2+h2, y1+h1 > y2]):
return True
return False
#end | true |
7ddbf394320fe3b4babc65bba39858c47eaa0482 | Luquicas5852/Small-projects | /easy/PascalTriangle.py | 392 | 4.15625 | 4 | """
This will generate Pascal's triangle.
"""
#Define a factorial using recursion
def f(n):
if n == 0:
return 1
else:
return n*f(n - 1)
rows = int(input('Enter with the amount of rows that you want to generate: '))
row = ""
for i in range(rows):
for j in range(i + 1):
num = f(i)/(f(j)*f(i - j))
row += str(num) + " "
print(row)
row = ""
| true |
3dc184b82e04ea5d263e6668832e574e3543b985 | dionboonstra/RecommendationsResit | /resitRPI.py | 2,627 | 4.4375 | 4 | # import csv in order to be able to read/import csv files into directory
import csv
#Load data using the reader function in python, therefrom create a list including all the information present in the userreviews csv file
file = csv.reader(open("/Users/dionboonstra/Downloads/userReviews all three parts.csv", encoding= 'utf8'), delimiter = ';')
reviews = list(file)
#print(reviews)
#Create a new list which includes all reviews on the movie American-Sniper
reviewers = []
for x in reviews:
if x[0] == 'american-sniper':
#all reviewers with reviews on the american-sniper movie are added to the list
reviewers.append(x)
#print(reviewers)
#Create a new list in which all reviews are included from the reviewers present in the reviewers list.
#In addition, the list is constructed so it only contains reviews from reviewers whom scored american-sniper with a 7 or higher,
#where the other reviews are higher than the one provided for american-sniper, and the reviews can be on the movie american sniper itself
recommendations = list()
for y in reviewers:
for z in reviews:
if y[2] == z[2] and int(y[1]) > 7 and int(z[1]) >= int(y[1]) and z[0] != 'american-sniper':
#absolute and relative increase of the reviewscore in comparison to the american-sniper movie are created
absinc = int(z[1]) - int(y[1])
relinc = (int(z[1]) - int(y[1])) / int(y[1])
#the absolute and relative increases of reviewscore are added to the existing list of rows of the original csv file
totalrec = (z[0], z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9], absinc, relinc)
#all rows are added to the recommendations list
recommendations.append(totalrec)
#print(recommendations)
#The recommendations list is sorted descending on the absolute increase of the review score (tup[11])
sortedrec = sorted(recommendations, key=lambda tup: (tup[11]), reverse=True)
#print(sortedrec)
#Headers are added in order to create a clear overview for the new recommendations file
header = ["movieName", "Metascore_w", "Author", "AuthorHref", "Date", "Summary", "InteractionsYesCount", "InteractionsTotalCount", "InteractionsThumbUp", "InteractionsThumbDown", "AbsoluteIncrease", "RelativeIncrease"]
#Create a new csv including the header and sortedrec list, completing the movie recommendations list with american-sniper as favorite movie
with open("MovieRecommendations.csv", "w", newline= '') as ResitRecSys:
writer = csv.writer(ResitRecSys, delimiter=';')
writer.writerow(header)
for row in sortedrec:
writer.writerow(row)
| true |
5cf2041655940707401f2869a256f14be25d00bc | 17e23052/Lesson-10 | /main.py | 1,463 | 4.34375 | 4 | price = 0
print("Welcome to the Pizza cost calculator!")
print("Please enter any of the options shown to you with correct spelling,")
print("otherwise this program will not work properly.")
print("Would you like a thin or thick crust?")
crust = input().lower()
if crust == "thin":
price = price + 8
elif crust == "thick":
price = price + 10
print("Would you like an 8, 10, 12, 14, or 18 inch crust?")
size = int(input())
if size == 8 or size == 10:
price = price + 0
elif size == 12 or size == 14 or size == 18:
price = price + 2
print("Would you like cheese on your pizza? Please enter yes or no.")
cheese = input().lower()
if cheese == "yes":
price = price + 0
elif cheese == "no":
price = price - 0.5
print("What type of pizza would you like? You can choose from margarita, vegetable, vegan, Hawaiian or meat feast.")
pizzatype = input().lower()
if pizzatype == "margarita":
price = price + 0
elif pizzatype == "vegetable" or pizzatype == "vegan":
price = price + 1
elif pizzatype == "hawaiian" or pizzatype == "meat feast":
price = price + 2
if size == 18:
print("Do you have a voucher code? Please enter yes or no.")
voucher = input().lower()
if voucher == "yes":
print("Type in your voucher code here:")
code = input()
if code == "FunFriday":
print("Code valid")
price = price - 2
else:
print("Code invalid")
print("The total cost for your pizza is:")
print(price)
print("pounds. Enjoy your pizza!") | true |
ee090bb4302155b486dbfe50f7f500206cf68e30 | shubhangi2803/More-questions-of-python | /Data Types - List/Q 7,8,9.py | 726 | 4.3125 | 4 | # 7. Write a Python program to remove duplicates from a list.
# 8. Write a Python program to check a list is empty or not.
# 9. Write a Python program to clone or copy a list.
li_one=list(map(int,input("Enter list elements separated by lists : ").split()))
li_two=[]
print("List 1 : ")
print(li_one)
print("List 2 : ")
print(li_two)
def is_empty(li):
return len(li)==0
print("List 1 : Is Empty ?? {}".format(is_empty(li_one)))
print("List 2 : Is Empty ?? {}".format(is_empty(li_two)))
li_one_clone=li_one
li_two_clone=li_two
print("Copy of list 1 : {}".format(li_one_clone))
print("Copy of list 2 : {}".format(li_two_clone))
li_one_new=set(li_one)
print("After removing duplicates, list 1 : {}".format(li_one_new))
| true |
044e09d766cc7a3eac7f85577d937ddc3ac5205a | shubhangi2803/More-questions-of-python | /Lambda functions/Q 6.py | 304 | 4.21875 | 4 | # 6. Write a Python program to square and cube every number in a given list of integers using Lambda.
li=list(map(int,input("Enter list of numbers : ").split()))
p=list(map(lambda x: x*x, li))
q=list(map(lambda y: y*y*y, li))
print("List of squares : {}".format(p))
print("List of cubes : {}".format(q))
| true |
9f9a285d1187ac3b7ff6e85c4b6aaec22c4a21ca | vray22/Coursework | /cs153/Assignment2.py | 1,183 | 4.3125 | 4 | #Name: Victor Lozoya
#Date:2/9/17
#Assignment2
#create string to avoid typing it twice
str = "Twinkle, twinkle, little star,\n"
#use print statements for each line to avoid confusion
print(str)
print("\t How I wonder what you are! \n")
print("\t\t Up above the world so high, \n")
print("\t\t Like a diamond in the sky, \n")
print(str)
print("\t How I wonder what you are\n\n\n\n\n\n\n\n\n ")
#set radius to user input and cast it to float
radius = float(input("Enter radius for circle \n"))
print("The radius is: ")
print(radius)
pie = 3.14
area = pie * radius**2#calculate area
print("\nThe area is: ")
print(area)
#set length to user input and cast to int
length = int(input("\n\n\n\n\n\nEnter length of square\n"))
print("The length is: ")
print (length)
area = length**2#calculate area
print("\nThe area is: ")
print (area)
#set base and height equal to user input and cast both to int
base = int(input("\n\n\n\n\nEnter length of base\n"))
height = int(input("Enter length of heigth\n"))
print("Base: ")
print (base)
print("\nHeight: ")
print(height)
area = base * height#Calculate area for rectangle
print("\nArea: ")
print(area)
| true |
80b8af95d4df47a9449331f58b3244ef031c6c25 | njberejan/TIY-Projects | /multiples_exercise.py | 577 | 4.21875 | 4 | list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def multiple_of_3_or_5(list_of_numbers):
multiples_of_3_or_5_list = []
total = 0
for number in list_of_numbers:
if number % 3 == 0:
multiples_of_3_or_5_list.append(number)
elif number % 5 == 0:
multiples_of_3_or_5_list.append(number)
else:
continue
for number in multiples_of_3_or_5_list:
#print(multiples_of_3_or_5_list)
#print(total)
total += number
return total
print(total)
multiple_of_3_or_5(list_of_numbers)
| true |
5674214283bf08513493920731e534bf1ee84316 | VolatileMatter/GHP_Files | /sorts.py | 774 | 4.125 | 4 | import random
def in_order(a_list):
last_item = None
for item in a_list:
if not last_item:
last_item = item
if item < last_item:
return False
last_item = item
return True
#Insertion Sort
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
return alist
ranList = random.sample(xrange(1, 101), 10)
print "Random list:",ranList
print ""
mylist = [2,5,1,8,3,9]
test1 = [1,2,3,4,5,6,7,8]
test2 = [1,9,3,4,5,6,7,8,2]
test3 = [4,3,2,1,7,9,8]
test4 = [6,9,10,5,2,8]
print "insertion: "
print insertionSort(mylist)
print insertionSort(ranList)
print ""
| true |
4758c61d8a45c42db805d1ce5dcf6cc7c56fbde4 | goosebones/spellotron | /string_modify.py | 1,556 | 4.15625 | 4 | """
author: Gunther Kroth gdk6217@rit.edu
file: string_modify.py
assignment: CS1 Project
purpose: minipulate words that are being analyzed
"""
def punctuation_strip(word):
""" strips punctuation from the front and back of a word
returns a tuple of word, front, back
:param word: word to strip punctuation from
"""
front = ""
back = ""
# front strip
while word[0].isalpha() == False:
front += word[0]
word = word[1:]
if len(word) == 0:
return word, front, back
# back strip
while word[-1].isalpha() == False:
back += word[-1]
word = word[:len(word)-1]
# reverse back's order
true_back = ""
for ch in back:
true_back = ch + true_back
return word, front, true_back
def lower_case(word):
""" convert first letter to lowercase
uses a list method
:param word: word to convert
"""
letter_list = []
new_word = ""
for ch in word:
letter_list.append(ch)
first = letter_list[0]
lower = first.lower()
letter_list[0] = lower
for element in letter_list:
new_word += element
return new_word
def upper_case(word):
""" convert first letter to uppercase
uses a list method
:param word: word to convert
"""
letter_list = []
new_word = ""
for ch in word:
letter_list.append(ch)
first = letter_list[0]
cap = first.upper()
letter_list[0] = cap
for element in letter_list:
new_word += element
return new_word
| true |
59407725886e12ac88af7d5a5be9b765f40890b5 | diksha12p/DSA_Practice_Problems | /Palindrome Number.py | 1,014 | 4.125 | 4 | """
LC 9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
def isPalindrome_alt(self, x: int) -> bool:
if x < 0:
return False
num , rev_num = x, 0
while num:
q, r = divmod(num, 10)
rev_num = rev_num * 10 + r
num = q
return x == rev_num
if __name__ == '__main__':
sol = Solution()
assert sol.isPalindrome(121) is True
assert sol.isPalindrome(-121) is False
assert sol.isPalindrome(10) is False
assert sol.isPalindrome_alt(121) is True
assert sol.isPalindrome_alt(-121) is False
assert sol.isPalindrome(10) is False
| true |
1ff85b27640580d2df9b5bad1a023d37d0a507e8 | diksha12p/DSA_Practice_Problems | /Letter Combinations of a Phone Number.py | 1,068 | 4.1875 | 4 | """
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could
represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any
letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
from typing import List
class Solution:
def __init__(self):
self.KEYBOARD = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv",
"9": "wxyz"}
def letterCombinations(self, digits: str) -> List[str]:
if not digits: return []
result = []
self.dfs(digits, 0, "", result)
return result
def dfs(self, digits, idx, path, result):
if len(path) == len(digits):
result.append(path)
return
for char in self.KEYBOARD[digits[idx]]:
self.dfs(digits, idx + 1, path + char, result)
if __name__ == '__main__':
sol = Solution()
print(sol.letterCombinations('23'))
| true |
678696e563fd889705b32dfdffc578f5b575415c | diksha12p/DSA_Practice_Problems | /Binary Tree Right Side View.py | 1,666 | 4.28125 | 4 | """
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see
ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# IDEA 1: Level Order Traversal and append the ele at index = -1 to the final answer
def rightSideView(self, root: TreeNode) -> List[int]:
if not root: return []
# queue: List(TreeNode)
result, queue = list(), [root]
while queue:
level = []
result.append(queue[-1].val)
for node in queue:
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
queue = level
return result
# IDEA 2: Obtain the right side views for the left and right child of the root. (view_right, view_left)
# Depending upon the length of view_right, append view_left[len(view_right) : ]
def rightSideView_alt(self, root: TreeNode) -> List[int]:
if not root: return []
view_right = self.rightSideView_alt(root.right)
view_left = self.rightSideView_alt(root.left)
if len(view_left) < len(view_right):
return [root.val] + view_right
else:
return [root.val] + view_right + view_left[len(view_right):]
| true |
9cd96360b3da0bb90a3f98d9486cb9137714b0a3 | lcongdon/tiny_python_projects | /07_gashlycrumb/addressbook.py | 1,069 | 4.125 | 4 | #!/usr/bin/env python3
"""
Author : Lee A. Congdon <lee@lcongdon.com>
Date : 2021-07-14
Purpose: Tiny Python Exercises: addressbook
"""
import argparse
import json
def get_args():
"""Parse arguments"""
parser = argparse.ArgumentParser(
description="Print line(s) from file specified by parameters",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-f",
"--file",
default="addressbook.json",
type=argparse.FileType("rt"),
help="Input file in json format",
metavar="FILE",
)
parser.add_argument("entry", help="Name of person", metavar="entry")
return parser.parse_args()
def main():
"""Main program"""
args = get_args()
addresses = json.load(args.file)
if args.entry in addresses:
print(
addresses[args.entry]["emailAddress"]
+ "\n"
+ addresses[args.entry]["phoneNumber"]
)
else:
print(f'I do not have an entry for "{args.entry}".')
if __name__ == "__main__":
main()
| true |
53f80b39a9af33f5d1cde67c3ad9848e534dca74 | joshuasewhee/practice_python | /OddOrEven.py | 460 | 4.21875 | 4 | # Joshua Sew-Hee
# 6/14/18
# Odd Or Even
number = int(input("Enter a number to check: "))
check = int(input("Enter a number to divide: "))
if (number % 2 == 0):
print("%d is even." %number)
elif (number % 2 != 0):
print("%d is odd." %number)
if (number % 4 == 0):
print("%d is a multiple of 4." % number)
if (number % check == 0):
print("%d divides evenly in %d" %(number,check))
else:
print("%d does not divide evenly in %d." %(number,check))
| true |
e1b80889e822b256ac44f915be4d3d3d414bd042 | Neanra/EPAM-Python-hometasks | /xhlhdehh-python_online_task_4_exercise_1/task_4_ex_1.py | 486 | 4.1875 | 4 | """04 Task 1.1
Implement a function which receives a string and replaces all " symbols with ' and vise versa. The
function should return modified string.
Usage of any replacing string functions is prohibited.
"""
def swap_quotes(string: str) -> str:
str_list = []
for char in string:
if char == "'":
str_list.append('"')
elif char == '"':
str_list.append("'")
else:
str_list.append(char)
return ''.join(str_list) | true |
98418b93761efe90361044257d2ccb8821814a84 | smohapatra1/scripting | /python/practice/start_again/2023/08122023/daily_tempratures.py | 1,293 | 4.28125 | 4 | # 739. Daily Temperatures
# Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
# Example 1:
# Input: temperatures = [73,74,75,71,69,72,76,73]
# Output: [1,1,4,2,1,1,0,0]
# Example 2:
# Input: temperatures = [30,40,50,60]
# Output: [1,1,1,0]
# Example 3:
# Input: temperatures = [30,60,90]
# Output: [1,1,0]
# Approach :-
# Iterate through each day, check if the current day can resolve the most recently unresolved day.
# If it can then resolve the day, and continue checking and resolving until it finds a day it cannot resolve
# Add current day to unresolved days (stack)
def DailyTemp(tempratures):
stack=[] # All Indices that are still unsettled
res=[0] * len(tempratures) # Add new days to our stacks
for i, t in enumerate(tempratures):
while (stack and tempratures[stack[-1]] < t):
cur = stack.pop()
res[cur] = i - cur
stack.append(i)
return res
if __name__ == "__main__":
tempratures=[73,74,75,71,69,72,76,73]
print ("Results are {}".format(DailyTemp(tempratures))) | true |
b6e7a07afee721eaf42e989702f4e783ec895e52 | smohapatra1/scripting | /python/practice/start_again/2021/04242021/Day9_1_Grading_Program.py | 1,547 | 4.46875 | 4 | #Grading Program
#Instructions
#You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
#Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
#DO NOT modify lines 1-7 to change the existing student_scores dictionary.
#DO NOT write any print statements.
#This is the scoring criteria:
#Scores 91 - 100: Grade = "Outstanding"
#Scores 81 - 90: Grade = "Exceeds Expectations"
#Scores 71 - 80: Grade = "Acceptable"
#Scores 70 or lower: Grade = "Fail"
#Expected Output
#'{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}'
student_scores = {
"sam" : 90,
"jon" : 50,
"tom" : 88,
"harry" : 60,
}
student_grades = {}
for student in student_scores:
score = student_scores[student]
#print (student)
if score >= 90 :
student_grades[student] = "Outstanding"
print (f"{student} - {student_grades[student]} - {score} ")
elif score > 70:
student_grades[student] = "Exceeds Expectations"
print (f"{student} - {student_grades[student]} - {score} ")
else:
student_grades[student] = "Fail"
print (f"{student} - {student_grades[student]} - {score} ") | true |
bcff2a824797cb88f04d621f495d065e21061c2b | smohapatra1/scripting | /python/practice/start_again/2021/01312021/Arithmetic_Progression_Series.py | 1,113 | 4.1875 | 4 | #Python Program to find Sum of Arithmetic Progression Series
#Write a Python Program to find the Sum of Arithmetic Progression Series (A.P. Series) with a practical example.
#Arithmetic Series is a sequence of terms in which the next item obtained by adding a common difference to the previous item.
# Or A.P. series is a series of numbers in which the difference of any two consecutive numbers is always the same.
# This difference called a common difference.
#In Mathematical behind calculating Arithmetic Progression Series
#Sum of A.P. Series : Sn = n/2(2a + (n – 1) d)
#Tn term of A.P. Series: Tn = a + (n – 1) d
def main():
a = int(input("Enter the first number: "))
n = int(input("Enter the how many numbers you want: "))
d = int(input("Enter the difference : "))
total = (n * (2 * a + (n-1) * d) /2)
tn = a + (n-1)* d
i = a
print ("A.P series : " , end=" ")
while ( i <= tn):
if i != tn:
print ("%d" %i , end=" ")
else:
print ( "%d = %d " %(i, total))
i = i + d
print ("\n")
if __name__ == "__main__":
main() | true |
7e01c666f5165874a1c7a19b71006f19781ef8bd | smohapatra1/scripting | /python/practice/start_again/2021/04192021/Day5.4-Fizbuzz_Exercise.py | 893 | 4.53125 | 5 | # Fizzbuzz exercise
#FizzBuzz
#Instructions
#You are going to write a program that automatically prints the solution to the FizzBuzz game.
#Your program should print each number from 1 to 100 in turn.
#When the number is divisible by 3 then instead of printing the number it should print "Fizz".
#`When the number is divisible by 5, then instead of printing the number it should print "Buzz".`
#`And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"`
#e.g. it might start off like this:
#`1
#2
#Fizz
#4
#Buzz
#Fizz
#7
#8
#Fizz
#Buzz
#11
#Fizz
#13
#14
#FizzBuzz`
for num in range (1,10):
if num % 3 == 0 and num % 5 == 0 :
print (f"FizzBuzz - {num}")
elif num % 3 == 0:
print (f"Fizz - {num}")
elif num % 5 == 0 :
print (f"Buzz - {num}")
else:
print (f" {num} Not divisible by 3 or 5") | true |
557e3ada7a2d31cacb69c92e24adcd9cabc203b8 | smohapatra1/scripting | /python/practice/start_again/2021/02032021/sum_of_odd_even.py | 533 | 4.375 | 4 | #Python Program to Calculate Sum of Odd Numbers
#Write a Python Program to Calculate Sum of Odd Numbers from 1 to N using While Loop, and For Loop with an example.
# Sum of even numbers as well
def main():
n = int(input("Enter the N numbers you want : "))
even = 0
odd = 0
for i in range (1, n+1):
#EVEN
if i % 2 == 0 :
even = even + i
else:
odd = odd + i
print ("Sum of ODD = % d AND Sum of Even = %d " % ( odd, even ))
if __name__ == "__main__":
main() | true |
afaab750d64902af88baf0e0f775bbf9e7e8e3b0 | smohapatra1/scripting | /python/practice/start_again/2023/07202023/topk_frequent_elements.py | 986 | 4.1875 | 4 | # 347. Top K Frequent Elements
# Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
#Ref https://interviewing.io/questions/top-k-frequent-elements
# Example 1:
# Input: nums = [1,1,1,2,2,3], k = 2
# Output: [1,2]
# Approach :-
# Accept the array of integers
# Loop through the integers
# Use counters
#BFM
def top_k(nums,k):
counts={}
for num in nums:
if num not in counts:
counts[num] = 1
else:
counts[num] +=1
# Sort in descending order based on the counts
counts_list=sorted(counts.items(), key=lambda x:x[1], reverse=True)
sorted_counts=dict(counts_list[:k])
return [num for num in sorted_counts]
if __name__ == "__main__":
nums=[1,2,3,4,5,1,2,4,4,4,4]
k=5 # Highest number of repeated numbers to show
print("Current numbers {}".format(nums))
print("Most frequent number is {}".format(top_k(nums,k))) | true |
70102efaa0cb459776deb46145e3ea97dd87d796 | smohapatra1/scripting | /python/practice/start_again/2021/04252021/Day9.2_Calculator.py | 926 | 4.25 | 4 | #Design a calculator
def add (n1, n2):
return n1 + n2
def sub (n1, n2):
return n1 - n2
def mul (n1, n2):
return n1 * n2
def div (n1, n2):
return n1 / n2
operations = {
"+" : add,
"-" : sub,
"*" : mul,
"/" : div,
}
def calculator():
num1=float(input("Enter the first number : "))
for operators in operations:
print (operators)
dead_end=False
while dead_end == False:
action=input("Pick the operations from line abobe: ")
num2=float(input("Enter the 2nd number: "))
calculation_function=operations[action]
answers=calculation_function(num1, num2)
print (f" {num1} {action} {num2} = {answers}")
ask=input("Enter 'y' to continue or 'n' to exit: ")
if ask == "y":
num1 = answers
else:
print ("Exit the calculation ")
dead_end=True
calculator()
calculator()
| true |
2a223dffa17d46d91db72e500c1a87f93f3a9f04 | smohapatra1/scripting | /python/practice/start_again/2023/07182023/valid_anagram.py | 1,311 | 4.3125 | 4 | # #Given two strings s and t, return true if t is an anagram of s, and false otherwise.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: s = "anagram", t = "nagaram"
# Output: true
# Example 2:
# Input: s = "rat", t = "car"
# Output: false
#Solution
# 1. Validate and make sure these are strings
# 2. First we have to convert these strings into lower case
# 3. Make sure len of each string is equal, else false
# 4. Sort those string and if they are equal , return True , else False
# 5. If they matches then its a valid anagram
# 6. Else it's not a valid anagram
import os
def find_anagram(string1, string2 ):
a=len(string1)
b=len(string2)
if a != b :
return False
elif (sorted(string1) == sorted(string2)):
return True
else:
return False
if __name__ == "__main__":
string1=input("Enter the first String1: ".lower())
string2=input("Enter the first String2: ".lower())
if find_anagram(string1, string2):
#print ("The" , string1, string2 , "are anagram" )
print ("The {} and {} are anagram" .format(string1, string2))
else:
print ("The {} and {} are not anagram" .format(string1, string2) ) | true |
cd9f44ea5f2845dcbd9d2483658a21b34ec17773 | smohapatra1/scripting | /python/practice/start_again/2023/07192023/two_sum.py | 1,032 | 4.21875 | 4 | #Two Sum :-
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
# Steps
# Define the array of integers - nums
# Define another integer - target
# Get the two integers
# Added the two integers
# Go until its end and return the Sum of two integers
#BFM
def twoSum(nums,target):
n=len(nums)
required={}
for i in range(n):
for j in range(i+1, n ):
if nums[j] == target - nums[i]:
return [i, j]
#print ("The fields are {},{} and values are {} + {} = {}".format(i , j, nums[i], nums[j],target))
return False
if __name__ == "__main__":
nums=[1,2,3,5,8,10]
target=3
print ("The nums are {} & Target is {}".format(nums, target))
print ("The Number positions for the target are {}".format(twoSum(nums,target))) | true |
68ce09d3a1a0f6ab6630400048a6298dab9f0e3f | smohapatra1/scripting | /python/practice/start_again/2022/01232022/Odd_even.py | 253 | 4.375 | 4 | #Ask an user to enter a number. Find out if this number is Odd or Even
def odd_even(n):
if n > 0:
if n %2 == 0 :
print (f'{n} is even')
else:
print (f'{n} is odd')
odd_even (int(input("Enter the number : "))) | true |
6a5481244b5254a8fb1b1a2c529021559e5b7e42 | smohapatra1/scripting | /python/practice/start_again/2020/11232020/return_unique_way2.py | 364 | 4.15625 | 4 | #Write a Python function that takes a list and returns a new list with unique elements of the first list.
#Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]
#Unique List : [1, 2, 3, 4, 5]
def uniq(x):
uNumber = []
for nums in x:
#print (nums)
if nums not in uNumber:
uNumber.append(nums)
print (uNumber)
uniq([1,1,1,1,2,2,3,3,3,3,4,5]) | true |
276855e33856f3c06ffb785c92368e084a2cbcdd | smohapatra1/scripting | /python/practice/day28/while_loop_factorial.py | 464 | 4.3125 | 4 | #/usr/bin/python
#Write a program using while loop, which asks the user to type a positive integer, n, and then prints the factorial of n. A factorial is defined as the product of all the numbers from 1 to n (1 and n inclusive). For example factorial of 4 is equal to 24. (because 1*2*3*4=24)
a = int(input("Enter a number "))
f = 1
count = 1
while f <= a :
count = f * count
f +=1
#count +=1
print ("v : % d and c %d " % (f, count))
print (count)
| true |
24e90f48c6eb41aef70079751e3637e3bfae7a9a | smohapatra1/scripting | /python/practice/day54/inverted_pyramid.py | 243 | 4.375 | 4 | #Example 3: Program to print inverted half pyramid using an asterisk (star)
def triag(x):
for i in range(x,0,-1):
for j in range(1, i - 1):
print("*", end=" ")
print("\r")
triag(int(input("Enter a value : ")))
| true |
7908fb2010308508274fe772a706bdb847b8c547 | smohapatra1/scripting | /python/practice/day57/merge_k_sorted_list.py | 625 | 4.15625 | 4 | '''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
class Solution:
def k_list(self, lists):
res =[]
for i in range(len(k_list)) :
item=lists[i]
while item != None:
res.append(item.val)
item = item.next
res = sorted(res)
return res
#k_list(input("Enter lists with space: "),input("Enter lists with space: "), input("Enter lists with space: "))
lists(input("Enter lists with space: "))
| true |
a8e64901300abcb4c2605b7631d0e6580bc44723 | smohapatra1/scripting | /python/practice/start_again/2020/10212020/print_format.py | 558 | 4.1875 | 4 | #Use print Format
string="Hello"
print('Hello {} {}' .format('Samar' ,' , How are you?'))
# Another format of replacing indexes/formats
print('Hello {1} {0}' .format('Samar' ,' , How are you?'))
#Using key value pairs
print ('Hello {a} {b}'.format(a='Samar,', b='How are you?'))
result = 100/777
print ('Your result is {r}'.format(r=result))
#Format values - "value:width.percision f""
print ('Your result is {r:1.3f}'.format(r=result))
#Formatted string
name="samar"
print(f'My name is {name}')
print('Python {} {} {}'.format('rules!', 'and', 'rocks'))
| true |
6a2dd722f1b305bbf17ac97b270637cb14187954 | smohapatra1/scripting | /python/practice/start_again/2020/12022020/bank_withdrawal.py | 1,221 | 4.1875 | 4 | #For this challenge, create a bank account class that has two attributes:
#owner
#balance
#and two methods:
#deposit
#withdraw
#As an added requirement, withdrawals may not exceed the available balance.
class bank():
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
#print ("{} is owner".format(self.owner))
def get_deposit(self,deposit):
self.balance += deposit
print ("{} is deposited".format(deposit))
print ("{} is new balance".format(self.balance))
def get_withdraw(self,withdraw):
if withdraw >= self.balance :
print ("Balance unavailable")
else:
self.balance -= withdraw
print ("Your new balance is {}".format(self.balance))
def __str__(self):
return "Owner : {self.owner} \n Balance : {self.balance}"
#withdrawal = 1000
#deposit = 300
myaccount = bank("Sam", 100)
print ("{} is only owner".format(myaccount.owner))
print ("{} Initial Balance".format(myaccount.balance))
myaccount.get_deposit(300)
myaccount.get_withdraw(1000)
#print ("I have {} in balance".format(self.balance)
#print ("I have total {} new in balance".format(self.balance))
| true |
e7ac2a2569c2a6f6fedbcf050a7c47324aab22f0 | smohapatra1/scripting | /python/practice/start_again/2021/05192021/Day19.3_Turtle_Race.py | 1,068 | 4.125 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
user_bet= screen.textinput(title="Make your bet", prompt="While turtle will win")
color = ["red", "orange", "blue", "purple", "yellow", "green"]
y_position = [-70, -40, -10, 20, 50, 80 ]
all_turtle = []
for turtle_index in range(0,6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(color[turtle_index])
new_turtle.goto(x=-230, y=y_position[turtle_index])
all_turtle.append(new_turtle)
is_race_on=False
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() > 230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print (f"You have own. The winning color {winning_color}")
else:
print (f"You have lost. The winning color {winning_color}")
random_distance = random.randint(0,10)
turtle.forward(random_distance)
screen.exitonclick()
| true |
9bc20c7bd49c75ad4fa1f7f14bdaf53b067c2765 | smohapatra1/scripting | /python/practice/day22/4.if_else_elsif.py | 454 | 4.34375 | 4 | #!/usr/bin/python
#Write a program which asks the user to type an integer.
#If the number is 2 then the program should print "two",
#If the number is 3 then the program should print "three",
#If the number is 5 then the program should print "five",
#Otherwise it should print "other".
a = int(raw_input("Enter an integer : "))
if a == 2 :
print ('two')
elif a == 3 :
print ('three')
elif a == 5 :
print ('five')
else:
print ('other')
| true |
9e3497c111907de60e9c65126ccb0392bb226cb8 | smohapatra1/scripting | /python/practice/start_again/2023/07282023/valid_palindrome.py | 1,570 | 4.21875 | 4 | # 125. Valid Palindrome
# A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.
# Alphanumeric characters include letters and numbers.
# Given a string s, return true if it is a palindrome, or false otherwise.
# Example 1:
# Input: s = "A man, a plan, a canal: Panama"
# Output: true
# Explanation: "amanaplanacanalpanama" is a palindrome.
# Example 2:
# Input: s = "race a car"
# Output: false
# Explanation: "raceacar" is not a palindrome.
# Solution
# Remove the spaces and punctuation
# Convert them into lowercase using link comprehension
# Join them into a new string
# Find the string with Start and End indices
# Now look for first and last letters of the string, if they matches it's good, Go to next letter
# Keep doing that check until it runs out of letters to check
# If it doesn't find a pair, return false
# The process continues until either the indices cross each other or a mismatch found
# OR
# Using built in functions
def palindrome( word: str) -> bool:
# word1=""
# for i in word:
# if i.isalpha():word1 +=i.lower()
# if i.isnumeric():word1 +=i
# return word1 == word1[::-1]
word=[char.lower() for char in word if word.isalnum()]
return word == word[::-1]
if __name__ == "__main__":
word="A man, a plan, a canal: Panama"
print ("The word is : {}".format(word))
print ("The '{}' is Palindrome: {}".format(word, palindrome(word)))
| true |
9824a4b453375626bcb9f8aa7b44a1918bb9aefc | smohapatra1/scripting | /python/practice/start_again/2021/01282021/multiplication_table.py | 522 | 4.34375 | 4 | #Python Program to Print Multiplication Table
#Write a Python Program to Print Multiplication Table using For Loop and While Loop with an example.
#https://www.tutorialgateway.org/python-program-to-print-multiplication-table/
def main():
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
for i in range (a,b):
for j in range (1, b+1):
print ("{} * {} = {}".format(i,j,i*j))
print ("==================")
if __name__ == "__main__":
main() | true |
20c8b64f6be8db91cba68f554d3e3ae05419dd91 | smohapatra1/scripting | /python/practice/start_again/2020/11192020/exercise1_volume_sphere.py | 246 | 4.59375 | 5 | #Write a function that computes the volume of a sphere given its radius.
#Volume = 4/3 * pi * r**2
from math import pi
def volume(x):
v = ( (4/3) * pi * (x**3))
print ("The volume is {}".format(v))
volume(input("Enter the the radius : ")) | true |
46498d3f88a2b0fc51b346c66a97e5fda3a0062e | smohapatra1/scripting | /python/practice/start_again/2022/01112022/function_strip_and_lower.py | 377 | 4.125 | 4 | #Define a fucntion strip and lower
#This function should remove space at the begining and at the end of the string
# this it will convert the string into lower case
import string
import os
def strip_lower(a):
remove_space=a.strip()
print (f'{remove_space}')
lower_text=remove_space.lower()
#return lower_text
print (f'{lower_text}')
strip_lower(" Samar Mohapatra ")
| true |
dabf1a922d38efaf401cf0965010f9cf573ea5e6 | smohapatra1/scripting | /python/practice/start_again/2022/01232022/Seasonal_dress.py | 595 | 4.3125 | 4 | # Define a function that decides what to wear, according to the month and number of the day.
# It should ask for month and day number
# Seasons and Garments :
# Sprint - Shirt
# Summer : T-Shirt
# Autumn : Sweater
# Winter : Coat
def what_to_wear (m, d ):
if m == "March" and d < 15 or d > 20:
print (f'In {m}, day {d} Wear - Shirt ')
elif m == "June" and d < 15 :
print (f'In {m}, day {d} wear : Shirt')
elif m == "Decemember" and d < 15 :
print (f'In {m}, day {d} wear - Coat')
what_to_wear (str(input("Enter Month: ")), int(input("Enter day: "))) | true |
abafe23702ae19b7226190cf0d257696b2b37246 | smohapatra1/scripting | /python/practice/start_again/2023/07202023/group_anagrams.py | 1,268 | 4.375 | 4 | # Given an array of strings strs, group the anagrams together. You can return the answer in any order.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat","bat"]
# Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
# Idea
# Enter the arrays
# Create a dictionary
# Loop through each word
# Break the words and sort them with Join
# If word exists, append the word to the value list of the corresponding keys
# if key doesn't exist create a new key with sorted word
# After iterating through all the words, return the values of the dictionary as a list of lists with groups
def groupAnagram(words):
anagram_dict={}
for word in words:
sorted_word=''.join(sorted(word))
if sorted_word in anagram_dict:
anagram_dict[sorted_word].append(word)
else:
anagram_dict[sorted_word]=[word]
return list(anagram_dict.values())
if __name__ == "__main__":
words=["eat","tea","tan","ate","nat","bat"]
n=len(words)
print("The original list {}".format(words))
print("The formatted list {}".format(groupAnagram(words))) | true |
6dde775a5d0c80f11e01a71098f64c47bc20d618 | smohapatra1/scripting | /python/practice/start_again/2022/09112022/Reverse_array.py | 334 | 4.21875 | 4 | #Reverse array
def reversearray(array):
n=len(array)
lowindex=0
highindex=n-1
while highindex > lowindex:
array[lowindex], array[highindex] = array[highindex], array[lowindex]
lowindex+=1
highindex-=1
if __name__ == '__main__':
array=[1,2,3,4,5]
reversearray(array)
print (array) | true |
f87568f78e5811a171fd3a48a693fbabad90f562 | smohapatra1/scripting | /python/practice/day8/loop_until_your_age.py | 243 | 4.34375 | 4 | #!/usr/bin/python
#Create a loop that prints out either even numbers, or odd numbers all the way up till your age. Ex: 2,4,6,....,14
age = int(raw_input("Enter your age: "))
for i in range(0,age, 2):
print ("%d is a even number") % i
| true |
16dd759bfb679b455f370364a9113c3d1bdc3979 | cristearadu/CodeWars--Python | /valid parentheses.py | 966 | 4.25 | 4 | #Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function
#should return true if the string is valid, and false if it's invalid.
#0 <= input.length <= 100
def valid_parentheses(string):
if not string:
return True
ret_val = 0
for ch in string:
if ch == "(":
ret_val += 1
elif ch == ")":
ret_val -= 1
if ret_val < 0:
return False
return True if ret_val == 0 else False
return (True if dict_parentheses["("] == dict_parentheses[")"] else False)
#print(valid_parentheses("("))#False
#print(valid_parentheses(" ("))#False
#print(valid_parentheses("()"))#True
#print(valid_parentheses("(())((()())())"))#True
print(valid_parentheses(")test"))#False
print(valid_parentheses("hi(hi)()"))#True
print(valid_parentheses(""))#True
print(valid_parentheses(")("))
| true |
d22ddd5a6b3f4bd42aefe3384054ceea2fef38db | OMAsphyxiate/python-intro | /dictionaries.py | 1,084 | 4.9375 | 5 | # Dictionaries allow you to pair data together using key:value setup
# For example, a phone book would have a name(key):phone number (value)
# dict[key] --> value
# Stored using {}
phone_book1 = {'qazi':'123-456-7890', 'bob':'222-222-2222', 'cat':'333-333-3333'}
# This can be created this way to make the code more readable
# Also makes it easier to add addtional values based on the keys
phone_book = {
'qazi':['123-456-7890', 'qazi@qazi.com'],
'bob':['222-222-2222', 'bob@bob.com'],
'cat':['333-333-3333', 'cat@cat.com']
}
# Now we have a dictionary that contains three keys (qazi, bob, cat)
# And each key contains a list of elements
# And each list contains two elements
# Now that we've stored a few key:value pairs, we can tap into the values using the keys
print(phone_book1['qazi']) #will print out the value of the key 123-456-7890
print(phone_book['qazi']) #will print out the list of values phone and email
# If we only want a single item in the list of values
print(phone_book['qazi'][1]) #Will index the 2nd value (0, 1) from the list
# resulting in printing his email qazi@qazi.com | true |
55d6cf63e7d64239137d5156afbeae90b661c6e5 | whuang67/algorithm_dataStructure | /Part6_Search_Sort/SequentialSearch.py | 1,278 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 20:40:39 2018
@author: whuang67
"""
###### Sequential Search ######
def search(arr, item, sort=False):
## Unordered
def seq_search(arr, item):
pos = 0
found = False
while pos < len(arr) and not found:
print(pos)
if arr[pos] == item:
found = True
else:
pos += 1
return found
## Ordered
def ordered_seq_search(arr, item):
pos = 0
found = False
stopped = False
while pos < len(arr) and not found and not stopped:
print(pos)
if arr[pos] == item:
found = True
elif arr[pos] > item:
stopped = True
else:
pos += 1
return found
## If unknown, unordered is the default.
if sort:
return ordered_seq_search(arr, item)
else:
return seq_search(arr, item)
if __name__ == "__main__":
arr = [1,2,3,4,5,6,7]
arr2 = [7,6,5,4,3,2,1]
print(search(arr, 5, True))
print(search(arr, 10, True))
print(search(arr2, 1))
print(search(arr2, 10))
| true |
e3e3d68b5af0809f5bd6adc8d191a50158b63535 | drfoland/test-repo | /week_3/weekly-exercises/insertionSort.py | 662 | 4.1875 | 4 | ### This is my own insertionSort code completed as an eLearning exercise.
"""
main() function is used to demonstrate the sort() function
using a randomly generated list.
"""
def main():
### List Initialization
from numpy import random
LENGTH = 6
list = []
for num in range(LENGTH):
list.append(random.randint(100))
print("Unsorted List:")
print(list)
print()
list = sort(list)
print("Sorted List:")
print(list)
"""
sort() is the implementation of a basic insertion sort
algorithm.
"""
def sort(list):
### Beginning of Selection Sort Algorithm
"""
NEEDS TO BE UPDATED
"""
return list
if __name__ == "__main__":
main()
| true |
39e1e460c3ddf9293efa189a46e30f58c3222481 | Fili95160/Final1.PCBS | /exp.py | 2,903 | 4.125 | 4 | """A series of trials where a Circle is presented and the participant must press a key as quickly as possible.
"""
import random
from expyriment import design, control, misc, stimuli
########## ******************* PART 1.Experiment settings ******************* ####################
NTRIALS = 5
ITI = 1000 # inter trial interval
exp = design.Experiment(name="Side Detection")
control.initialize(exp)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen("Instructions",
f"""From time to time, a Circle will appear at the center of screen.
Your task is to press the space bar key as quickly as possible when you see it (We measure your reaction-time).
There will be {3*NTRIALS} trials in total.
Press the space bar to start.""")
###### 1.A --> Definition of the only two possible trials made up of two stimuli "Blue/Red"
#Stimulus red
visual_trial_red = design.Trial()
visual_trial_red.add_stimulus(stimuli.Circle(radius=100, colour=(255,0,0)))
#Stimulus blue
visual_trial_blue = design.Trial()
visual_trial_blue.add_stimulus(stimuli.Circle(radius=100, colour= (0,0,255)))
###### 1.B --> Definition of Associated Blocks "Blue/Red"
visual_block_red = design.Block("red")
# Buidlding red block with 5 stimuli
for i in range(NTRIALS):
visual_block_red.add_trial(visual_trial_red)
exp.add_block(visual_block_red) # Adding red block to experiment
# Building blue block with 5 stimuli
visual_block_blue = design.Block("blue")
for i in range(NTRIALS):
visual_block_blue.add_trial(visual_trial_blue)
exp.add_block(visual_block_blue) # Adding blue block to experiment
exp.add_data_variable_names([ 'block' , 'key' , 'time' ]) # Implementing data frame's columns name to study after experiment
visual_block_random = design.Block('random')
L=["red" , "blue"]
for i in range(NTRIALS):
rand = random.choice(L)
visual_block_random.name == rand
if(random == "red"):
visual_block_random.add_trial(visual_trial_red)
else:
visual_block_random.add_trial(visual_trial_blue)
exp.add_block(visual_block_random)
########## ******************* PART 2.Experiment ******************* ####################
control.start(skip_ready_screen=True) #begining experiment
instructions.present()
exp.keyboard.wait()
exp.clock.wait( 3000 )
for b in exp.blocks: # moving through each block
for t in b.trials: # iterating over stimuli inside each code
blankscreen.present()
exp.clock.wait( ITI ) # Fixed time between each stimulus.
exp.clock.wait( random.randint(1000, 2000) ) # Random time between 1 and 3 sec. between each stimulus.
t.stimuli[0].present() # Printing stimulus.
key, rt = exp.keyboard.wait(misc.constants.K_SPACE) # monitoring time
exp.data.add( [ b.name, key, rt ] ) #Adding data to our database
control.end() # ending experiment
| true |
881b990daf1d7e913a1d67e1001b3b861dfa706e | douzhenjun/python_work | /random_walk.py | 1,083 | 4.28125 | 4 | #coding: utf-8
from random import choice
class RandomWalk():
'''a class which generate random walking data'''
def __init__(self, num_points=20):
'''initial the attribute of random walking'''
self.num_points = num_points
#random walking origins from (0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
'''calculate all points belong to random walking'''
#random walking continually, until list up to the given length
while len(self.x_values) < self.num_points:
#the direction and the distance along this direction
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
#do not walking on the spot
if x_step == 0 and y_step == 0:
continue
#calculate the next point's x and y values
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
| true |
8e09b0b74fcfd1c9fab28dfc8cc0104feee6dea6 | justinminsk/Python_Files | /Intro_To_Python/X_Junk_From_Before_Midterm/SuperFloatPow.py | 338 | 4.125 | 4 | def SuperFloatPow(num, num2, num3) :
"""(number, number, number) -> float
Takes three numbers inculding float and the first number is taken to the
second numbers power then divided by the third and the answer is the remainder
>>>SuperFloatPow(4.5, 6.4, 8.9)
7.344729065655461
"""
return((num**num2)% num3)
| true |
6555a2c4680eff23807d266a903c229bc506abe6 | justinminsk/Python_Files | /Intro_To_Python/HW11/rewrite.py | 1,505 | 4.3125 | 4 | import os.path
def rewrite(writefile):
while os.path.isfile(writefile): # sees if the file exsits
overwrite = input('The file exists. Do you want to overwrite it (1), give it a new name (2), or cancel(3).')
# menu
if overwrite == '1':
print('I will overwrite the ' + writefile + ' file.')
with open(writefile, 'w') as file: # write over the file
newtext = input('Enter you new text') # get new text to put in the file
file.write(newtext) # write the new text into file
break # end loop
elif overwrite == '2':
print('I will now change the name of ' + writefile + ' file')
newtitle = input('Enter new file name with .txt') # get new title
with open(writefile, 'r') as file: # read the old file
with open(newtitle, 'w') as title: # write the new file
for text in file: # read all of the text
text = text # save the text as a variable
title.write(text) # write the new file
break # end loop
elif overwrite == '3':
return 'Canceling' # ends the rewrite
else:
print('Invalid key pressed') # print to let user know what they did wrong
continue # restart loop
if __name__ == '__main__': # Run the rewrite
rewrite('test.txt') # run using test.txt
# test.txt has:
# this is a text
# doc
| true |
8914809ff2f8fa02fc8368e032fd3faaa2c4aa8f | justinminsk/Python_Files | /Intro_To_Python/HW15/find_min_max.py | 689 | 4.1875 | 4 | def find_min_max(values):
"""(list of numbers) -> NoneType
Print the minimum and maximum value from values.
"""
min = values[0] # start at the first number
max = values[0] # start at the first number
for value in values:
if value > max:
max = value
if value < min:
min = value
print('The minimum value is {0}'.format(min))
print('The maximum value is {0}'.format(max))
if __name__ == '__main__':
find_min_max([0, 1, 3, 4, 0, 2, -1])
# None type screws up the list and produces an error
# change line 6 and 7 to the first item on the list. This still does not help with mixed lists (string and num).
| true |
8e80963193c11d414b5d73adbacb1cf3b952b6f6 | mshellik/python-beginner | /working_with_variable_inputs.py | 503 | 4.34375 | 4 | #this is to understand the variables with input and how we can define them and use them
YourFirstName=input("Please enter Your First Name: ") # Input will always take variable as string
YourLastName=input("Please enter your Last Name: ")
print(f'Your First Name is {YourFirstName} and the Last Name is {YourLastName}')
print("This is to EVAL with INPUT")
yourINPUT=eval(input("Please Enter either Num/float/Text in quotes :" ))
print(f'The type of input you have entered is {type(yourINPUT)}')
| true |
0aeffedd3cf8073d2e6bdd291ec17485d5e3aefd | kai-ca/Kai-Python-works | /LAB08/dicelab/dice.py | 1,442 | 4.15625 | 4 | """ Dice rolls. We roll dice. One die or a
pair of dice. The dice usually have six
sides
numbered 1 thru 6, but we also allow
dice with any nsides. See the test files
for details.
Copyright (c)2015 Ulf Wostner
<wostner@cyberprof.com>. All rights
reserved. """
import random
def roll(nsides=6):
"""Roll a die with nsides. Returns an
int from 1 to nsides."""
return random.randint(1, nsides)
def rollpair(nsides=6):
"""Roll a pair of nsided dice. Returns
rolls as tuples, like (3, 6)."""
return (roll(nsides), roll(nsides))
def rolls(ntimes=10, nsides=6):
"""Roll an nsided die ntimes. Returns a list.
>>> import random; random.seed('downtown')
>>> rolls()
[2, 5, 4, 5, 4, 1, 6, 6, 2, 2]
"""
rollList = []
for i in range(ntimes):
rollList.append(roll(nsides))
return rollList
def rollpairs(ntimes=10, nsides=6):
"""Roll a pair of nsided die ntimes.
Returns a list.
>>> import random; random.seed('pythonistas')
>>> rollpairs()
[(2, 6), (6, 2), (6, 4), (5, 5), (6,
3), (2, 4), (1, 3), (3, 4), (5, 6), (4,
5)]
"""
pairList = []
for i in range(ntimes):
pairList.append(rollpair(nsides))
return pairList
def dice_sum(pair):
""""Returns the sum of the values on
the dice pair.
>>> pair = (6, 1)
>>> dice_sum(pair)
7
"""
return sum(pair)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
b0d5a5d7747c0071fab9d13962963dbca0b44157 | kai-ca/Kai-Python-works | /LAB09/datastructlab/queuemodule.py | 1,198 | 4.5 | 4 | """We implement a Queue data structure.
Queue is a FIFO = First In First Out data structure, like people in line at a ticket office.
We create a class named Queue.
Then we can make instances of that class.
>>> myqueue = Queue()
>>> isinstance(myqueue, Queue)
True
>>> myqueue.push('Alice')
>>> myqueue.push('Eve')
Who is first in line?
>>> myqueue.peek()
'Alice'
Remove them in order (remember FIFO).
>>> myqueue.pop()
'Alice'
>>> myqueue.pop()
'Eve'
"""
class Queue:
"""Queue data structure.
"""
def __init__(self):
self.data = []
def push(self, item):
"Push item onto the Queue"
self.data.append(item)
def pop(self):
"""Remove the "top item" (the biggest item) from the Queue. """
return self.data.pop(0)
def is_empty(self):
"""Returns True if the Queue is empty."""
return self.data == []
def peek(self):
"""Return the item at "the front" of the Queue. Do not remove that item."""
return self.data[0]
def __str__(self):
return "<Queue: {} items>".format(len(self.data))
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
e72216a516cffe0cd78432f118de9d5fb6441a47 | kai-ca/Kai-Python-works | /LAB09/datastructlab/stackmodule.py | 1,658 | 4.21875 | 4 | """We implement a Stack data structure.
Stack is a LIFO = Last In First Out data
structure, like a atack of plates. The last
plate you put on the stack is the first plate
that will be removed.
Tip: Print out all the test files in the tests
directory and then get to work on the metods,
one by one.
Use your Stack class to create an instance
named mystack.
>>> mystack = Stack()
>>> isinstance(mystack, Stack)
True
The Stack has a push method. Push a bunch of
numbers onto the stack.
>>> for item in [90, 30, 50, 60, 20, 50]:
... mystack.push(item)
Remove an item from the stack using the pop
method you definfed for Stack. Notice that
it's LIFO !
>>> mystack.pop()
50
>>> mystack.pop()
20
>>> mystack.is_empty()
False
"""
class Stack:
"""Stack data structure.
>>> mystack = Stack()
"""
def __init__(self):
"""Creates an instance of Stack with no items in it."""
self.data = []
def push(self, item):
"Push item onto the stack."
self.data.append(item)
def pop(self):
"""Remove the item we put in last ( remember it's LIFO). """
return self.data.pop()
def is_empty(self):
"""Returns True if the stack is empty."""
return self.data == []
def peek(self):
"""Returns the top item of the stack but does not remove that item. Just peeking."""
return self.data[-1]
def __str__(self):
"""Method for casting Stack objects as str object. Used by print."""
return "<Stack: {} items>".format(len(self.data))
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
0da353feebc2597c645b088385db28f6f023235e | ramakrishna1994/SEM2 | /NS/Assg1/d_5_Decryption_Procedure_code.py | 2,803 | 4.28125 | 4 | '''
Author : Saradhi Ramakrishna
Roll No : 2017H1030081H
M.E Computer Science , BITS PILANI HYDERABAD CAMPUS
Description : Takes Cipher text as input and gives the Plain text as output
Input - 1.Key
2.Cipher Text
Output - Decrypted Plain Text
Steps : 1. Shifts the cipher in the length of key by 0,1,2,3,.... (SUBTRACTION)
2. Applies Vignere Cipher Decryption Procedure by repeating the key until it satisfies
the cipher text length.
3. Finally prints the decrypted plain text onto the console.
'''
file1 = open("h20171030081_decrypted.txt","r")
originalcipher = file1.read().strip()
key = "edgarcodd"
cipheraftershifting = ""
currentlength = 0;
currentshift = -1;
'''
Function which returns the decrypted character in vignere cipher by taking
a single encrypted character and single key character.
'''
def getDecryptedCharInVignere(enc,key):
e = ord(enc)
k = ord(key)
d = ((e - k + 26) % 26) + 65 # d = ((e - k + 26) mod 26) + 65
return chr(d)
'''
Shifting Original Cipher by 0,1,2,3.... in the length of key repetitively
'''
for c in originalcipher:
if ord(c) >=65 and ord(c) <=90:
if ((currentlength % len(key)) == 0):
currentlength = 0;
currentshift += 1;
res = ord(c) - (currentshift % 26)
if res < 65:
res += 26
cipheraftershifting += str(chr(res))
currentlength = currentlength + 1
elif ord(c) >=97 and ord(c) <= 122:
if ((currentlength % len(key)) == 0):
currentlength = 0;
currentshift += 1;
res = ord(c.upper()) - (currentshift % 26) # Shifting by 0,1,2,3,... (Subtraction)
if res < 65:
res += 26
cipheraftershifting += str(chr(res).lower())
currentlength = currentlength + 1
else:
cipheraftershifting += str(c)
currentlength = 0;
plaintextafterdecryption = ""
'''
Applying Vignere Cipher breaking procedure and getting the plain text.
Key is repeated in lengths of its size until it satisfies the plain text length.
'''
for c in cipheraftershifting:
if ord(c) >= 65 and ord(c) <= 90:
if ((currentlength % len(key)) == 0):
currentlength = 0;
plaintextafterdecryption += getDecryptedCharInVignere(c.upper(),key[currentlength].upper())
currentlength = currentlength + 1
elif ord(c) >= 97 and ord(c) <= 122:
if ((currentlength % len(key)) == 0):
currentlength = 0;
plaintextafterdecryption += getDecryptedCharInVignere(c.upper(),key[currentlength].upper()).lower()
currentlength = currentlength + 1
else:
plaintextafterdecryption += str(c)
print plaintextafterdecryption
| true |
761cfb3ca383146a744b8919598e46cfe7216cba | Gongzi-Zhang/Code | /Python/iterator.py | 850 | 4.625 | 5 | '''
Iterable is a sequence of data, one can iterate over using a loop.
An iterator is an object adhering to the iterator portocol.
Basically this means that it has a "next" method, which, when called
returns the next item in the sequence, and when there's nothing to
return, raise the StopIteration exception.
'''
'''
Why is iterator useful. When an iterator is used to power a loop, the loop
becomes very simple. The code to initialise the state, to decide if the loop
is finished, and t ofind the next value is extracted into a separate place,
therefore highlighting the body of the loop.
'''
'''
Calling the __iter__ method on a container to create an iterator
object is the most straightforward way to get hold of an iterator.
The iter function does that for us. Similarly, the next function
will call the __next__ method of the iterator.
'''
| true |
0aaa40fdb013ee3cc2b10000709f9fcc7241c476 | vrrohan/Topcoder | /easy/day11/srm740/getaccepted.py | 2,810 | 4.4375 | 4 | """
Problem Statement for GetAccepted
Problem Statement
For this task we have created a simple automated system. It was supposed to ask you a question by giving you a String question.
You would have returned a String with the answer, and that would be all. Here is the entire conversation the way we planned it:
"Do you want to get accepted?"
"True."
Unluckily for you, a hacker got into our system and modified it by inserting negations into the sentence.
Each negation completely changes the meaning of the question to the opposite one, which means that you need to give us the opposite answer.
Write a program that will read the question and answer accordingly. More precisely, your program must return either the string "True." if the question you are given has the same meaning as the one shown above or the string "False." if the question has the opposite meaning.
Definition
Class: GetAccepted
Method: answer
Parameters: String
Returns: String
Method signature: String answer(String question)
(be sure your method is public)
Notes
- All strings in this problem are case-sensitive. In particular, make sure the strings your program returns have correct uppercase and lowercase letters, as shown in the statement and examples.
Constraints
- question will always have the following form: "Do you " + X + "want to " + Y + "get " + Z + "accepted?", where each of X, Y and Z is the concatenation of zero or more copies of the string "not ".
- question will have at most 1000 characters.
Examples
0) "Do you want to get accepted?"
Returns: "True."
This is the original question, you should give the original answer.
1) "Do you not want to get accepted?"
Returns: "False."
This question has the opposite meaning from the original, you should give the opposite answer.
2) "Do you want to not get accepted?"
Returns: "False."
This is another possible negation of the original question.
3) "Do you want to get not not accepted?"
Returns: "True."
Two negations cancel each other out. The meaning of this question is the same as the meaning of the original question, so you should answer "True.".
4) "Do you not want to not get not not not accepted?"
Returns: "False."
"""
import re
def answer(question) :
allWords = re.split('\\s', question)
totalNots = 0
for nots in allWords :
if nots == 'not' :
totalNots = totalNots + 1
if totalNots%2 == 0 :
return "True."
else :
return "False."
print(answer("Do you want to get accepted?"))
print(answer("Do you not not not not not not not not not not not not want to not not not get not not not accepted?"))
print(answer("Do you not not not not not not not not not not not not not not not not not not not not not want to not not not not not not not not not get not not not not not not not accepted?"))
| true |
2fe7c4f1acffb9dbd5a1e8b005adbdb871bace1f | MoisesSanchez2020/CS-101-PYTHON | /cs-python/w02/team02_2.py | 1,352 | 4.40625 | 4 | """
File: teach02_stretch_sample.py
Author: Brother Burton
Purpose: Practice formatting strings.
This program also contains a way to implement the stretch challenges.
"""
print("Please enter the following information:")
print()
# Ask for the basic information
first = input("First name: ")
last = input("Last name: ")
email = input("Email address: ")
phone = input("Phone number: ")
job_title = input("Job title: ")
id_number = input("ID Number: ")
# Ask for the additional information
hair_color = input("Hair color: ")
eye_color = input("Eye color: ")
month = input("Starting Month: ")
training = input("Completed additional training? ")
# Now print out the ID Card
print("\nThe ID Card is:")
print("----------------------------------------")
print(f"{last.upper()}, {first.capitalize()}")
print(job_title.title())
print(f"ID: {id_number}")
print()
print(email.lower())
print(phone)
print()
# There are various ways to accomplish the spacing
# In this approach, I told it that hair_color will take exactly 15
# spaces, and month will take 14. That way, the next columns will
# line up. I had to do month 14 (instead of 15) because the word
# 'Month' that came before my value was one letter longer.
print(f"Hair: {hair_color:15} Eyes: {eye_color}")
print(f"Month: {month:14} Training: {training}")
print("----------------------------------------")
| true |
34abc2ab48a1065cb7f0055b1b0489654a406ed0 | MoisesSanchez2020/CS-101-PYTHON | /w04/team04.py | 2,862 | 4.28125 | 4 | """
File: teach04_sample.py
Author: Brother Burton
Purpose: Calculate the speed of a falling object using the formula:
v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
"""
import math
# while you don't _have to_, it's considered good practice to import libraries
# at the top of your program, so that others know exactly which libraries
# you are using.
print("Welcome to the velocity calculator. Please enter the following:\n")
# Note: In this example, I chose to use single letter variable names, because they
# map directly to variables in the physics equation, so it seemed like it would
# actually be more clear in this case to use the single letter variables than to
# try to use the more descriptive names of "mass" or "gravity".
m = float(input("Mass (in kg): "))
g = float(input("Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): "))
t = float(input("Time (in seconds): "))
p = float(input("Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): "))
A = float(input("Cross sectional area (in m^2): "))
C = float(input("Drag constant (0.5 for sphere, 1.1 for cylinder): "))
# First calculate c = 1/2 p A C
c = (1 / 2) * p * A * C
# Now calculate the velocity v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
v = math.sqrt(m * g / c) * (1 - math.exp((-math.sqrt(m * g * c) / m) * t))
print() # display a blank line
print(f"The inner value of c is: {c:.3f}")
print(f"The velocity after {t} seconds is: {v:.3f} m/s")
"""
File: teach04_sample.py
Author: Brother Burton
Purpose: Calculate the speed of a falling object using the formula:
v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
"""
import math
# while you don't _have to_, it's considered good practice to import libraries
# at the top of your program, so that others know exactly which libraries
# you are using.
print("Welcome to the velocity calculator. Please enter the following:\n")
# Note: In this example, I chose to use single letter variable names, because they
# map directly to variables in the physics equation, so it seemed like it would
# actually be more clear in this case to use the single letter variables than to
# try to use the more descriptive names of "mass" or "gravity".
m = float(input("Mass (in kg): "))
g = float(input("Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): "))
t = float(input("Time (in seconds): "))
p = float(input("Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): "))
A = float(input("Cross sectional area (in m^2): "))
C = float(input("Drag constant (0.5 for sphere, 1.1 for cylinder): "))
# First calculate c = 1/2 p A C
c = (1 / 2) * p * A * C
# Now calculate the velocity v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t))
v = math.sqrt(m * g / c) * (1 - math.exp((-math.sqrt(m * g * c) / m) * t))
print() # display a blank line
print(f"The inner value of c is: {c:.3f}")
print(f"The velocity after {t} seconds is: {v:.3f} m/s")
| true |
b0bcfd87202ae144fbf263229c4fe94efebb6072 | MoisesSanchez2020/CS-101-PYTHON | /w10/checkpoint.py | 917 | 4.3125 | 4 | # Create line break between the terminal and the program.
print()
# Explain use of program to user.
print('Please enter the items of the shopping list (type: quit to finish):')
print()
# Create empty shopping list.
shop_list = []
# Define empty variable for loop.
item = None
# Populate shop_list with user input:
while item != 'Quit':
item = input('Item: ').capitalize()
if item != 'Quit':
shop_list.append(item)
print('The shopping list is:')
for item in shop_list:
print(item)
print('The shopping list with indexes is:')
for i in range(len(shop_list)):
item = shop_list[i]
print(f'{i}. {item}')
print()
index = int(input('Which item would you like to change? '))
new_item = input('What is the new item? ').capitalize()
shop_list[index] = new_item
print('The shopping list with indexes is:')
for i in range(len(shop_list)):
item = shop_list[i]
print(f'{i}. {item}') | true |
e2a8d0f69d84f49228e816676adc8c6506905696 | vpdeepak/PirpleAssignments | /AdvancedLoops/main.py | 1,104 | 4.28125 | 4 | """
This is the solution for the Homework #6: Advanced Loops
"""
print("Assignment on Advanced Loops")
def DrawBoard(rows, columns):
result = False
if(rows < 70 and columns < 235):
result = True
for row in range(rows):
if(row % 2 == 0):
for column in range(columns):
if(column % 2 == 0):
if(column != columns - 1):
print(" ", end="")
else:
print(" ")
else:
if(column != columns - 1):
print("|", end="")
else:
print("|")
else:
for column in range(columns):
if(column != columns - 1):
print("-", end="")
else:
print("-")
return result
result = DrawBoard(69, 234)
if(result is False):
print("Playing Board doesn't fit the screen !! Please re-consider rows and column values")
| true |
6948f7fae7e5042b299b5953d967a2159c9ed999 | damani-14/supplementary-materials | /Python_Exercises/Chapter03/CH03_05.py | 543 | 4.15625 | 4 | # program to calculate the order costs for the "Konditorei Coffee Shop"
# cost = 10.50/lb + shipping
# shipping = 0.86/lb + 1.50 fixed overhead cost
import math
def main():
print("")
print("This program will calculate the total cost (10.50/lb) for your coffee plus shipping (0.86/lb + 1.50 fixed).")
print("")
wt = eval(input("Enter the quantity of coffee you would like to order in pounds: "))
print("")
cost = wt * 11.36 + 1.5
print("The total cost of your order + shipping is $", cost)
print("")
main() | true |
2bd6df777921168b3b76c52becaad87f6fe7ab70 | damani-14/supplementary-materials | /Python_Exercises/Chapter03/CH03_17.py | 958 | 4.3125 | 4 | # bespoke algorithm for calculating the square root of n using the "guess-and-check" approach
# Newton's method of estimating the square root, where:
# sqrt = (guess + (x/guess))/2
# guess(init) = x/2
import math
def main():
print("")
print("This program will estimate the square root of a value 'x' using 'n'",end="\n")
print("attempts to improve accuracy.",end="\n\n")
x = eval(input("Please select a value to estimate the square root: "))
n = eval(input("Please confirm the number of times to iterate: "))
guess = x/2
sr = 0
print("")
for i in range(1,n+1):
sr = (guess + (x / guess)) / 2
guess = sr
print("Attempt ",i,":",sep="",end="\n")
print("Guess = ",guess, sep="", end="\n")
print("Square Root = ", math.sqrt(x), sep="", end="\n")
print("Accuracy = ", (math.sqrt(x) - guess), sep="", end="\n\n")
print("...",end="\n\n")
print("END",end="\n\n")
main() | true |
c8ce4ca5959e673f92c28944bb53d3058329f4c5 | damani-14/supplementary-materials | /Python_Exercises/Chapter03/CH03_06.py | 555 | 4.21875 | 4 | # program which calculates the slope of a line given x,y coordinates of two user provided points
import math
def main():
print("")
print("This program will calculate ths slope of a non-vertical line between two points.")
print("")
x1,y1 = eval(input("Enter the coordinates of POINT 1 separated by a comma: "))
print("")
x2,y2 = eval(input("Enter the coordinates of POINT 2 separated by a comma: "))
print("")
m = (y2 - y1)/(x2 - x1)
print("The slope between the selected coordinates is: ", m)
print("")
main() | true |
ec940e4973e310100d24207050f870e66b0543b1 | damani-14/supplementary-materials | /Python_Exercises/Chapter05/CH05_01.py | 800 | 4.53125 | 5 | # CH05_01: Use the built in string formatting methods to re-write the provided date converting program p. 147
#-----------------------------------------------------------------------------------------------------------------------
# dateconvert2.py
# Converts day month and year numbers into two date formats
def main():
# get the day month and year
day, month, year = eval(input("Enter the day, month, and year numbers: "))
date1 = "/".join([str(month), str(day), str(year)])
print(date1)
months = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
monthStr = months[month-1]
date2 = monthStr+" "+str(day)+", "+str(year)
print("The date is {0} or {1}.".format(date1, date2))
main() | true |
22a1797bf0d139c56371968d6ba26eb7f176ed81 | damani-14/supplementary-materials | /Python_Exercises/Chapter08/CH08_01.py | 400 | 4.25 | 4 | # CH08_01: Wite a program that computes and outputs the nth Fibonacci number where n is a user defined value
#----------------------------------------------------------------------------------------------------------------------
def main():
a, b = 1,1
n = eval(input("Enter the length of the Fibonacci sequence: "))
for i in range(n-1):
a, b = b, (a+b)
print(a)
main() | true |
37c43ced0891ada8ca9d7b2d01df59b9ba96113c | JacksonJ01/List-Operations | /Operations.py | 2,338 | 4.28125 | 4 | # Jackson J.
# 2/10/20
# List Operations with numbers
from ListMethodsFile import *
print("Hello user, today we're going to do some tricks with Lists"
"\nFor that I'm going to need your help"
"\nOne number at a time please")
# This loop will get all five values needed for the methods in the other file to run properly.
# It also calls the adding function which appends the lists
inc = 1
dec = 5
while inc <= 5:
print(f"\n{dec} more numbers required")
adding()
inc += 1
dec -= 1
# Calls the sort method
sort()
# calls the method to sum the List
print("\nThe sum of all the numbers is:", s_m())
time_()
# This will call the multiply the 5 values
print("\nThe product of numbers in this list is:", product())
time_()
# Call the the average function
print("\nThe mean, or average of these numbers is:", mean())
time_()
# The calls the median function
print("\nThe median is:", median())
time_()
# Calls the mode function to check if the list contains a mode
print("\nNow lettuce check if this list has any modes:")
if mode() == "Yes":
print("")
else:
print("No, this list doesn't have a mode.")
time_()
# Call the function to check what the largest number is
print("\nThe largest number in this list is:", large())
time_()
# Call the function to check what the smallest number is
print("\nThe smallest number in the list is:", smallest())
time_()
# If there is a mode, then this deletes it
print("\n")
if mode() == "Yes":
print("*As we stated earlier*."
"\nSo, let's remove any extra numbers:")
else:
print("There are no reoccurring numbers, so nothing will be removed from the list.")
time_()
# Calls the function to display odd numbers
print("\nTime to take out the even numbers:"
"\nODD:")
only_odd()
time_()
# Calls the function to display even numbers
print("\nAnd now to take out the odd numbers"
"\nEVEN:")
only_even()
time_()
# Checks if the user input equals one of the numbers in the list
print(f"\nType a number and we'll see if it's in the list of numbers you gave me:")
included()
time_()
# Shows the second largest number in the list
print("\nHey hey hey, bonus time")
print(f"\nThe second largest number in this list is:", sec_large(), "\b.")
time_()
print("Well, that wasn't much of a crazy ending, but thanks for participating.")
| true |
2a54f5959a20c597b8250b63a2e3852066193204 | tstennett/Year9DesignCS4-PythonTS | /StringExample.py | 984 | 4.5 | 4 | #This file will go through the basics of string manipulation
#Strings are collections of characters
#Strings are enclosed in "" or ''
#"Paul"
#"Paul is cool"
#"Paul is cool!"
#Two things we need to talk about when we think of strings
#index - always starts at 0
#length
#example
# 0123 012345
#"Paul" "Monkey"
#len("Paul") = 4
#len("Monkey") = 6
name = "Paul"
print(name) #I can print strings
sentence = name + " is cool!" #concatination is adding strings
print(sentence)
print(sentence + "!")
#I can access specific letters
fLetter = name[0] #name at 0 (first character)
print(fLetter)
letters1 = name[0:2] #inclusive:exclusive (up to 2)
print(letters1)
letters2 = name[2:1]
print(letters2)
letters2a = name[2:len(name)] #forma way of writing letters 2a
print(letters2a)
letters3 = name[:2]
print(letters3)
lname = len(name) #length of string
print(lname)
#if I want to print out all letters
for i in range(len(name)):
print(name[i])
| true |
cae88fdf277cf60c97b82bac80aea1729728ffdd | juanchuletas/Python_dev | /objects.py | 825 | 4.21875 | 4 | #!/usr/bin/python
# In python everything is an object
# a variable is a reference to an object
# each object has an identity or an ID
x = 1
print(type(x))
print(id(x))
#####################
# class 'int'
# 139113568
####################
# number, string, tuple -> inmutable
# list, dictionary -> mutable
x = 1
y = 1
print(type(x))
print(id(x))
print(type(y))
print(id(y))
if x==y:
print("True")
else:
print("False")
if x is y:
print("True")
else:
print("False")
##################
# see the last two lines, both are true # class 'int'
# 139113568
# class 'int'
# 139113568
# True
# True
##################
a = dict(x = 1, y = 1)
print(type(a))
print(id(a))
b = dict(x = 1, y = 1)
print(id(b))
if a == b:
print("True")
else:
print("False")
if a is b:
print("True")
else:
print("False")
| true |
056aa02e58696d83b7e75f8cadad3339e09096ed | goodGopher/HWforTensorPython | /DZ4to11032021/prog4_deliting_elements.py | 823 | 4.125 | 4 | """Removing duplicate elements in list.
Functions:
list_reading(my_list):
Allows to read list from keyboard.
remove_copies(m_list):
Removing duplicate elements in list.
main():
Organize entering and clearing of list.
"""
import checks
def remove_copies(m_list):
"""Removing duplicate elements in list."""
rand_list = list(set(m_list))
m_list.reverse()
for i in rand_list:
while m_list.count(i) > 1:
m_list.remove(i)
m_list.reverse()
def main():
"""Organize entering and clearing of list."""
print("Введите список через Enter:")
main_list = []
checks.list_reading(main_list)
remove_copies(main_list)
print(f"обработанный список {main_list}")
if __name__ == "__main__":
main()
| true |
64b15b4ed5ed67df6e7f912891491dbc6576230c | adiiitiii/IF-else | /alphabet digit or special char???.py | 233 | 4.125 | 4 | ch=input("enter any character")
if ch>"a" and ch<"z" or ch>"A" and ch<"Z" :
print("the character is an alphabet")
elif ch[0].isdigit():
print("the character is a digit")
else:
print("the character is a special character") | true |
a84e87ca3ec6379c4c7582862ed4ff48f4cbee24 | 121710308016/asignment4 | /10_balanced_brackets.py | 2,396 | 4.15625 | 4 | """
You're given a string s consisting solely of "(" and ")".
Return whether the parentheses are balanced.
Constraints
Example 1
Input
s = "()"
Output
True
Example 2
Input
s = "()()"
Output
True
Example 3
Input
s = ")("
Output
False
Example 4
Input
s = ""
Output
True
Example 5
Input
s = "((()))"
Output
True
"""
import unittest
# Implement the below function and run this file
# Return the output, No need read input or print the ouput
# Workout the solution or the logic before you start coding
def balanced_brackets(sentence):
def is_match(ch1, ch2):
match_dict = {')':'(', ']':'[', '}':'{'}
return match_dict[ch1] == ch2
lst = []
close = [']', ')', '}']
open = ['{', '(', '[']
for i in sentence:
if i in open:
lst.append(i)
if i in close:
if len(lst)==0:
return False
if not is_match(i,lst.pop()):
return False
return (len(lst)==0)
# DO NOT TOUCH THE BELOW CODE
class TestBalancedBrackets(unittest.TestCase):
def test_01(self):
self.assertEqual(balanced_brackets("()"), True)
def test_02(self):
self.assertEqual(balanced_brackets("()()"), True)
def test_03(self):
self.assertEqual(balanced_brackets(")("), False)
def test_04(self):
self.assertEqual(balanced_brackets(""), True)
def test_05(self):
self.assertEqual(balanced_brackets("((()))"), True)
def test_06(self):
self.assertEqual(balanced_brackets("((((())))(()))"), True)
def test_07(self):
self.assertEqual(balanced_brackets(
"(((((((((())))))))))()((((()))))"), True)
def test_08(self):
self.assertEqual(balanced_brackets(")))))((((("), False)
def test_09(self):
self.assertEqual(balanced_brackets(
"()()(((((((((()()))))))))))((((()))))"), False)
def test_10(self):
self.assertEqual(balanced_brackets(
"()()()(((())))((()))()()(()())(((((())()()()()()))))"), True)
def test_11(self):
self.assertEqual(balanced_brackets(
"()((((((()()()()()((((((())))))))))(())))()))))))()()(((((()))))))))))))))))))())()))"), False)
if __name__ == '__main__':
unittest.main(verbosity=2)
| true |
746a47a541ca0da03832a24b02ef340be66659ec | src053/PythonComputerScience | /chap3/ladderAngle.py | 891 | 4.5 | 4 | # This program will determine the length of the ladder required to
# reach a height on a house when you have that height and the angle of the ladder
import math
def main():
# Program description
print("This program will find the height a ladder will need to be when given two inputs")
print("1) The height of the house 2) the angle (in degrees) of the ladder")
height = eval(input("Please provide the height of the house: ")) # The var that contains the height of the house
degrees = eval(input("Please provide the angle of the ladder against the house: ")) # The var that contains the degree angle of the ladder
radians = (math.pi / 180) * degrees # The equation to find the radian
length = round(height / math.sin(radians), 2) # The equation to find the needed length of the ladder
# Print the length of the ladder
print("length the ladder will need to be: ", length)
main() | true |
326c7997a605b2a681185f98f76b309ae2548e58 | src053/PythonComputerScience | /chap5/avFile.py | 602 | 4.28125 | 4 | #program that will count the number of words in a sentence from within a file
def main():
#get the name of file
fname = input("Please enter the name of the file: ")
#open the file
infile = open(fname, "r")
#read in file
read = infile.read()
#split the sentence into a list
split = read.split()
#count the length of the split list
length = len(split)
count = 0
#loop through each word and count the len
for w in split:
for i in w:
count = count + 1
#calculate average
av = count / length
#print the average
print("The average word length is: {0:0.2f}".format(av))
main() | true |
e200b43b7d728635cf1581cf5eb4fcde4729bff6 | src053/PythonComputerScience | /chap3/slope.py | 985 | 4.3125 | 4 | # This program will calculate the slope of to points on a graph
# User will be required to input for var's x1, x2, y1, y2
import math
def slope(x1, x2, y1, y2):
return round((y2 - y1)/(x2 - x1)) #Calculate and return the slope
def distance(x1, x2, y1, y2):
return round(math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)), 2)
def main():
print("This program takes to points on a graph and finds the slope")
print()
x1 = eval(input("Enter the x1 location: ")) #prompt for x1 location
y1 = eval(input("Enter the y1 location: ")) #prompt for y1 location
x2 = eval(input("Enter the x2 location: ")) #prompt for x2 location
y2 = eval(input("Enter the y2 location: ")) #prompt for y2 location
choice = eval(input("If you want the slope type 1 type anything else for the distance: ")) #prompt user for what equation they want done
if choice == 1:
s = slope(x1, x2, y1, y2)
print("The slope is: ", s)
else:
d = distance(x1, x2, y1, y2)
print("The distance is: ", d)
main() | true |
90873ee519d41e877adbe3037d7fcd9b5e0b7e96 | src053/PythonComputerScience | /chap3/easter.py | 467 | 4.125 | 4 | # This program will take the year a user inputs and output the value of easter
def main():
print("This program will figure out the epact for any given year")
year = eval(input("Input the year you would like to know the epact of: "))
#Equation to figure out integer division of C
C = year//100
#Equation to figure out epact
epact = (8 + (C // 4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30
#Display the epact
print("The epact is: ", epact)
main() | true |
26870cc55f6e78c2d25cc09b9119491abdef8434 | src053/PythonComputerScience | /chap2/convert.py | 331 | 4.28125 | 4 | #A program to convert Celsius temps to Fahrenheit
def main():
print("This program will convert celsius to farenheit")
count = 0
while(count < 5):
celsius = eval(input("What is the Celsuis temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degree Fahrenheit.")
count += 1
main() | true |
f40123af7ffca03d3d4184aa3fcf131f7f8f2ce4 | Kdk22/PythonLearning | /PythonApplication3/exception_handling.py | 2,688 | 4.21875 | 4 | # ref: https://docs.python.org/3/tutorial/errors.html
while True:
try:
x = int(input('Please enter a number: '))
break
except ValueError:
print('Ooops ! THat was no valid number. Try agian..')
''' If the error type matches then only in displays message.
If the error type is not matched then it is passed to outer
try statements, if no handler is found to handle that
statement then it is unhandled exception and execution
stops
'''
''' Therefore you can add more than one except clause in try statement
except (RuntimeError , TypeError, NameError):
pass
'''
# I didn't understood this
class B(Exception):
print('It\'s B')
pass
class C(B):
print('It\'s C that extracts B')
pass
class D(C):
print('It\'s D that extracts C')
pass
for cls in [B,C,D]:
try:
raise cls()
except B:
print('B')
except D:
print('D')
except C:
print('C')
'''
THis is the real way of doing exception handling
if name of the error is not given then it works as
wildcard(means it handles all the exception.).
'''
import sys
try:
with open('D:\Visual Studio 2017\Repos\PythonApplication3\PythonApplication3\exception_test.txt') as f:
s= f.readline()
i= int(s.strip()) # strip() returns the copy of string in which the defined characters are stripped from beginning and end.
except OSError as err:
print('OS Error: {0}'. format(err))
except ValueError:
print('Could not convert data to integer.')
except:
print('Unexcepted Error: ', sys.exc_info()[0])
raise
'''
sys.exc_info gives information about the exception that is
currently being handled in the format (type, value, traceback)
'raise' displays the class object of error along with value
'''
#Check
import sys
try:
a= 1/0
c= '!!!cat!!!'
b= int(c.strip('!'))
except:
print('Unexceptied Error ', sys.exc_info()[0])
# raise
try:
raise Exception('spam','eggs') # associated value or exception's argument
except Exception as inst: # inst is variable that represents exception instance
print(type(inst)) # and the exception instance is bound to instance.args , type() returns the type of variable
print(inst.args) #__str__ allows args to be printed as we know that print executes __str__()
print(inst) # but may be overwrritten
x, y = inst.args #unpack args
print('x =', x)
print('y =', y)
# even functions can be called indirectly
def this_fails():
x =1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err)
| true |
bb52036b8bf49eb4af098c7f2025fce8080316d8 | Kdk22/PythonLearning | /PythonApplication3/class_var_and_instance_var.py | 1,005 | 4.5625 | 5 |
class foo:
x='orginal class'
c1,c2 = foo(), foo()
''' THis is creating the multiple objects of
same as
c1 = foo()
c2 = foo()
and these objects can access class variable (or name)
'''
print('Output of c1.x: ', c1.x)
print('Output of c2.x: ', c2.x)
'''
Here if you change the c1 instance, and it will
not affect the c2 instance
'''
c1.x = 'changed instance'
print('Output of c1.x: ',c1.x)
print('Output of c2.x: ',c2.x)
'''
But if I change the foo class, all instances of that
class will be changed
'''
foo.x = 'Changed class'
print('Output of c1.x: ',c1.x)
print('Output of c2.x: ', c2.x)
'''
Now using 'self'
Here Changing the class does not affect the instances
'''
class foo:
def __init__(self):
self.x = 'Orginal self'
c1 = foo
foo.x ='changed class'
print('Output of instance attributes: ', foo.x)
print('Output of self: ',c1.x)
# ref: https://stackoverflow.com/questions/1537202/variables-inside-and-outside-of-a-class-init-function | true |
b6417cda68e6efe3792e317980cbbdb923a5cb63 | vohrakunal/python-problems | /level2prob4.py | 806 | 4.375 | 4 | '''
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out .
You are given a string . Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character '' with in the string.
For a better understanding of the problem, check the explanation.
Input Format
A single line of input consisting of the string .
Output Format
A single line of output consisting of the modified string.
Constraints
All the characters of denote integers between and .
Sample Input
''''
########## Solution ################
from itertools import groupby
S = str(raw_input())
T = [list(g) for k, g in groupby(S)]
for i in T:
print (len(i), int(i[0])),
| true |
61d217ee89bf72920f370c96b6554d675a4c035e | steveiaco/COMP354-Team-E | /Functions/pi.py | 1,320 | 4.125 | 4 | # Goal: Calculate pi to the power of a given variable x
# Author: Ali
from Functions.constants import get_pi
# Pie Function
# Using Table Method
# I have basically created a global variable for PIE and its power
PIE = get_pi()
# the index (n) of the dictionary represent PIE**(10**n)
PIE_Dictionary = {
-5: 1.000011447364379,
-4: 1.0001144795408674,
-3: 1.001145385339187,
-2: 1.0115130699114478,
-1: 1.1212823532318632,
0: 1,
1: PIE,
2: 93648.04747608298,
3: 5.187848314319592e+49
}
def pi_function(args):
x = 0
# check if
if len(args) == 1:
x = args[0]
else:
raise Exception(
f"Invalid number of arguments, pie expected 1 argument but got "
f"{len(args)} arguments.")
negative_exponent = False
if float(x) < 0:
negative_exponent = True
x = float(x) * -1
exponent = list(str(float(x)))
decimal = list(str(float(x))).index('.')
n = 1.0
for i in range(len(exponent)):
power_level = decimal - int(
i) # power_level give us the index of PIE_Dictionary
if power_level != 0:
j = int(exponent[i])
for k in range(j):
n = n * PIE_Dictionary[power_level]
if negative_exponent:
return 1 / n
return n
| true |
2dd449e8b85f1814e6c857a1e411936f21ea6c09 | verjavec/guessing_game | /game.py | 1,217 | 4.25 | 4 | """A number-guessing game."""
import random
# Put your code here
# Greet the player
name = input("Please enter your name: ")
print (f'Hello {name}!')
#choose a random number
numbertoguess = random.randrange(1,100)
print(numbertoguess)
keep_guessing = True
num_guesses = 0
#repeat this part until random number equals the guess
#ask player to input a number from 1-100
#check if input number is equal to random number
while keep_guessing:
str_guess = input("Please choose a number between 1 and 100: ")
guess = int(str_guess)
if guess == numbertoguess:
num_guesses += 1
print(f'Congratulations {name}! You guessed the number in {num_guesses} tries!!!')
#increase number of guesses
keep_guessing = False
#if random number is not equal to input number, is it higher?
elif guess > numbertoguess:
print(f'Too high! Try a lower number, {name}.')
num_guesses += 1
elif guess < numbertoguess:
print(f'Too low! Try a higher number, {name}.')
num_guesses += 1
#if random number is not equal to or higher, it must be lower
#give user a hint
#once random number equals the guess, congratulate the user.
| true |
946d079c682179d1e5b09bfeed6ae36a23045eae | inwk6312winter2019/week4labsubmissions-deepakkumarseku | /lab5/task4.py | 762 | 4.34375 | 4 | import turtle
class rectangle():
"""Represents a rectangle.
attributes: width, height.
"""
class circle():
"""Represents a circle.
attributes: radius.
"""
radius=50
def draw_rect(r):
""" Draws a rectangle with given width and height using turtle"""
for i in range(2):
turtle.fd(r.width)
turtle.lt(90)
turtle.fd(r.height)
turtle.lt(90)
def draw_circle(c):
"""Draws a circle with given radius using turtle"""
turtle.circle(c.radius)
def main():
r = rectangle()
r.width=50
r.height=200
c = circle()
c.radius=50
print(draw_rect(r))
turtle.reset()
print(draw_circle(c))
turtle.mainloop()
if __name__ == '__main__':
main()
| true |
8f2e39d178be9670253ca98d275cc549226b6971 | williamstein/480_HW2 | /simple_alg.py | 1,050 | 4.15625 | 4 | print "Hello"
import math
#computes the probability of the binomial function in the specified range inclusive
#min, max are the values for the range
#n is the total population
#p is the success probability
def binom_range(min, max, n, p):
if(min > max):
raise Exception("Please pass a valid range")
if(min < 0):
raise Exception("The minimum must be positive")
if(max >n):
raise Exception("The maximum cannot exceed the total population")
current = min
total = 0
while(current <= max): #go through and add up all the probabilities
total+= binom(current, n,p)
current = current+1
return total
def binom(x, n, p):
coeff = math.factorial(n) / (math.factorial(x)*math.factorial(n-x))
return coeff*(p**x)*((1-p)**(n-x))
#examples
# We want the probability that a binomial with population of 2 and success probability of .5
#for 0<= x <= 1
x = binom_range(0,1,2,.5)
print x # should print .75
x = binom_range(10,15,20, .7)
print x
| true |
5bc42f93d4da19adc21bc675f5cfa6aec78411a7 | tianxiongWang/codewars | /sum.py | 484 | 4.15625 | 4 |
# >Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.
# 其实就是把a到b之间的数求和,太简单了
def get_sum(a,b):
if a == b:
return a
if a < b:
sum = 0
for num in range(a, b+1):
sum += num
else:
sum = 0
for num in range(b, a+1):
sum += num
return sum
| true |
32699826b747b0009a4313fb427fda5a4ac7ef79 | Kallol-A/python-scripting-edureka | /Module 3/Case1/commavalues.py | 641 | 4.1875 | 4 | #Write a program that calculates and prints the value according to the given formula:
#Q = Square root of [(2 * C * D)/H]
#Following are the fixed values of C and H: C is 50. H is 30.
#D is the variable whose values should be input to your program in a comma- separated sequence.
#Let us assume the following comma separated input sequence is given to the program:
#100,150,180
#The output of the program should be:
#18,22,24
import math
from math import sqrt
values=input("Enter Comma seprated values").split(",")
print(values)
Q=[]
for i in values:
Q.append((int(math.sqrt((100 * int(i) )/30))))
print (*Q,sep=",")
| true |
58a0e3ca5ac367b7b994450b49fc7fc3a6c664ad | Alainfou/python_tools | /prime_list.py | 2,134 | 4.1875 | 4 | #!/usr/bin/python
import math
import sys
import getopt
print "\n\tHey, that's personal! That's my very, very personal tool for listing prime numbers! Please get out of here! =(\n"
dat_prime_list = [2,3]
def its_prime (p):
s = int(math.sqrt(p))+1
for i in dat_prime_list :
if (p%i) == 0:
return False
return True
def yeah (argv):
try:
opts, args = getopt.getopt(argv,"n:l:")
except getopt.GetoptError:
print 'prim.py -n <number_until_which_primes_shall_be_listed>'
sys.exit(2)
until_there = 42
based_on_prime_limit = False
list_length = 42
based_on_list_length = False
p = 5
for opt, arg in opts:
if opt == '-n':
based_on_prime_limit = True
try:
until_there = int(arg)
except ValueError:
print 'Invalid argument. Limit will be set to 42, which is a totally arbitrary and random number.'
elif opt == '-l':
based_on_list_length = True
try:
list_length = int(arg)
except ValueError:
print 'Invalid argument. Length will be set to 42, which is a totally arbitrary and random number.'
if based_on_prime_limit :
while (p < until_there):
if its_prime (p):
dat_prime_list.append(p)
p+=2
print 'Fine... Here are your prime numbers until ',until_there
elif based_on_list_length :
while (len(dat_prime_list)<list_length):
if its_prime (p):
dat_prime_list.append(p)
p+=2
print 'Fine... Here are your ',list_length,' prime numbers.'
print dat_prime_list
if __name__ == "__main__":
yeah(sys.argv[1:])
| true |
2a378d9c0099652c3f74f22fa67311636d6d477a | geraldo1993/CodeAcademyPython | /Strings & Console Output/String methods.py | 614 | 4.4375 | 4 | '''Great work! Now that we know how to store strings, let's see how we can change them using string methods.
String methods let you perform specific tasks for strings.
We'll focus on four string methods:
len()
lower()
upper()
str()
Let's start with len(), which gets the length (the number of characters) of a string!
Instructions
On line 1, create a variable named parrot and set it to the string "Norwegian Blue". On line 2, type len(parrot) after the word print, like so: print len(parrot). The output will be the number of letters in "Norwegian Blue"! '''
parrot="Norwegian Blue"
print len(parrot)
| true |
d3b8a54fca1ec8f724ec1a2de1a81f952c0368d7 | ohwowitsjit/WK_1 | /2.py | 201 | 4.125 | 4 | num_1 = int(input("Enter the first number: "));
num_2= int(input("Enter the first number: "));
product=0;
for i in range(0, num_2):
product=product+num_1;
print("Product is:", str(product)); | true |
2db6a8ca529a72823ce4e7ba45cfcb050ff830bd | puneet672003/SchoolWork | /PracticalQuestions/06_question.py | 358 | 4.28125 | 4 | # Write a Python program to pass a string to a function and count how many vowels present in the string.
def count_vowels(string):
vowels = ["a" ,"e", "i", "o", "u"]
count = 0
for char in string:
if char.lower() in vowels:
count += 1
return count
print(f"Total vowels : ", count_vowels(input("Enter string : "))) | true |
6647ec2418ab875585ed562ceeea49a6bd1c9746 | puneet672003/SchoolWork | /PracticalQuestions/03_question.py | 411 | 4.40625 | 4 | # Write a python program to pass list to a function and double the odd values and half
# even values of a list and display list element after changing.
def halfEven_doubleOdd(arr):
for i in range(len(arr)):
if arr[i] % 2 == 0:
arr[i] = arr[i]/2
else :
arr[i] = arr[i]*2
lst = eval(input("Enter list : "))
halfEven_doubleOdd(lst)
print(f"Final list : {lst}") | true |
d1fff6ff6f5f6c089029a521907eb1fe14a9680c | erin-koen/Whiteboard-Pairing | /CountingVotes/model_solution/solution.py | 1,377 | 4.28125 | 4 | # input => array of strings
# output => one string
# conditions => The string that's returned is the one that shows up most frequently in the array. If there's a tie, it's the one that shows up most frequently in the array and comes last alphabetically
# sample input => input: ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael'];
# expected output: 'michael'
# strategy: loop through array and add names to a dictionary. If name not in dictionary, dictionary[name]: 1, else dictionary[name]+=1
#this'll provide a count
# loop through dictionary, declare two variables - count and winner. If dictionary[key]:value >= count, value = count and winner = key
def counting_votes(arr):
vote_dict = {}
for name in arr:
if name not in vote_dict:
vote_dict[name] = 1
else:
vote_dict[name] = vote_dict[name] + 1
count = 0
winners = []
# figure out the largest number of votes
for value in vote_dict.values():
if value > count:
count = value
# find the name(s) of the people who got that many votes
for key in vote_dict.keys():
if vote_dict[key] == count:
winners.append(key)
return sorted(winners, reverse=True)[0]
print(counting_votes(['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael'])) | true |
4c051300bade9b496dcb31f81376b704a82f84eb | fionnmcguire1/LanguageLearning | /PythonTraining/Python27/BattleShip_medium.py | 1,815 | 4.1875 | 4 | '''
Author: Fionn Mcguire
Date: 26-11-2017
Description:
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
'''
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
numBattleships = 0
for line in xrange(len(board)):
for element in xrange(len(board[line])):
if board[line][element] == 'X':
if line != 0:
if board[line-1][element] != 'X':
if element != 0:
if board[line][element-1] != 'X':
numBattleships+=1
else:
numBattleships+=1
else:
if element != 0:
if board[line][element-1] != 'X':
numBattleships+=1
else:
numBattleships+=1
return numBattleships
| true |
a6d0f86a9c77d54bec821e91a665522357466cf5 | Dallas-Marshall/CP1404 | /prac_01/electricity_bill_estimator.py | 719 | 4.15625 | 4 | # Electricity Costs
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
electricity_cost = 0
# Define Menu:
MENU = """Please select tariff;
Tariff(11)
Tariff(31)"""
# Display Menu
print(MENU)
# Ask user to select menu option
user_choice = int(input(">>> "))
# Define relevant electricity cost
if user_choice == 31:
electricity_cost = TARIFF_31
else:
electricity_cost = TARIFF_11
# Daily use in kWh
daily_use = float(input("What is your daily usage in KWh: "))
# Number of days in the billing period
billing_period = int(input("How many days are in the billing period? "))
# Calculate bill total
bill_total = electricity_cost * daily_use * billing_period
print("Your estimated bill is: ${:.2f}".format(bill_total))
| true |
306684db850ddb2a45b4b554a8a4f940b9322151 | EtienneBauscher/Classes | /student.py | 1,970 | 4.1875 | 4 | """'student.py' is a program that computes the following:
1. The average score of a student's grades.
2. It tests whether a student is a male or a female.
The program utilises a class called Student
The class hosts various fucntions for the computation of the needed outcomes.
"""
class Student(object):
"""class 'Student' hosts the following variables:
a. age - for the student's age
b. name - for the name of the student.
c. gender - for the gender of the student
d. grades - for the grades of the student
"""
# initialise the class through the constructor
def __init__(self, age, name, gender, grades):
self.age = age
self.name = name
self.gender = gender
self.grades = grades
def compute_average(self):
"""this function calculates the average of the student's scores"""
# utilise the class variables in the list to compute
average = sum(
self.grades)/len(self.grades)
print("The average for student " +
str(self.name) + " is " + str(average)) # print the results
def check_if_male(self):
"""'check_if_male()' checks whether a student is male or not and
prints "True" if yes and "False" if no"""
# use a conditional to check if the gender is male
if self.gender == "Male":
print("True")
else:
print("False")
# three students
MIKE = Student(20, "Philani Sithole", "Male", [64, 65])
SARAH = Student(19, "Sarah Jones", "Female", [82, 58])
ETIENNE = Student(43, "Etienne Bauscher", "Male", [99, 99])
# run a couple of checks on the newly added check_if_male() method
ETIENNE.check_if_male()
ETIENNE.compute_average()
SARAH.check_if_male()
MIKE.check_if_male()
# create a new list
# run a for loop through the list calling the functions
NEWLIST = [ETIENNE, SARAH, MIKE]
for i in NEWLIST:
Student.check_if_male(i)
Student.compute_average(i)
| true |
532d90e13e03f6af7ef54e45544688a5ef934009 | ghostassault/AutomateTheBoringWithPython | /Ch7/RegEx.gyp | 2,277 | 4.375 | 4 | #The search() method will return a match object of the first matched text in a searched string
#1 Matching Multiple groups with the pipe
import re
heroR = re.compile(r'Batman|Tina Fey')
mo1 = heroR.search('Batman and Tina Fey.')
print(mo1.group())
#2 Optional Matching with the Question Mark
batRe = re.compile(r'Bat(wo)?man')
mo1 = batRe.search('The adventures of Batman')
print(mo1.group())
# The (wo)? part of the regular expression means the pattern wo is an optional group
batRe = re.compile(r'Bat(wo)?man')
# The regex will match text that has "zero" ie one instance of wo in it.
mo1 = batRe.search('The adventures of Batwoman, and Batman')
print(mo1.group())
# Using Regex to look for phone numbers that do or do not have an area code
phoneRe = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo1 = phoneRe.search('My number is 415-555-4242')
print(mo1.group())
#Match 0 or 1 of the group preceding this question mark. Questions (?) marks can be escaped with \?
mo2 = phoneRe.search('My number is 412-4565')
print(mo2.group())
#3 Matching zero or more with the Star. * means to match zero or more
batRe = re.compile(r'Bat(wo)*man')
mo1 = batRe.search('The adventures of Batman Batgirl')
print(mo1.group())
batRe = re.compile(r'Bat(wo)*man')
mo4 = batRe.search('The adventures of Batwowowowowowowoman')
print(mo4.group())
#4 Matching one or more with the plus
batRe = re.compile(r'Bat(wo)+man')
mo1 = batRe.search('The adventures of Batwowowoman')
print(mo1.group())
# The group preceding the plus must appear at least once
batRe = re.compile(r'Bat(wo)+man')
mo2 = batRe.search('The adventures of Batman')
print(mo2 == None )
# Matching specific repetitions with Curly Brackets
#If you have a group that you want to repeat a specific number of times, follow the group in your regex wit h number in curly brackets.
haRe = re.compile(r'(Ha){3}')
mo1 = haRe.search('HaHaHa')
print(mo1.group())
#Here, (Ha){3} matchers 'HaHaHa' but not 'Ha'. Since it doesnt match 'Ha 3', serach() returns None
mo2 = haRe.search('Ha')
mo2 == None
print(mo2)
#Greedy and Nongreedy matching
greedyHaRe = re.compile(r'(Ha){3,5}')
mo1 = greedyHaRe.search('HaHaHaHaHa')
print(mo1.group())
nonegreedyHaRe = re.compile(r'(Ha){3,5}?')
mo2 = nonegreedyHaRe.search('HaHaHaHaHa')
print(mo2.group())
| true |
db7cd6a5237bdfca4a0622c10b1cdd3ddb430bf8 | jinshanpu/lx | /python/func.py | 280 | 4.125 | 4 | print "the prog knows which number is bigger"
a=int(raw_input("Number a:"))
b=int(raw_input("Number b:"))
def theMax(a, b=0):
'''Prints the maximun of two numbers.
the two values must be integers'''
if a>b:
return a
else:
return b
print theMax(a, b)
print theMax.__doc__
| true |
e2e6f661dece58eb23e84de878e866878d54d295 | franklinharvey/CU-CSCI-1300-Fall-2015 | /Assignment 3/Problem1.py | 251 | 4.125 | 4 | #Franklin Harvey
#Assignment 3
#Problem 1
#TA: Amber
fullName = raw_input("What is your name in the format Last, First Middle? ")
comma = fullName.find(",")
lastName = fullName[0:comma]
#print lastName
print fullName [comma + 2:len(fullName)] + " " + lastName | true |
1398a66b86aca613a6dbb7ba5c534615e14348cc | ShreyasAmbre/python_practice | /PythonPracticeQuestion2.0/PythonProgram_2.3.py | 432 | 4.1875 | 4 | # WAP to add 'ing' at the end of a given string (length should be at least 3). If the given
# string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3,
# leave it unchanged.
s = "playing"
ls = list(s)
if len(s) > 3:
estr = "ing"
ostr = s[-3:]
if estr == ostr:
nstr = "ly"
newls = s.replace(ostr, nstr)
print(newls)
else:
print(s)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.